简体   繁体   中英

Jest.js and Create-react-app: I get "SyntaxError: Cannot use import statement outside a module" when running test

My code

App.test.js

import moment from "moment-timezone";

let result = moment().format();


describe("anything",()=>{
    it("should return a fail..or at least something",()=>{
        expect(result).toBe("wrong")
    })
})

I run:

npx jest or yarn test or npm test

I get:

npx jest
 FAIL  src/App.test.js
  ● Test suite failed to run

    /home/wktdev/Desktop/thing/workflow_magic_guest_app/src/App.test.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import moment from "moment-timezone";
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.586s
Ran all test suites.

It looks like it is similar to this: https://github.com/facebook/jest/issues/9292

When I do npm ls jest it says there are missing dependencies. When II try to manually install them they don't install and the problem is not fixed.

UNMET DEPENDENCY react-scripts@2.1.5
  └── UNMET DEPENDENCY jest@23.6.0 

I figured it out per a message that jest outputs. There are instructions that jest gives to remove the package.lock file, yarn.lock and reinstall via yarn install. I tried it before and I thought that it didn't work and only removed jest, but I was wrong. It seems to work - for now.

If you add jest manually, remove jest dependency from package.json and run npm install or yarn install .

or you can run npm test or yarn test to check the instruction.

To fix that do you need create the file: ./__tests__/setup.js and put that:


import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";

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

After that you only need run: npm run test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM