我正在为反应代码库添加打字稿支持,虽然应用程序工作正常,但是jest测试在整个地方都失败了,显然没有认识到有关es6语法的东西.
我们正在使用ts-jest.下面是我正在尝试处理jest的测试设置文件时的错误消息.
FAIL src/data/reducers/reducers.test.js
? Test suite failed to run
/Users/ernesto/code/app/react/setupTests.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import './polyfills';
^^^^^^^^^^^^^
SyntaxError: Unexpected string
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
Run Code Online (Sandbox Code Playgroud)
它无法识别一个简单的import './polyfills',说引用的字符串是意外的.
这些是我的设置:
package.json中的jest配置
"jest": {
"setupTestFrameworkScriptFile": "<rootDir>/app/react/setupTests.js",
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
]
},
Run Code Online (Sandbox Code Playgroud)
tsconfig.json
{
"compilerOptions": {
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es6", "dom"],
"module": "es6",
"moduleResolution": "node",
"allowJs": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"target": "es5",
"jsx": "react",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true, …Run Code Online (Sandbox Code Playgroud) 我写了一个脚本,其主要目的是为一些表格的单元格添加新元素.
测试是通过类似的方式完成的:
document.body.innerHTML = `
<body>
<div id="${containerID}">
<table>
<tr id="meta-1"><td> </td></tr>
<tr id="meta-2"><td> </td></tr>
<tr id="meta-3"><td> </td></tr>
<tr id="no-meta-1"><td> </td></tr>
</table>
</div>
</body>
`;
const element = document.querySelector(`#${containerID}`);
const subject = new WPMLCFInfoHelper(containerID);
subject.addInfo();
expect(mockWPMLCFInfoInit).toHaveBeenCalledTimes(3);
Run Code Online (Sandbox Code Playgroud)
mockWPMLCFInfoInit,当被调用时,告诉我该元素已添加到单元格中.
部分代码使用MutationObserver在mockWPMLCFInfoInit向表中添加新行时再次调用:
new MutationObserver((mutations) => {
mutations.map((mutation) => {
mutation.addedNodes && Array.from(mutation.addedNodes).filter((node) => {
console.log('New row added');
return node.tagName.toLowerCase() === 'tr';
}).map((element) => WPMLCFInfoHelper.addInfo(element))
});
}).observe(metasTable, {
subtree: true,
childList: true
});
Run Code Online (Sandbox Code Playgroud)
WPMLCFInfoHelper.addInfo是真正的版本mockWPMLCFInfoInit(当然是一种模拟方法).
从上面的测试,如果添加这样的东西......
const table = element.querySelector(`table`); …Run Code Online (Sandbox Code Playgroud)