【问题标题】:Unit Tests Failing After Updating React Scripts from v.3.4.4 to v.4.0.3将 React 脚本从 v.3.4.4 更新到 v.4.0.3 后单元测试失败
【发布时间】: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


    【解决方案1】:

    解决方案是将resetMocks 设置为false。我尝试在 Jest 配置中执行此操作,但无法使其正常工作,因此直接将其添加到 package.json:

    "jest": {
        "resetMocks": false
    }
    

    从失败的测试来看并不明显,但是阅读release notes 你可以看到 Create React App 使用的 Jest 版本从 v24 更改为 v26。在此过程中,resetMocks 设置为 true,这破坏了上述测试中的实现,导致它们全部超时。

    【讨论】:

      猜你喜欢
      • 2022-06-30
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      相关资源
      最近更新 更多