【发布时间】:2019-05-20 03:18:32
【问题描述】:
我正在使用 Jest、Enzyme 和 Typescript,但由于某些原因,某些导入无法正常工作......它们是未定义的。例如,我在一个文件中有import ReactMarkdown from 'react-markdown';,当我运行测试时,我得到Cannot read property 'createElement' of undefined for ReactMarkdown。下面是配置文件
jest.config.js
/* tslint:disable */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
moduleFileExtensions: [
"ts",
"tsx",
"js"
],
transform: {
"^.+\\.tsx?$": "ts-jest",
"^.+\\.svg$": "jest-svg-transformer"
},
testMatch: [
"**/*.(test|spec).(ts|tsx)"
],
globals: {
"ts-jest": {
babelConfig: true,
tsConfig: "jest.tsconfig.json"
}
},
coveragePathIgnorePatterns: [
"/node_modules/",
"enzyme.js"
],
setupTestFrameworkScriptFile: "<rootDir>/enzyme.js",
coverageReporters: [
"json",
"lcov",
"text",
"text-summary"
],
moduleNameMapper: {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/mocks.js",
"\\.(css|less|scss)$": "<rootDir>/__mocks__/mocks.js"
}
};
jest.ts.config.json
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"module": "commonjs",
"target": "esnext",
"jsx": "react",
"sourceMap": false,
"experimentalDecorators": true,
"noImplicitUseStrict": true,
"removeComments": true,
"moduleResolution": "node",
"lib": [
"es2017",
"dom"
],
"typeRoots": [
"node_modules/@types"
]
},
"exclude": [
"node_modules",
"out",
".next"
]
}
【问题讨论】:
-
是不是因为你的tsconfig.json里需要
allowSyntheticDefaultImports:true? -
不,我的 tsconfig 中有这个
-
@mergesort 你找到解决这个问题的方法了吗?
-
显示你的 tsconfig。根据我的经验,大多数(如果不是全部)导入问题都源于错误的 tsconfig。 tsconfig 允许您定义诸如路径别名和 baseUrl 之类的东西,它们可以提供更好的路径,但不能与其他 JS 技术很好地配合。
-
你使用哪个版本的 react-markdown?
标签: reactjs typescript jestjs babeljs enzyme