Перейти до основного змісту

Jest 23: 🔥 Неймовірно Швидке Приємне Тестування

· 7 хвилин читання
Ricky Hanlon
Ricky Hanlon

Сьогодні ми з радістю анонсуємо Jest 23, наш найбільший великий реліз станом на сьогодні! Разом із понад 100 учасниками, ми публікуємо купу оновлень та виправлень помилок. Дякуємо всім у спільноті за допомогу в Покращенні JavaScript Тестування.

We would also like to welcome both Babel and webpack to the Jest community! Після переходу з Mocha на Jest 23 Beta, webpack отримав зменшення загального часу виконання тестових наборів в 6 разів, з 13 хвилин до 2 хв 20 секунд. #blazingmeansgood

Ось деякі з Jest 23 новинок і принципових змін.

For a full list see the changelog.

Інтерактивний режим знімка

Ми додали нову опцію меню спостереження за замовчуванням під назвою Інтерактивний режим знімка. Цей новий режим дозволяє вам проходитись через кожен невдалий знімок в кожному провальному наборі, аби переглянути та обрати оновити або пропустити кожен окремо.

Interactive snapshot mode in action

See the Interactive Snapshot Mode docs here.

Матчери властивостей знімків

Часто об'єкти, які ви знімаєте, містять згенеровані значення, такі як дати та ID. Jest тепер дозволяє передавати властивості в матчери знімків, які визначають структуру даних замість конкретних значень. Ці матчери властивостей будуть перевірені перш ніж серіалізувати тип матчера (замість значення), надаючи вам послідовні результати знімків виконання тестів.

Snapshot Property Matchers

See the updated toMatchSnapshot docs or the Property Matcher guide for more information.

Користувальницькі асинхронні матчери

We now support asynchronous matchers with expect.extends! Async matchers return a Promise so that you can await for the matcher to resolve. Для прикладу:

Custom asynchronous matchers in action

Docs available here.

Користувацькі асиметричні матчери

Асиметричні матчери є відмінним інструментом, якщо ви дбаєте тільки про асиметричну рівність. Наприклад, коли ліва сторона повинна бути об'єктом з деяким підмножиною властивостей праворуч замість точного збігу. Jest надає ряд вбудованих асиметричних матчерів, і в цьому релізі ми додаємо користувацькі асиметричні матчери.

Custom asymmetric matchers in action

Jest Each

@mattphillipsio has donated the jest-each package to Jest Core (thanks Matt!). jest-each is a library inspired by mocha-each and Spock Data Tables which allows you to define a table of test cases, and then run a test for each row with the specified column values. We support both array types and template literals for all flavors of describe and test. Docs are available here, and for those not on Jest 23 yet, we're still publishing jest-each separately!

jest-each in action

Huge shout out to Prettier for fixing the table formatting so quickly (see Prettier 1.13)!

Нові матчери

We only add matchers to core if we believe they will be useful to a large amount of people in the Jest community, and leave the majority of matchers to the community (see jest-extended). Деякі матчери потрапили в основний склад з Jest 23:

  • nthCalledWith
  • toReturn
  • toReturnTimes
  • toReturnWith
  • lastReturnedWith
  • nthReturnedWith
  • toStrictEqual

New matchers in action

See the updated expect docs here.

Налагодження зависання тестів

Розповсюджена проблема, яку ми помітили, стосується моменту зависання Jest після виконання тестів. Зазвичай, це стається через програмний код, який залишає відкриті елементи керування, заважаючи завершенню роботи Jest. In the past, users have resorted to --forceExit to fix (not recommended).

Аби допомогти відстежувати подібні проблеми, відтепер ми знаходимо моменти, на яких Jest не завершує свою роботу:

Detecting hanging tests

And we offer a new flag --detectOpenHandles to help find the open handles:

Running detectOpenHandles

See the updated CLI docs here.

Плагіни режиму спостереження

Ми повністю переписали систему режиму спостереження, що дозволить додавати користувацькі плагіни в цей режим. Тепер плагіни режиму спостереження дозволяють підключатись в події Jest та надавати користувацькі опції в Меню режиму спостереження. All of the default Watch Mode prompts are implemented as plugins in this system, and the docs to create your own are available here.

With this change, we're also now able to bring back typeahead support as a Watch Mode Plugin via jest-watch-typeahead!

Typeahead plugin in action

See jest-watch-typeahead for documentation and install instructions. Huge thank you to @rogeliog for the new watch mode plugin system and the jest-watch-typeahead plugin!

Важливі Зміни

Як і в кожному великому релізі, ми здійснюємо кілька змін для внесення більших змін в майбутньому, а також для того, щоб вивести досвід тестування на новий рівень. Ось список найбільших змін:

  • Require test descriptions and functions: We're now failing tests that do not include both a function and a description.
  • Remove undefined props from React snapshots: Smaller snapshots and proper React behavior.
  • Remove deprecations: We removed mapCoverage since it's no longer needed. Additionally, we removed jest.genMockFunction and jest.genMockFn since these are the same as jest.fn.
  • Add snapshot names to failures: We added the snapshot name (if provided) to the snapshot failure message so it's easier to find the snapshot that's failing.
  • Replace mock timestamps: We replaced mock timestamps with invocationCallOrder since two or mocks may often have the same timestamp, making it impossible to test the call order.
  • Add results to mock snapshots: We added mock function call results to snapshots so that both the calls and the results of the invocation are tracked.

Інші покращення

  • Watch mode coverage: Coverage is now limited to only the files tested in watch mode or when using --onlyChanged and --findRelatedTests.
  • Version documentation: We added docs for each minor release back to Jest 22, and have removed all of the “Requires Jest X.X+” from the docs.
  • Better snapshot summaries: We overhauled the Snapshot Summary output to make obsolete snapshots more informative.
  • Better stack traces: We added stack traces to asynchronous errors, timeout errors, expect.assertions, and thrown non-errors. Також ми вказуємо стовпець в коді фрейму!
  • Better React 16 support: Adds snapshot support for React.Fragment, React.forwardRef, and React.createContext.
  • Track mock return and throw values: Adds mock.results that contains the return value or thrown value for each mock call.
  • Blazing 🔥: We've added a blazing badge to the README to indicate that Jest is blazing good.

Саміт Jest

Минулого тижня команда Jest зустрілася на саміті Jest у Facebook, Лондон, де розробляли та випустили Jest 23, оголосивши про Jest Open Collective та виступивши з кількома промовами:

Full talk is available here.

Все пройшло чудово, ми змогли персонально зустрітись з лондонською частиною спільноти. Дякуємо усім, хто долучився, за вашу постійну підтримку! Очікуйте наш наступний допис щодо Jest Open Collective та планів на майбутнє.

As always, this release couldn't have been possible without you, the JavaScript community. Ми безмежно вдячні за можливість покращувати тестування JavaScript разом з вами. If you'd like to contribute to Jest, please don't hesitate to reach out to us on GitHub or on Discord.