Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Where do I put setupTests file #1265

Closed
iiison opened this issue Oct 15, 2017 · 39 comments
Closed

Where do I put setupTests file #1265

iiison opened this issue Oct 15, 2017 · 39 comments
Labels

Comments

@iiison
Copy link

iiison commented Oct 15, 2017

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?

@kmcq
Copy link
Contributor

kmcq commented Oct 15, 2017

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() });

@FezVrasta
Copy link
Contributor

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.

@quantuminformation
Copy link

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

I have this:

image

but get:

image

@quantuminformation
Copy link

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

@ljharb
Copy link
Member

ljharb commented Nov 6, 2017

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

@adepatie
Copy link

adepatie commented Nov 8, 2017

@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

@likethemammal
Copy link
Contributor

Made a PR to clarify Jest setup #1396

@priyajeet
Copy link

priyajeet commented Dec 6, 2017

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'],
        ...
    }
    ...
}

@yinguangyao
Copy link

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

@priyajeet
Copy link

priyajeet commented Dec 20, 2017

@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 #1257 (comment) and this #1318 (comment) 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.

@yinguangyao
Copy link

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

@amorfati0310
Copy link

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

@ljharb
Copy link
Member

ljharb commented Jan 5, 2018

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 ljharb closed this as completed Jan 5, 2018
@nileshgulia1
Copy link

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 .

@bullgare
Copy link

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.

@kreedz
Copy link

kreedz commented Feb 7, 2018

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.

@jayarjo
Copy link

jayarjo commented Feb 21, 2018

@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() });

@xploreraj
Copy link

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

@nileshgulia1
Copy link

@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;

@mcgodan
Copy link

mcgodan commented Apr 23, 2018

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

@dosentmatter
Copy link

dosentmatter commented Apr 27, 2018

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.

@manoharreddyporeddy
Copy link

manoharreddyporeddy commented May 12, 2018

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.

\src\setupTests.js has

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

Hope that helps.

@ShawnXiao105
Copy link

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

@manoharreddyporeddy
Copy link

manoharreddyporeddy commented May 31, 2018

@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.

@julianjurai
Copy link

julianjurai commented Aug 24, 2018

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

@HarryDao
Copy link

HarryDao commented Oct 29, 2018

I believe it must be "<rootDir>/src/setupTests.js", not just "src/setupTests.js"

@travisCarson
Copy link

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" }

@kirrosh
Copy link

kirrosh commented Dec 12, 2018

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() });

@silouanwright
Copy link

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

@guilhermefsreis
Copy link

image

I used require:

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

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

It worked!

image

@ljharb
Copy link
Member

ljharb commented Jul 15, 2019

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

@ilyasidorchik
Copy link

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

@mfaizan1
Copy link

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

Scrolled down to comment it , already here :P

@adrienplg
Copy link

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';

@kikiondo117
Copy link

kikiondo117 commented Nov 11, 2019

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)/

@exapsy
Copy link

exapsy commented Dec 24, 2019

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.

@iiison
Copy link
Author

iiison commented May 16, 2020

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

@kikiondo117
Copy link

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

@ruslanguns
Copy link

The answer provided by @kmcq works and fix this issue how ever in favor of the deprecation of "setupTestFrameworkScriptFile" you have to use "setupFilesAfterEnv" which receives an Array of jest setup files:

// package.json

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

Or if you have a jest.config.js file:

// jest.config.js

module.exports = {
  "setupFilesAfterEnv": [
      "<rootDir>/path/to/your/file.js"
   ]
}

If your React application is generated by CRA then make sure you add setupTest.js file inside src/*. If you want to override this behavior follow the steps above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests