我试着用Jest测试用类型记录编写的响应组件,但是当我运行测试时,我得到了以下错误:
Cannot use JSX unless the '--jsx' flag is provided.
该项目需要多个tsconfig文件(一个用于节点服务器,另一个用于客户端源),因此该项目的结构如下:
/root
package.json
jest.config.js
/src
tsconfig.json
/server
tsconfig.json
我目前只尝试在src
目录中运行测试。我认为问题在于ts-jest没有加载正确的tsconfig文件,但是在浏览了它们的文档、问题并在空闲通道上询问之后,我找不到任何方法将--jsx
标志传递给ts-jest或指定要使用的tsconfig。
以下是我的配置文件的内容:
/root/jest.config.js
module.exports = {
roots: [
'<rootDir>/src',
],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
testRegex: '/__tests__/.*\\.test\\.tsx?$',
moduleFileExtensions: [
'ts',
'tsx',
'js',
'jsx',
'json',
'node',
],
setupFilesAfterEnv: ['jest-enzyme'],
testEnvironment: 'enzyme',
};
/root/src/tsconfig.json
{
"compilerOptions": {
"plugins": [
{
"name": "typescript-styled-plugin"
}
],
"target": "es2018",
"lib": ["es2018", "dom"],
"jsx": "react",
"moduleResolution": "node",
"allowJs": true,
"esModuleInterop": true,
"skipLibCheck": true,
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"noImplicitReturns": true,
"outDir": "../dist/src",
"baseUrl": ".",
"typeRoots": ["./types", "../node_modules/@types"]
}
}
以及我在package.json
中的相关依赖项
"@types/jest": "^24.0.10",
"@types/enzyme": "^3.9.0",
"enzyme": "^3.9.0",
"enzyme-adapter-react-16": "^1.10.0",
"jest": "^24.3.1",
"jest-environment-enzyme": "^7.0.2",
"jest-enzyme": "^7.0.2",
"ts-jest": "^24.0.0",
"ts-node": "^8.0.2",
"typescript": "^3.3.3",
"typescript-styled-plugin": "^0.13.0"
以及失败的测试(位于/root/src/pages/__tests__/index.test.tsx
)
import React from 'react';
import IndexPage from '../index';
import { shallow } from 'enzyme';
describe('pages/index', () => {
test('Should render without error', () => {
const wrapper = shallow(<IndexPage/>);
});
});
我在这里做错什么了?
编辑:
在此期间,我只需将root/src/tsconfig.json
迁移到root/tsconfig.json
,就可以让它发挥作用。如果我想向服务器添加测试,这是行不通的,但我将使用它,直到出现更好的结果。
发布于 2019-03-09 12:19:05
默认情况下,ts-jest
将查找<roodDir>/tsconfig.json
。
如果要指定特定的配置文件,请使用global/ts-jest/tsconfig
选项:
// package.json/jest or jest.config.json
{
"globals": {
"ts-jest": {
"tsConfig": "<your tsconfig.json file path>"
}
}
}
参考资料:https://kulshekhar.github.io/ts-jest/user/config/#options
https://stackoverflow.com/questions/55070538
复制相似问题