Jest 22: Refinements & Custom Runners
Сьогодні ми анонсуємо нову версію Jest, в якій вдосконалено майже всі частини Jest з метою забезпечення міцнішої бази для тестування. Разом зі спільнотою, ми внесли широкий ряд змін, які допоможуть вам отримати більше від Jest. We are also graduating the custom runners feature out of the experimental stage and added a new package, jest-worker, for parallelizing work across multiple processes. We have compiled a list of highlights below but make sure to check out the (as always) massive changelog.
Good bye Node 4 & welcome JSDOM 11
Цього релізу ми припиняємо підтримку Node 4, головним чином тому, що завершує їх підтримку одна з наших головних залежностей JSDOM. Jest now comes out of the box with JSDOM 11 which features better support for SVGs, requestAnimationFrame, URL and URLSearchParams built in, and much more.
Custom Runners + Easy parallelization with jest-worker
В Jest 21 ми представили концепцію користувацьких виконавців Jest. Since then, Rogelio, one of Jest's core contributors, built a number of useful runners: If you have many existing tests written using another framework but you'd like to immediately benefit from Jest's features, check out jest-runner-mocha. If you have a large codebase that needs linting, you may get a significant speedup if you run eslint within Jest using jest-runner-eslint.
Щоб отримати глибинний контроль над важкими завданнями паралелізації (наприклад, перетворення файлів або спостереження за файловою системою), ми розробили нову відповідну бібліотеку. We developed a modern, Promise-based module with an approachable API, called jest-worker, that allows you to delegate to child processes those intensive functions. As jest-worker, like any other Jest package, is a part of the Jest platform, you can use it however you like even without ever using Jest itself. You'll find more in the documentation here.
To get a better understanding of custom runners and Jest as a platform, make sure to check out Rogelio's talk from Reactive Conf 2017: Jest as a Platform.
Код фрейму в тестових помилках
Щоб легше визначити, яке твердження є провальним для вашого тесту, ми додали код фрейму, який показує твердження, що має допомогти сфокусуватися на вашому коді. Приклад тесту:
test('some test', () => {
function someFunctionWhichShouldThrow() {
if (false) {
throw new Error();
}
return 'success!';
}
expect(someFunctionWhichShouldThrow).toThrow();
});
В Jest 21, ми виводили наступну помилку:

В Jest 22, ми додали код фрейму, який дає більше контексту провальному твердженню. Ми також очистили стекові сліди, частково прибравши безлад.

Полегшене тестування помилок в асинхронному коді
You can now use toThrow and toThrowErrorMatchingSnapshot on promise rejections in the same way you can on synchronous errors.
async function throwingFunction() {
throw new Error('This failed');
}
test('asynchronous rejection', async () => {
await expect(throwingFunction()).rejects.toThrowErrorMatchingSnapshot();
});
Асинхронні тестові середовища
When Puppeteer, a way of programmatically interacting with a real Chromium Browser, was announced by the Google Chrome team in August, many wanted to be able to use Jest to write their tests running them in Chrome. Спільнота допомогла нам зробити це можливим завдяки асинхронному тестовому середовищу. We are still working on making this experience as good as possible, but please see this guide for how to use Puppeteer with Jest, starting today.
Експериментальна діагностика витоку
We added an experimental --detectLeaks setting to Jest that will let you know if your internal environment instance is leaked after a test execution. Також буде попередження, коли ваш набір тестів вимагає файл після завершення тесту; це означає, що ви не дочекались всіх асинхронних операцій або залишили щось, що не було належним чином очищено. This will however not discover leaks in user land code, only in test land code; although the technology used behind it can help you (see jest-leak-detector). If you are reporting a bug about Jest's memory usage, please provide a repro where --detectLeaks will make the test suite fail. We started building a better sandboxing mechanism for Jest but it's not ready yet to be enabled by default. Якщо ви хотіли б допомогти, будь ласка, зв'яжіться з нами через discord!
Покращення режиму спостереження
When using watch mode, there is now a way to focus only on tests that previously failed. В цьому режимі Jest не буде повторно запускати успішні тести, що повинно допомогти вам усунути всі проблеми в тестах. Additionally, we added a plugin system to watch mode. By adding modules to watchPlugins in your configuration you can extend the features of the watch mode.
Підтримка Babel 7
Jest використовує Babel, щоб робити покриття коду та покращені функції імітації. Jest 22 також підтримує майбутній Babel 7. You'll find more in the documentation here.
Вдосконалення фу нкцій-імітацій
Jest 22 вносить декілька змін в функції-імітації, що робить їх ще простішими. Firstly, we added a mockName property allowing you to name your mocks, which is useful in assertion failures. We have also made the Jest mock function serializable in pretty-format, meaning that you can snapshot test mocks. In Jest 21, expect(jest.fn()).toMatchSnapshot() would serialize to [Function], in Jest 22, you might get something like this:
test('my mocking test', () => {
const mock = jest.fn().mockName('myMock');
mock('hello', {foo: 'bar'});
expect(mock).toMatchSnapshot();
});
// Serializes to:
exports[`my mocking test 1`] = `
[MockFunction myMock] {
"calls": Array [
Array [
"hello",
Object {
"foo": "bar",
},
],
],
}
`;
Деталі Jest 21
Jest 21 був випущений у вересні, і ми, на жаль, не випустили відповідний допис. Тож тримайте короткий огляд основних змін версії 21:
- Use expect and jest-mock in the browser: Michael Jackson donated his excellent
expectpackage to the Jest project. As part of that transition, the Jest core team, with much help from Kenneth Skovhus, made bothjest-matchers(renamed toexpect) andjest-mockwork in browsers. This means that while you cannot use Jest itself in browsers (yet), you can use its awesome assertions and mocks for instance as replacements for Chai and Sinon running in Mocha tests. If you are migrating from earlierexpectto the new Jest-poweredexpect, you can usejest-codemodsto automate the migration. - MIT License: We changed Jest's license to MIT. Yay!
- Fail test suites on async errors: Jest used to have a bug that made it crash when errors were thrown in certain parts of async code. Це було виправлено розробниками спільноти.
- Faster startup: With Jest 21 we fine tuned Jest's startup to be more than 50% faster. Для малих тестів завжди були проблемою великі витрати часу Jest, але тепер це не має стримувати вас від використання Jest.
Jest Community
Спільнота Jest тяжко працює, щоб забезпечувати ще кращий досвід тестування. Це окремі проєкти від основного Jest, але ми хочемо виділити деяких наших особистих улюбленців.
- jest-image-snapshot – custom matcher to compare images with snapshots by American Express developers
- ts-jest – all you need to successfully run Jest within TypeScript project by @kulshekhar
- jest-codemods – migrate your tests from other frameworks to Jest with ease
- jest-plugins – a new community project oriented around simplifying setting up test environment for specific tools, like React, or providing some handy utilities
We'd also like to announce that recently we launched a new place for high quality Jest additions – jest-community. It's a new GitHub organization already featuring our favorite projects, like vscode-jest, jest-extended, to name a few, curated by Jest maintainers and collaborators. We've even migrated our eslint-plugin-jest there, and already see some great contributions, which are published independently at a faster pace.

Спільні проєкти єдиної організації є чудовим способом експериментувати в таких речах, як автоматизований реліз, який ми б хотіли розглянути в контексті Jest. Вони також дають нам змогу вносити в них однакові речі, як то формат README (дякуємо спільноті webpack за ідею), спрощуючи їх вивчення та використання.
Якщо у вас є щось круте щоб поділитися, ви можете зв'язатися з нами! Ми були б раді розділити з вами ваш проєкт.
