user1584120
user1584120

Reputation: 1261

When testing react project npm test works but jest doesn't

I have used create-react-app to create a new react app and have added a couple of simple components and tests. When running the tests using 'npm test' they run fine. When running with jest I get 'Unexpected token' when using the imported component within the test. For example:

import React from 'react';
import { shallow } from 'enzyme';
import App from './App';

it('renders without crashing', () => {
  shallow(<App />);
});

The usage of App within the test gives the error, but only when running jest.

Upvotes: 0

Views: 1629

Answers (2)

grizzthedj
grizzthedj

Reputation: 7505

If you want more control over this, I would recommend bypassing what comes out of the box with create-react-app.

You can add a test entry in your package.json that will essentially use jest, but allow you to pass a config file.

  "scripts": {
    ...
    "test": "jest --config jest.conf.js",
    ...
  },

Then in your jest.conf.js, you can add variables to be used in your tests. The collectCoverage and coverageDirectory attributes are for code coverage.

{
  "globals":{
    "__DEV__": true,
    "API_BASE_URL": "http://api",
    "SOME_VAR": "whatever"
    "unmockedModulePathPatterns": [
      "node_modules/react/",
      "node_modules/enzyme/"
    ]
  },
  "collectCoverage": "true",
  "coverageDirectory": "coverage"
}

Then when running npm run test, it will execute the tests using jest, with a custom config.

Upvotes: 0

peter.mouland
peter.mouland

Reputation: 1983

The unexpected token error is likely to be because you haven't installed babel-jest and haven't add the transform key to the jest.json. I expect createReactAppis doing something to hide this from you. If you want to use non-createReactApp commands (likejest`) then i'd 'eject' the app (which can not be undone) so that you can see all configs etc.

or you could add your own jest.json, but i feel this might get confusing to have 2 ways of running tests.

Upvotes: 2

Related Questions