🃏 Jest 19: Immersive Watch Mode & Test Platform Improvements
Сьогодні ми із задоволенням публікуємо версію 19 платформи для тестування Jest. Це найбільший реліз Jest, який ми коли-небудь публікували, і ми дуже раді показати вам, що ми створили за останні два місяці:
Поглиблений режим спостереження
We completely rewrote the watch mode to make it instant and more extensible. В результаті, отримуємо поглиблений досвід використання: тести одразу перезапускаються після змін у файлі та ми полегшили вибір правильних тестів.
Оновлення знімків
Ми зробили декілька змін у форматі знімку. Ми не вносимо такі зміни часто і розглядаємо їх додавання, лише якщо вони дійсно покращать роботу знімків. Так само як додавання номера версії знімку, ми акумулювали ряд змін, які ми вже деякий час хотіли внести до формату:
- We dropped the “test” prefix in snapshot names from top level
testoritcalls. - Ми покращили вивід елементів React, аби отримувати менше змін при змінах властивостей елементу.
- Ми покращили механізм обходження символів для кращої захищеності.
До цього:
exports[`test snap 1`] = `
<header>
<h1>
Jest \"19\"
</h1>
<Subtitle
name="Painless JavaScript Testing" />
</header>
`;
Після (немає префікса "test", кращий JSX рендеринг, заголовок версії):
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`snap 1`] = `
<header>
<h1>
Jest "19"
</h1>
<Subtitle
name="Painless JavaScript Testing"
/>
</header>
`;
Ми вирішили, що прийшов час ввести версії знімків, щоб гарантувати, що всі розробники використовують сумісні версії Jest. Ось як ми попереджаємо вас про необхідність оновлення вашого знімку:

Переконайтеся, що ви скасували всі локальні зміни перед оновленням, аби зробити перехід безпроблемним і переконатись, що жодні небажані зміни від провальних тестів не були додані в нові знімки.
Вдосконалений вивід пропущених тестів
Пропущені тести виводяться єдиним рядком замість виводу кожного окремого тесту при тестуванні в детальному режимі або одному наборі. Сподіваємось, це дозволить вам сфокусуватися на важливих тестах. Також це займає значно менше простору!

Нові аргументи CLI
Jest 19 публікується з двома новими аргументами покриття, які ви можете запустити з командного рядка:
--collectCoverageFrom--coverageDirectory
Тепер ми також виводимо неприпустимі аргументи CLI, не ігноруючи їх. But we've got your back with helpful error message like the one below, e.g. when you try running jest --watc:

expect Improvements
We're close to almost full feature parity with the expect npm package. Michael Jackson, the author of the package, agreed to donate it to the Jest project, which means that jest-matchers will be renamed to expect. Since our version of expect is not intended to be fully compatible, Christopher Chedeau is working on a codemod to make the transition painless. Christopher also worked on a number of improvements to jest-matchers which enables it to be used outside of Jest and even works inside browsers.
eslint-plugin-jest – our very own ESLint plugin
Thanks to Jonathan Kim Jest finally has its own official ESLint plugin. Він містить три правила:
- no-disabled-tests - this rule prevents you from accidentally committing disabled tests.
- no-focused-tests - this rule prevents you from committing focused tests which would disable all other tests in the same suite.
- no-identical-title - disallows identical titles in test names.
You can install it using npm install --save-dev eslint-plugin-jest or yarn add --dev eslint eslint-plugin-jest and it can be enabled by adding {"plugins": ["jest"]} to your eslint configuration.
New public package: jest-validate
Коли ми переробили код перевірки та нормалізації для конфігурації Jest, ми були настільки задоволені новими повідомленнями про помилки, що ми виділили його в окремий модуль, щоб поділитися з іншими. With Jest 19 we welcome jest-validate to our self-sustained packages family.
jest-validate is a generic configuration validation tool that helps you with warnings, errors and deprecation messages in your JavaScript tool. Він також здатен показувати зручні для користувачів приклади правильних налаштувань та надає простий, але потужний API. Сподіваємось, це стане гарним доповненням до ваших проєктів!

