Custom Arguments with Jest
How and why you should use them in your test configuration
2 min read
What are custom arguments
Normally, Jest has its own arguments that you can run like below:
The command above allows you to run your tests sequentially, instead of in parallel. It's a useful command for when you need to debug your tests.
Custom arguments are similar to the above example, except you define what you want to send to the jest cli (aka "arguments")
For example, let's say I want to do something like this:
The example above illustrates that I would like the test suite to stop executing the rest of the test when the first failed test. As of right now, this is not supported by Jest natively. However, with custom arguments, this can become a reality.
(Note: Jest does have a fail fast(-ish) option built-in (
--bail) however, it exits on the first failed test suite, not individual test. Open issue about this: Github Issue)
How to enable custom arguments
Upon researching this topic, I came to the conclusion that the best way for this to work without impacting the existing functionality of jest and it's cli, was to create a
.js file that we pass custom arguments to, perform computation, and pass the jest runner the modified, but supported arguments for the test suite(s).
It would look something like this:
And in your package.json, in your scripts portion, you would run it like this:
test: "node preJest.js --runInBand", test:failFast: "node preJest.js --failFast=true --runInBand"
With this configuration, you are able to share easily different configurations for your tests without the hassle of sharing and updating environment files and/or creating new ones for different use cases.
Additionally, we are able to run the commands above, mixing both the custom arguments and the official arguments without any conflict.
If you made it this far, thank you for reading my article. If you have any questions, comments, or concerns about this, either leave a comment or contact me at firstname.lastname@example.org