Enzyme: Where do I put setupTests file

44

Hello, I am following this guid to setup tests in my project(with React-15). I was going through ES6:(setup) and I couldn't get where should I put this test file. and how and where to import the testSetup file. I have tried to put it at root level and in the app directory(where all containers and redux logic is written) but none worked. I am using jest with enzyme. and while running tests I am getting this error:

Enzyme Internal Error: Enzyme expects an adapter to be configured, but found none. To
configure an adapter, you should call `Enzyme.configure({ adapter: new Adapter() })` 
before using any of Enzyme's top level APIs, where `Adapter` is the adapter 
corresponding to the library currently being tested. For example:

          import Adapter from 'enzyme-adapter-react-15';

Or do I need to configure adapter every time?

iiison picture iiison  ·  15 Oct 2017

Most helpful comment

299

Hey @iiison, jest will handle requiring the file for each test if you tell it where this file lives. See http://facebook.github.io/jest/docs/en/configuration.html and more specifically, http://facebook.github.io/jest/docs/en/configuration.html#setuptestframeworkscriptfile-string.

So in your package.json file, you'd have something like:

{
  "jest": {
    "setupTestFrameworkScriptFile": "<rootDir>/path/to/your/file.js",
  }
}

and in that file you'd require enzyme and use the adapter:

const Enzyme = require('enzyme');
const EnzymeAdapter = require('enzyme-adapter-react-15');

// Setup enzyme's react adapter
Enzyme.configure({ adapter: new EnzymeAdapter() });
kmcq picture kmcq  ·  15 Oct 2017

All comments

299

Hey @iiison, jest will handle requiring the file for each test if you tell it where this file lives. See http://facebook.github.io/jest/docs/en/configuration.html and more specifically, http://facebook.github.io/jest/docs/en/configuration.html#setuptestframeworkscriptfile-string.

So in your package.json file, you'd have something like:

{
  "jest": {
    "setupTestFrameworkScriptFile": "<rootDir>/path/to/your/file.js",
  }
}

and in that file you'd require enzyme and use the adapter:

const Enzyme = require('enzyme');
const EnzymeAdapter = require('enzyme-adapter-react-15');

// Setup enzyme's react adapter
Enzyme.configure({ adapter: new EnzymeAdapter() });
kmcq picture kmcq  ·  15 Oct 2017
213

If you use Create React App, you can create a src/setupTests.js and put inside it the Enzyme initialization code. CRA will tell Jest to load it before each of your tests automatically.

FezVrasta picture FezVrasta  ·  16 Oct 2017
23

What if your using https://github.com/wmonk/create-react-app-typescript ?

I have this:

image

but get:

image

quantuminformation picture quantuminformation  ·  6 Nov 2017
14

I also tried this:

  "jest": {
    "setupTestFrameworkScriptFile": "src/setupTests.js"
  }
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

image

same error

quantuminformation picture quantuminformation  ·  6 Nov 2017
-2

I believe typescript may be broken by default when importing from CJS - you may need to try import * as Adapter from ‘enzyme-adapter-whatever’.

ljharb picture ljharb  ·  6 Nov 2017
2

@QuantumInformation Were you able to figure this one out? Having the exact same issue currently.

Using '*' in the import didn't work unfortunately.

edit: I managed to resolve the error by typing the setup file as shown in this SO answer:
https://stackoverflow.com/questions/46435558/could-not-find-declaration-file-for-enzyme-adapter-react-16

adepatie picture adepatie  ·  8 Nov 2017
5

Made a PR to clarify Jest setup https://github.com/airbnb/enzyme/pull/1396

likethemammal picture likethemammal  ·  28 Nov 2017
4

Where would this go for mocha/karma?
I added the adapter logic in the karma.conf.js, however doesn't seem to work

{
    ...
    files: [
        'node_modules/babel-polyfill/dist/polyfill.js',
        'test/setupTests.js',
        ...
    ],
    preprocessors: {
        'test/setupTests.js': ['webpack'],
        ...
    }
    ...
}
priyajeet picture priyajeet  ·  6 Dec 2017
0

@priyajeet Hi, were you able to solve this issue?

yinguangyao picture yinguangyao  ·  15 Dec 2017
0

@yinguangyao I ended up migrating my repo to use Jest instead. Ripped the bandaid off before it gets worse.

You may also want to see this bug thread https://github.com/airbnb/enzyme/issues/1257#issuecomment-349797199 and this https://github.com/airbnb/enzyme/issues/1318#issuecomment-342590767 where you can get stuff working with Karma/Mocha, but it seems to force entire test suite to run with no clean path to run individual test files.

