【发布时间】:2021-09-02 17:35:37
【问题描述】:
我正在为客户开发一个新项目,并被要求将 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."
超时似乎与 Promise 的问题有关,因为它先于这个错误:
TypeError: Cannot read property 'then' of undefined
还有一个相当难以辨认的堆栈跟踪,其中列出了节点模块的负载。
这是一个失败的测试示例:
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();
});
await 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;
});
});
}
此方法在另一个运行 react-scripts 4.0.3 的项目上没有问题,所以我认为这本身不是问题,但如果我没记错的话,它无法返回任何东西。
Store 模拟如下:
beforeEach(() => {
store = mockStore({ initialState, reducers, rootSaga: sagas });
fetch.mockClear();
});
关于从哪里开始的任何提示?对为什么它在较新的版本上失败但在较早的版本上传递感到困惑。
【问题讨论】:
标签: reactjs jestjs create-react-app