Search code examples
reactjsconfigjestjsreact-on-rails

How can I make a config file to import the same modules for multiple jest tests?


I have tests for jest written in jsx files with these same lines of code:

import React from 'react';
import { configure } from 'enzyme';
import { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });

How can I make a config file to include these every time instead of writing these in my test file?


Solution

  • You will still need to do

    import React from 'react';
    import { shallow } from 'enzyme';
    

    in your unit tests since your tests need to use React and shallow but you can move

    import { configure } from 'enzyme';
    import Adapter from 'enzyme-adapter-react-16';
    
    configure({ adapter: new Adapter() });
    

    into a separate file and configure that file to be run before each test.

    If you bootstrapped your app using create-react-app v4 or higher and haven't ejected then you can put that code in src/setupTests.js

    Otherwise you can configure Jest to run it as a setupTestFrameworkScriptFile