We're happy to announce that jest-validate is validating config options of prettier since v0.12. Додавайте його до свого проєкту, спробуйте, надішліть нам відгук та допомагайте з покращенням, роблячи запити на ухвалення змін на GitHub.
Вдосконалені асиметричні матчери
Ми перемістили асиметричну реалізацію матчерів з Jasmine в Jest, що дало змогу надалі покращувати користувацький досвід. As a result, asymmetric matchers are now pretty-printed nicely, we added the new expect.stringContaining() matcher and we also paired them with expect.toMatchObject() so you can use the best of both:

Кращі ручні імітації
З останнім релізом, ручні імітації нарешті працюють з вкладеними каталогами. For example __mocks__/react-native/Libraries/Text/Text.js will now work as expected and mock the correct module. We also fixed issues with virtual mocks and transitive dependencies and improved moduleNameMapper to not overwrite mocks when many patterns map to the same file.
Важливі Зміни
As a part of our cleanups and fixes we removed the mocksPattern configuration option which was never officially supported. We also renamed the testPathDirs configuration option to roots which better explains what the option can be used for. The default configuration for roots is ["<rootDir>"] and can be customized to include any number of directories. Параметр конфігурації rootDir завжди використовув ався в основному як маркер для інших параметрів, тож це перейменування має зробити процес налаштування Jest зрозумілішим.
Оновлена документація
As you may have already seen, Hector Ramos and Kevin Lacker gave Jest's documentation a fresh new look. Ми змінили спосіб організації сайту, тепер Документація та API представлені окремими сторінками:
- Under Docs you can find an introduction to Jest, including Getting Started or Testing Asynchronous Code and handy guides like Snapshot Testing, Testing React Native App, Using with webpack or Migrating to Jest and many more!
- The API section on the other hand lists all available methods exposed by Jest: the
expectandjestobjects, mock functions, globals, along with configuration options from package.json and from the CLI.
The homepage was completely redesigned to be more descriptive of what Jest is about: “Zero configuration testing platform”. Ми також переконані, що новий вигляд зручніший для мобільних пристроїв. And for those using RSS – we finally provide a feed for our blog.
Оновлення спільноти
- We really loved this talk: “Introduction to Jest“ by Vas Boroviak.
- Follow @jestjs_ on Twitter.
- Команда Jest Core збирається раз на тиждень, щоб обговорити поточні та майбутні проблеми. Якщо ви б хотіли працювати над Jest, надішліть нам декілька запитів на злиття і приєднуйтеся до наших щотижневих командних зустрічей.
- The awesome engineers at Artsy wrote about Jest as part of their 2017 frontend stack.
- Stephen Scott wrote a detailed article about testing React components in which he weighs the pros and cons of different approaches.
- Using Jest with vue.js got a lot easier after reading Cristian Carlesso's blog post.
- Michele Bertoli wrote a book about React Design Patterns and Best Practices which features an entire section about Jest.
- Improved
--notifycommand that shows an operating system notification which can now also re-run tests from the notification. Насправді це просто функція Jest, ми просто перевіряємо, чи ви все ще читаєте цей допис. - Jest is now part of react-boilerplate.
- Read about the hidden powers of Jest's matchers.
Finally, we are happy to announce that the ava test runner has adopted parts of the Jest platform and is now shipping with basic snapshot support and is using pretty-format. Об'єднання тестової інфраструктури спрощує вивчення тестування додатків і дає нам змогу діл итися найкращими практиками. Ми з нетерпінням очікуємо побачити, чого ми можемо навчитись з наявних тестових бібліотек в майбутньому.
The full changelog can be found on GitHub. Jest 19 was a true JavaScript community effort with 17 people who contributed to this release. Ми дякуємо кожному з вас за вашу допомогу в покращенні цього проєкту.
This blog post was written by Rogelio Guzman and Michał Pierzchała.
