简体   繁体   中英

ts-jest cannot run testing on imported ES6 modules

I'm using a compiled ES6 library in my Typescript application. The testing fails with an error

TypeError: Cannot read property 'PropTypes' of undefined

The module it is complaining about is importing react as

import React from 'react';

If I change this to

import * as React from 'react';

then it will compile and run fine. Here is my package.json 's jest config:

"jest": {
    "transform": {
      ".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js|jsx)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json"
    ],
    "verbose": true,
}

And here is my tsconfig.json :

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "module": "commonjs",
        "target": "es5",
        "jsx": "react",
        "allowJs": true,
        "preserveConstEnums": true,
        "removeComments": true,
        "noImplicitAny": false,
        "moduleResolution": "node",
        "noUnusedParameters": true
    },
    "include": [
        "./src/**/*"
    ],
    "filesGlob": [
        "**/*.ts",
        "**/*.tsx"
    ],
    "exclude": [
        "node_modules",
        "typings/main",
        "typings/main.d.ts",
        "typings/index.d.ts"
    ]
}

What configuration have I messed up here?

then it will compile and run fine.

That is the way to go for TypeScript. import * as React from "react" .

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