Aller au contenu principal

Jest 24 : 💅 Actualisation, polissage, facilité d'utilisation de TypeScript

· 11 minutes de lecture
Simen Bekkhus
Simen Bekkhus

Aujourd'hui, nous sommes heureux de vous annoncer la prochaine version majeure de Jest - la version 24 ! Quatre mois se sont écoulés depuis la dernière version mineure, et huit mois depuis Jest 23. Cette mise à jour est donc importante, et chacun y trouvera son compte ! Parmi les points forts, citons la prise en charge intégrée de TypeScript par la mise à niveau des internes de Jest vers Babel 7, la correction de certains problèmes de longue date concernant l'absence de sortie de la console et les problèmes de performance lors du calcul de diffs importants, ainsi qu'un tout nouveau site Web étincelant. ✨

For a full list of all changes see the changelog.

Nouveau site web

@orta has provided a beautiful redesign of Jest's website, which has been implemented by community members @montogeek and @brainkim.

L'objectif de la refonte était de mettre davantage en évidence ce qui rend Jest génial, et de dissocier l'idée que Jest est principalement un outil pour tester les applications React - vous pouvez utiliser Jest pour toutes sortes de projets et nous voulons que cela soit évident. You can read more about the ideas behind the redesign in this issue.

Prise en charge de TypeScript

Nous avons mis à jour Babel 7 en interne pour Jest 24, qui est fourni avec la prise en charge pour les projets TypeScript. That means Jest can support transpiling TypeScript out of the box, as long as you configure Babel to use it with @babel/preset-typescript. La prise en charge par défaut de TypeScript, similaire à celle de Flow, présente un inconvénient : Babel ne supprimera les annotations de type que pour rendre votre code valide en JavaScript. It will not typecheck your code.

Bien que Jest prenne en charge Babel 7 depuis la version 22 publiée en décembre 2017, il a fallu utiliser un module passerelle afin de s'adapter à la prise en charge de Babel 6 par Jest. In Jest 24 we have migrated entirely over to Babel 7, with great help from community member @milesj. This means that setup is now easier and we can take advantage of other Babel 7 features, such as config loading and automatic modules transpilation. Make sure to remove the babel-core@^7.0.0-bridge.0 as it's not needed now.

If you want to run typechecks while you test, you should use ts-jest. You will need to configure the transformer, as Jest by default applies Babel to .ts (and .tsx) files. Alternatively, you can run tsc or even use a Jest runner to simultaneously transpile your TypeScript whilst running your tests! See jest-runner-tsc for more information.

See the docs for more details.

astuce

If you for whatever reason cannot upgrade to Babel 7, you can still use Jest 24 with babel@6 as long as you keep babel-jest at version 23.

test.todo

Jest 23 had a change that made tests missing an implementation throw instead of being skipped. This change was made due to feedback that accidentally skipped tests were hard to discover and hard to track down. However, this change broke the workflow for quite a few developers who used the feature to sketch out which tests to write.

In Jest 24, we are addressing this issue by adding an explicit test.todo (inspired by the excellent AVA), which will be printed separately in the test summary. It allows you to quickly sketch out which tests you want to write and in the future, an ESLint rule might even be able to warn you that you have forgotten to write out some tests.

test.todo('une entrée invalide doit être levée');

test.todo('les options manquantes doivent être normalisées');

test.todo

Messages d'assertion améliorés

When tests fail, you need to make confident and correct decisions which changes are expected progress and which changes are unexpected regressions. It is especially important not to miss a few regressions hidden among much progress. Jest 24 makes reports when assertions fail more clear and concise for several matchers. Because the effort will continue in Jest 25, you might notice some temporary inconsistencies. If your tests never fail, then you won't get to see them - for the rest of us, it'll be easier to debug why something isn't working as expected. Thanks for the hard work by @ittordepam and other contributors from the community.

You can see these changes across all these PRs: 7621, 7557, 7448, 7325, 7241, 7152, 7125, 7107, 6961.

Examples:

Failing assertion

failing assertion

Type mismatch

different types

Mock function not called

mock functions

Réparation de vieilles douleurs

We've fixed a couple of really old issues in this release.

The first one we'd like to highlight is console.log statements going missing. Jest intercepts and collects all logs in order to give you a stack trace to them, as well as provide them to reporters so you can handle them however you want. However, this has led to an issue where they have simply been missing in certain edge cases. Luckily for Jest 24, @spion has stepped up and fixed this issue. Thank you very much!

