jcp*_*den 3 reactjs jestjs create-react-app
我正在为客户开发一个新项目,并被要求将 create-react-app (react-scripts) 从 v.2.0.5 更新到 v.4.0.3。我这样做了,但一堆单元测试失败了。我回顾了该项目,并将重大更改隔离为从 React-scripts 3.4.4 到 4.0.0 的更新。
基本上,我看到的主要错误似乎适用于针对 async/await 方法运行的任何测试。Jest 报告测试超时,但这些测试只是因为失败而超时。它们都在早期版本的react-scripts(以及我猜的早期版本的Jest)上顺利通过。
thrown: "Exceeded timeout of 5000 ms for a test.
Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
Run Code Online (Sandbox Code Playgroud)
超时似乎与承诺问题有关,因为它之前出现了以下错误:
TypeError: Cannot read property 'then' of undefined
Run Code Online (Sandbox Code Playgroud)
还有一个相当难以辨认的堆栈跟踪,其中列出了节点模块的负载。
这是失败的测试的示例:
test('dispatching fetchPublishedArticlesAuthors action causes an API GET and updates the store', async (done) => {
const options = { page: 0, size: 20, sort: 'createdBy.firstName,asc' };
store.dispatch(fetchPublishedArticlesAuthors(options));
const state = await stateChange(store);
expect(fetch).toHaveBeenCalledWith(
`https://content.onehub.test/articles/authors?page=0&size=20&sort=createdBy.firstName%2Casc`,
expect.objectContaining({ method: 'GET' }),
);
expect(getPublishedArticlesAuthors(state)).toMatchSnapshot();
done();
});
Run Code Online (Sandbox Code Playgroud)
wait stateChange(store) 引用此方法:
export function stateChange(store) {
return new Promise((resolve) => {
let currentState = store.getState();
store.subscribe(() => {
const newState = store.getState();
if (newState !== currentState) {
resolve(newState);
}
currentState = newState;
});
});
}
Run Code Online (Sandbox Code Playgroud)
此方法在运行react-scripts 4.0.3的另一个项目上运行没有问题,所以我认为这本身不是问题,但如果我没有弄错的话,它无法返回任何内容。
Store 被嘲笑如下:
beforeEach(() => {
store = mockStore({ initialState, reducers, rootSaga: sagas });
fetch.mockClear();
});
Run Code Online (Sandbox Code Playgroud)
关于从哪里开始有什么建议吗?困惑为什么它在更新的版本上失败但在较早的版本上传递。
解决方案是将resetMocks设置为false。我尝试在 Jest 配置中执行此操作,但无法使其正常工作,因此只需将其直接添加到 package.json 中:
"jest": {
"resetMocks": false
}
Run Code Online (Sandbox Code Playgroud)
从失败的测试来看,这一点并不明显,但阅读发行说明后,您可以看到 Create React App 使用的 Jest 版本从 v24 更改为 v26。在此过程中,resetMocks被设置为true破坏上面测试中的实现,导致它们全部超时。
| 归档时间: |
|
| 查看次数: |
1620 次 |
| 最近记录: |