每当我运行 jest 时,我都会收到以下错误jest --coverage
;
Stackoverflow 说我还不能在我的帖子中添加图片。所以请打开链接查看错误。谢谢
代码和配置如下:
Package.json
"fetch-mock": "^9.9.0",
"fetch-mock-jest": "^1.5.1",
"jest": "26.6.3",
"@types/jest": "26.0.23",
"babel-jest": "^27.2.0",
"eslint-plugin-jest": "^23.20.0",
"ts-jest": "^27.0.5",
Jest Configuration
"jest": {
"preset": "ts-jest",
"transform": {
"^.+\.(ts|tsx)?$": "ts-jest",
"^.+\.(js|jsx)$": "babel-jest"
},
"testRegex": "./test/.*.(js|jsx)$",
"rootDir": ".",
"moduleNameMapper": {
"\.css$": "identity-obj-proxy"
},
"globals": {
"ts-jest": {
"isolatedModules": true
}
},
"moduleDirectories": [
"js",
".",
"node_modules"
]
},
example.test.js
import 'regenerator-runtime/runtime';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';
** It shows error on above line **
import { getEntityItems } from '../../src/actions/entity1';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
global.requestURI = '';
const store = mockStore({});
const root = '/endpoint';
const testHelper = (description, path, query_params = {}) = {
it(description, () => {
fetchMock.getOnce(
path, { body: { interactions: [] }, headers: { 'content-type': 'application/json' } }
);
return store.dispatch(getEntityItems(query_params)).then(() => {
expect(fetchMock.called(path)).toBe(true);
});
});
};
describe('GET entites query parameters', () => {
afterEach(fetchMock.reset());
testHelper('accepts an array of ids', root.concat('&ids=0,1,2'), { ids: [0, 1, 2] });
});
早些时候,该项目是用 javascript 编写的,这段代码运行良好,但现在它已迁移到 typescript。运行测试会引发上述错误。我一直在努力解决这个问题;没运气 :(
我也尝试使用 fetch-mock-jest 但无法正常工作。如果有人可以帮助我解决问题。那会很好!提前致谢 :)
调试更新
当我尝试调试 fetch-mock 时,看看发生了什么。得到了一些见解。当我单击第 1 行的调试时,它会打开debug/index.js
,如我们在屏幕截图 1 中看到的那样:
屏幕截图 1
当我使用 VSCode 的调试器实际调试测试时,我看到,第debug
1 行的变量值是空对象,即{}
(令人惊讶),可以在屏幕截图 2 中看到:
屏幕截图 2
我仍然无法弄清楚为什么代码在实际运行时无法导入包内容。:(