Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I ensure that all Jest tests have at least one expect?

Does Jest have a setting or is there a Lint rule or a way to ensure that every Jest test has at least one expect() call in it?

One way to ensure this is to have expect.assertions() in each test. This requires that I remember to add this to each test.

I'm looking for a tooling solution here.

like image 858
Guy Avatar asked Jan 01 '23 17:01

Guy


2 Answers

You can achieve what you want by setting a setup file that defines a beforeEach hook for all your tests.

You can do so by specifying a file through the setupFilesAfterEnv jest configuration option.

Also, you can make use of the hasAssertions method to check if the test has at least one assertion.

Taking all this into account, you could have a jest config file like:

setupFilesAfterEnv: [
    '<rootDir>tests/support/check-assertions-number.js',
],

and in the file check-assertions-number.js:

beforeEach(() => {
    expect.hasAssertions();
});
like image 139
mgarcia Avatar answered Jan 05 '23 15:01

mgarcia


One way to ensure this is to have expect.assertions() in each test. This requires that I remember to add this to each test.

I'm not an expert in jest, but could this be done in the teardown portion of the tests? You would still have to define it on a per-module basis, but it would minimize the duplication in comparison to a per-test basis.

EDIT: Coming from a mocha perspective, it is possible to set up global teardown handlers through afterEach outside of a describe block, which might be possible within jest so you don't even need to define it at a per-module level.

like image 45
jakemingolla Avatar answered Jan 05 '23 16:01

jakemingolla