I'm trying to make a function called loadFixtures available to all Jest tests.
I have the following line within the jest config object inside package.json:
"globalSetup": "<rootDir>/src/test/js/config/setup-globals.js"
setup-globals.js contains:
module.exports = function() {
function loadFixtures(filename) {
console.info('loadFixtures is working');
}
}
Within my tests I have, for example:
beforeEach(() => {
loadFixtures('tooltip-fixture.html');
});
However when I run Jest I get the following for each test:
ReferenceError: loadFixtures is not defined
I verified that the setup-globals.js file is definitely being found and loaded in by Jest before the tests execute.
Can anyone assist in identifying where I've gone wrong here? I've spent pretty much an entire day trying to debug without luck.
You should be using setupFiles
and not globalSetup
.
// jest config
"setupFiles": [
"<rootDir>/src/test/js/config/setup-globals.js"
]
then src/test/js/config/setup-globals.js
:
global.loadFixtures(filename) {
console.info('loadFixtures is working');
}
references: https://medium.com/@justintulk/how-to-mock-an-external-library-in-jest-140ac7b210c2
If you bootstrapped your application using npx create-react-app
(CRA), you do not need to add the setupFiles
key under your jest
key in the package.json
file (CRA prevents overriding that key).
what you simply need to do is to add the file setupTests.js
in the root of your SRC
folder, and populate it with the snippet below:
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({
adapter: new Adapter(),
});
remember you must have earlier installed the right versions of
enzyme
andenzyme-adapter-react
CRA has been wired to automatically load the setupTests.js
file in the src
folder if it exists. Hence after adding these, you can then go over to your test and do import {shallow} from enzyme
without triggering an error.
if you are not using Create-react-app
, all you need to do, in addition to adding the file above to your src
folder is to add the key setupFiles
into the jest
key in your package.json. it should look like this:
"jest": {
"setupFiles": ['<rootDir>/src/setupTests.js'],
}
and you are good to go.
Cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With