I have some utils functions that I\'m using among various Jest tests, for example a function like this, for mocking a fetch response:
There is an ability to expose helpers as global functions without any need to import modules explicitly.
package.json:
"jest": {
"setupFiles": ["helpers.js"]
}
helpers.js:
global.mockFetchJsonResponse = (data) => {
ok: () => true,
json: () => data
};
somecomponent.test.js:
mockFetchJsonResponse(); // look mom, I can call this like say expect()!
TypeScript will complain with cannot find name 'mockFetchJsonResponse'
. You can fix that by adding a declaration file:
helpers.d.ts:
declare function mockFetchJsonResponse(data: any): any;
And add that file to the files
section of your tsconfig.json:
// ...
"files": [
"./.jest/helpers.d.ts"
],
// ...
This also exposes the declaration of mockFetchJsonResponse
to your entire code base though, which probably isn't desirable. I can't think of a simple way to avoid that.
Sure it does not answer you direct question "where to put the files" but it's anyway up to you. You just need specify those files in setupFiles
section. Since there is no import
needed in tests it does not really matter.
As for testing test helpers I'm not sure. See it's part of testing infrastructure like spec file itself. And we don't write tests for tests or it would never stop. Sure, it's up to you - say if logic behind is really-really complex and hard to follow. But if helper provides too complex/complicated logic it would lead to tests themselves be impossible to understand, do you agree?
kudos to that article on testing compoentns with intl. Have never dealt with globals
in jest before.
Another approach is by having a test directory and moving helpers on it.
src/
components/
utils/
...
test/
testHelpers.js
Then on the test:
// src/components/MyComponent.spec.js
import { helperFn } from '../../test/testHelpers';
Benefits:
Drawbacks:
test
directory might look silly by containing just a helper fileLooks like GitLab is implementing this approach on their RoR project.
¹ no matter which approach you take, please don't test the test helpers. If the helper fails then your test must fail too. Otherwise your helper is not helping at all.