Jest is a powerful test runner, assertion library, and simple to use. Personally, It has replaced other configurations I've used like Mocha, Chai, Sinon for my Javascript testing. But one thing I really wished for, in Jest, is the ability to enable custom command line arguments. With custom arguments, I'm able to isolate testing configurations between npm scripts. Let's dive into what they are.
What are custom arguments
Normally, Jest has its own arguments that you can run like below:
jest --runInBand
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:
jest --failFast=true
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"
This configuration utilizes a third-party dependency called Yargs and Yargs-unparser. Both of these utilities allow me to easily manipulate the CLI like JavaScript.
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 contact@christianarty.com
Top comments (0)