Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve issue in jest unit test?

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)$"
  },
like image 473
bier hier Avatar asked Sep 14 '25 10:09

bier hier


1 Answers

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'
like image 172
Fenton Avatar answered Sep 17 '25 00:09

Fenton