The second one is an issue where Jest runs out of memory if the difference in serialization of expected and received value has a huge number of insertion changes (either unexpected because of mistake in test or defect in serializer or expected because of temporary failures during test-driven development). @ittordepam has replaced the previous diffing algorithm with diff-sequences package, which should fix this issue because it uses the theoretical minimum amount of memory. It opens up possibility for word-diffs in the future, similar to what git provides. Please see this PR and don't hesitate to reach out if you want to help make that happen!

Autres faits marquants

  • We have some improvements for globalSetup and globalTeardown as well - code transformation will be applied to them similar to setupFiles and they are now supported as part of projects.
  • You can configure Jest's snapshot location, this is mainly useful if you are building tools which use Jest in a larger build process.
  • A quirk of Jest's CLI has been that while some flags and options have been camel cased (such as runInBand), others have not been (such as no-cache). Dans Jest 24, les deux sont reconnus, ce qui signifie que vous pouvez écrire vos arguments CLI comme vous le souhaitez.
  • We've renamed setupTestFrameworkScriptFile to setupFilesAfterEnv, and made it into an array. Nous espérons que cela rendra les options plus claires. Nous avons prévu de remanier encore la configuration dans la prochaine version majeure, voir le paragraphe dans la section ci-dessous.
  • To reduce the amount of magic Jest performs to “just work™”, in this release we decided to drop automatic injection of regenerator-runtime, which is sometimes used in compiled async code. Including regenerator-runtime is not always necessary and we believe it's the user's responsibility to include it if it's needed. If you use @babel/preset-env with targets set to a modern Node version (e.g. Node 6+) you will not need to include it. Please see our Using Babel docs for more information.
  • Node.js 10 came with an experimental module called worker_threads, which is similar to Worker threads in the browser. jest-worker, part of the Jest platform, will be able to use worker_threads if available instead of child_process, which makes it even faster! Benchmarks show a 50% improvement. En raison de sa nature expérimentale, il n'est pas activé lorsque vous utilisez Jest en tant qu'exécuteur de test, mais vous pouvez l'utiliser dans vos propres projets aujourd'hui ! Nous prévoyons de l'activer par défaut lorsqu'il sera sorti du statut expérimental dans Node.js.

Changements de rupture

While all breaking changes are listed in the changelog, there's a few of them that are worth highlighting:

  • Nous avons fait une mise à jour vers Micromatch 3. Bien que cela n'affecte pas tous les utilisateurs, cette version est plus stricte dans l'analyse des globs que la version 2, qui est utilisée dans Jest 23. Please read through this and linked issues for examples of invalid globs in case you have problems.
  • Nous avons supprimé les restes de code qui étaient nécessaires pour Node 4. Il était auparavant techniquement possible d'exécuter Jest 23 sur Node 4 - ce n'est plus possible sans polyfill et transpilation.
  • Quelques changements dans la sérialisation des fonctions simulées dans les snapshots - assurez-vous de vérifier vos snapshots mis à jour après la mise à jour de la version. Related PR.
  • Jest no longer automatically injects regenerator-runtime - if you get errors concerning it, make sure to configure Babel to properly transpile async functions, using e.g. @babel/preset-env. Related PR.

L'avenir

We are incredibly humbled by the results in State Of JS 2018, where Jest won the “Highest Satisfaction” award. Another huge thing to happen in 2018 was in October, when Jest passed 2 million weekly downloads for the first time. Thank you.

We are very thankful for the trust in us shown by the community, and hope to build on it in the future. We will ensure Jest 24 and future releases will continue to build upon this incredible foundation, and continue to be an integral part of JavaScript developers' toolkits.

This has been the first release where we have explored the idea of using our Open Collective funding to create bug bounties. This worked well in getting non-core developers involved in the implementation of the new landing page, and we're optimistic for a long running bug where Jest globals are mismatched from Node globals. We'd like to do more, if you have a pet bug that's a good candidate for our bounty program, please let us know. In the meantime, you can find all the tickets with a bounty via the issue label.

We have already started to make plans for the next release of Jest 25, with the biggest planned feature being an overhaul of our configuration, which is pretty hard to grok, mainly because of overlapping option and mixing globs and regular expressions. Feedback on how you want Jest's configuration to look is very much welcome, and can be submitted in this issue.

You might also have heard that we are planning to migrate the code base from Flow to TypeScript. We are hopeful that this migration will enable even more contributors to jump in and help make 2019 even better for JavaScript testing. 🚀 The plan is to land this in a minor release in the not too distant future. Feedback on this choice can be added to the RFC.

Lastly, if you've ever wondered about how Jest is built, @cpojer has recorded a video with an architectural overview of how Jest is put together under the hood. Feel free to reach out if you have any further questions about it. The video is available on our website.

Happy Jesting ! 🃏