admin管理员组

文章数量:1394978

I have a unit test for a ReactJs/Typescript project that has a reference to a module called nock.js, and using jest:

import nock from 'nock'
...

afterEach(() => {
   nock.cleanAll();
})

When I run the test I get an error in the .cleanAll statement:

TypeError: nock_1.default is not a function

However when I change the import statement to :

var nock = require('nock');

The issue is solved. How can I still use import instead of require ? Is this an issue with the jest configuration? This is the config:

"jest": {
    "transform": {
      "^.+\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "testRegex": "/__tests__/.*\\.(ts|tsx|js)$"
  },

I have a unit test for a ReactJs/Typescript project that has a reference to a module called nock.js, and using jest:

import nock from 'nock'
...

afterEach(() => {
   nock.cleanAll();
})

When I run the test I get an error in the .cleanAll statement:

TypeError: nock_1.default is not a function

However when I change the import statement to :

var nock = require('nock');

The issue is solved. How can I still use import instead of require ? Is this an issue with the jest configuration? This is the config:

"jest": {
    "transform": {
      "^.+\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "testRegex": "/__tests__/.*\\.(ts|tsx|js)$"
  },
Share Improve this question edited Oct 2, 2017 at 11:33 Andreas Köberle 111k58 gold badges280 silver badges307 bronze badges asked Oct 2, 2017 at 11:24 bier hierbier hier 22.6k44 gold badges104 silver badges174 bronze badges 2
  • Maybe this issue? github./node-nock/nock/issues/584 (Jest tries to mock 'nock'…) – helb Commented Oct 2, 2017 at 11:29
  • @helb did not work for me this one – bier hier Commented Oct 2, 2017 at 11:55
Add a ment  | 

2 Answers 2

Reset to default 7

If a module has a default export, you can use:

import nock from 'nock'

But if it doesn't have a default export, you'll need to use:

import * as nock from 'nock'

I met the same exact issue, and fixed it by adding the following config to my tsconfig.json:

{
...
"esModuleInterop": true
...
}

本文标签: javascriptHow to solve issue in jest unit testStack Overflow