priyajeet picture priyajeet  ·  20 Dec 2017
0

@priyajeet hahaha, thanks.
But I have solved this issue in my repo: https://github.com/yinguangyao/msg-board

yinguangyao picture yinguangyao  ·  21 Dec 2017
0

I also have same problem using react-script-ts
These options in your package.json Jest configuration are not currently supported by Create React App:
• setupTestFrameworkScriptFile

amorfati0310 picture amorfati0310  ·  5 Jan 2018
0

It’s possible that CRA doesn’t work with a jest setup file without ejecting; if so, that’s a bug you should file.

Since this is both answered here and a part of jest’s (or other frameworks’) documentation that’s unrelated to enzyme, i think this can be closed.

ljharb picture ljharb  ·  5 Jan 2018
0

Can anyone please tell me where to keep jest.config.js in my project ?I tried keeping it in a subfolder inside my root dir but it throws error same as specified by @QuantumInformation .

nileshgulia1 picture nileshgulia1  ·  5 Jan 2018
5

If you use create-react-app, maybe this solution could help:
https://stackoverflow.com/a/46810504/801426
The idea is that config should be placed in path src/setupTests.js.

bullgare picture bullgare  ·  18 Jan 2018
15

I had the same issue.
My problem was that I put "setupFiles": ["<rootDir>/src/setupTests.ts"], into package.json, but if you have jest.config.js than you should place setupFiles in that file.

kreedz picture kreedz  ·  7 Feb 2018
45

@QuantumInformation, @adepatie and everybody who uses Create React App + TypeScript - correct path, that you can use without ejecting from default environment, is src/setupTests.ts (notice .ts extension).

Also this is what you put inside (as of now):

import { configure } from 'enzyme';
import * as Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });
jayarjo picture jayarjo  ·  21 Feb 2018
4

For those who are not using create-react-app, and only mocha + enzyme and not jest, how should we configure the setup file?

xploreraj picture xploreraj  ·  19 Mar 2018
2

@xploreraj There is small a instruction here http://airbnb.io/enzyme/docs/guides/mocha.html . This is a general configuration file we use for mocha , jsdom:

require('babel-register')();

var jsdom = require('jsdom').jsdom;

var exposedProperties = ['window', 'navigator', 'document'];

global.document = jsdom('');
global.window = document.defaultView;
Object.keys(document.defaultView).forEach((property) => {
  if (typeof global[property] === 'undefined') {
    exposedProperties.push(property);
    global[property] = document.defaultView[property];
  }
});

global.navigator = {
  userAgent: 'node.js'
};

documentRef = document;
nileshgulia1 picture nileshgulia1  ·  19 Mar 2018
0

i can't get it to work in mocha either, I've tried --require setupTests.js in mocha which didn't work

mcgodan picture mcgodan  ·  23 Apr 2018
0

I've been working on setting up a starter create-react-app + typescript + mocha project for the past two weeks.
Like others have said, use
import * as Adapter from 'enzyme-adapter-react-16';
instead of
import Adapter from 'enzyme-adapter-react-16';
in your setup file

Put your setup file at src/setupTests.ts if you are using the default jest. You can see that your tsconfig.json already references this file to exclude from the build:
image

@mcgodan
To get mocha working, it requires some setup. If I get the time, I'll write up an article or something on how to set it up. But for now, here are some pictures:

Add test script to package.json:
image

scripts/test.sh:
image

mocha.opts:
image

config/enzyme.ts:
image

Pretty much you have to set everything for mocha that jest already does in create-react-app-ts. I don't like putting the enzyme.ts file at src/setupTests.ts because it's for tests and not really app source code. I might end up symlinking it just so jest still works.

dosentmatter picture dosentmatter  ·  28 Apr 2018
56

Several hours wasted, and below config worked;

package.json has

  "dependencies": {
    "react": "^16.3.2",
    "react-dom": "^16.3.2",
    "react-scripts": "1.1.4"
  },
  "devDependencies": {
    "enzyme": "^3.3.0",
    "enzyme-adapter-react-16": "^1.1.1",
    "react-addons-test-utils": "^15.6.2",
    "react-test-renderer": "^16.3.2"
  },

Note: The jest > setupTestFrameworkScriptFile key in package.json must not be there, remove if it exists.

srcsetupTests.js has

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

Hope that helps.

manoharreddyporeddy picture manoharreddyporeddy  ·  12 May 2018
0

@manoharreddyporeddy Thanks, it works!!!! Remove jest > setupTestFrameworkScriptFile key in package.json is very very important.

ShawnXiao105 picture ShawnXiao105  ·  31 May 2018
-9

@ShawnXiao105 glad to hear
I worked in React.js for 2 days :-), its good but Angular 4/5 is taking on the world, even though React.js is nice, its because of the problems like you are facing is an example of many changes and old documentation, here React.js needs to be improve.

Update:
In a recent project, i chose reactjs again. In just 3 days project is 80% complete (even without using Redux, but using only passing callbacks from parent to client)

Reactjs is definitely better than Angular 6, in developing application faster, writing highly maintainable code, super fast on run time. Used MERN tack instead of MEAN, used Visual Studio 2017.

manoharreddyporeddy picture manoharreddyporeddy  ·  31 May 2018
18

For those like me please pay attention to the file name \src\setupTests.js its plural!! setupTests

Julian-Jurai picture Julian-Jurai  ·  24 Aug 2018
0

I believe it must be "

HarryDao picture HarryDao  ·  29 Oct 2018
2

Jest looks for the setupTests.js file when you start the test runner. If you have a terminal open somewhere with the test runner in watch mode, you'll get no love.

You don't need to add the following to your package.json unless you've ejected
"jest": { "setupTestFrameworkScriptFile": "<rootDir>/src/setupTests.js" }

travisCarson picture travisCarson  ·  10 Dec 2018
3

Worked for me: jest.config.js and setupTests.ts in root directory
image

My jest.config.js

module.exports = {
  roots: [
    '<rootDir>/src'
  ],
  transform: {
    '.*\.tsx?$': 'ts-jest'
  },
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$',
  moduleFileExtensions: [
    'ts',
    'tsx',
    'js',
    'jsx',
    'json',
    'node'
  ],
  moduleDirectories: ["node_modules", "src"],
  moduleNameMapper: {
    '\.(css|jpg|png)$': '<rootDir>/empty-module.js',
  },
  collectCoverageFrom: [
    'src/**/*.{ts,tsx}',
    '!src/index.tsx',
  ],
  testURL: 'http://localhost/',
  setupTestFrameworkScriptFile: "<rootDir>/setupTests.ts"
}

You can see setupTestFrameworkScriptFile: "<rootDir>/setupTests.ts" there.

My setupTests.ts

import { configure } from 'enzyme';
import * as Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });
kirrosh picture kirrosh  ·  12 Dec 2018
2

Is there anyway to "require" the setupTests file? I'd love to just define this once.

reywright picture reywright  ·  1 Feb 2019
0

image

I used require:

import * as enzyme from 'enzyme';
const Adapter = require ('enzyme-adapter-react-16') ;

enzyme.configure({ adapter: new Adapter() });

It worked!

image

guilhermefelipesilva picture guilhermefelipesilva  ·  14 Jul 2019
1

That’s because it’s incorrect to use import * as there - that’s typescripts broken-by-default module system.

ljharb picture ljharb  ·  15 Jul 2019
9

Just as a precaution, you should restart tests if you add setupTest.js.

ilyasidorchik picture ilyasidorchik  ·  12 Sep 2019
0

Just as a precaution, you should restart tests if you add setupTest.js.

Scrolled down to comment it , already here :P

mfaizan1 picture mfaizan1  ·  20 Oct 2019
0

The solution provided by @kirrosh worked for me, for the exception of the import syntax for the Adapter. I used the following with "typescript": "^3.6.2"

import Adapter from 'enzyme-adapter-react-16';
adrienplg picture adrienplg  ·  24 Oct 2019
3

If you are using ts with create-react-app . --typescript and you used script eject you need to add a new path as the image show you:

bubu

n.n)/

kikiondo117 picture kikiondo117  ·  11 Nov 2019
0

I've tried every solution I could. Making a jest.config.js file in root dir and setting up a setupFiles configuration. Then setting up snapshotSerializers with enzyme-to-json serializer. Then switching between .ts and .js extensions just in case. Nothing worked really in my CRA TS no-inject case.

What worked is placing the jest configuration inside package.json.
Note: setupFiles or setupTestFrameworkScriptfile apparently isn't supported from CRA. Only snapshotSerializers worked for me.

package.json

{
  "jest": {
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ]
  }
}

But of course you first have to install npm install --save-dev enzyme-to-json/yarn add -D enzyme-to-json which is something guides didn't inform me of but was quite easy to get that information from errors.

exapsy picture exapsy  ·  24 Dec 2019
1

@kikiondo117 I like the font you are using. What's the name of this font(if you don't mind 🙏)?

iiison picture iiison  ·  16 May 2020
2

Sure, the name is fira code, it's free :D, you can download here -> https://github.com/tonsky/FiraCode

kikiondo117 picture kikiondo117  ·  18 May 2020