Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest globalSetup option not working

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.

like image 977
theclarkofben Avatar asked Mar 16 '18 17:03

theclarkofben


Video Answer


2 Answers

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

like image 117
Good Idea Avatar answered Sep 24 '22 11:09

Good Idea


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 and enzyme-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!

like image 39
Adépòjù Olúwáségun Avatar answered Sep 24 '22 11:09

Adépòjù Olúwáségun