javascript - 具有异步功能的有状态 React 组件未通过 Jest 测试

标签 javascript reactjs unit-testing testing jestjs

我正在关注这个 Jest test tutorial on Pluralsight here .我写的代码和作者一模一样,但出于某种原因我的测试没有通过。

我对作者仓库的 Pull 请求:https://github.com/danielstern/isomorphic-react/pull/19

我有一个简单的 React 组件,它通过对 componentDidMount 中的服务进行异步/等待调用来更新它的 count 状态。

{this.state.count != -1 ? `${this.state.count} Notifications Awaiting` : 'Loading...'}

预计

因为我模拟了 NotificationsService,并将计数设置为 42,所以测试应该通过,组件内的文本为 "42 Notifications Awaiting!"

结果

文本保持默认状态 Loading...

我已经正确模拟了服务,count 变量甚至被正确记录为 42!但是 this.state.count 仍然是 -1 所以它不会显示:${this.state.count} Notifications Awaiting 它仍然显示 Loading... 因此测试失败。


我尝试过的

1) 我试过将延迟增加 1000。

2) 尝试在测试中使用 setTimeout。

3) 尝试了 jest.useFakeTimers();jest.runAllTimers();

但是没有任何效果,即使 count 设置为 42,组件内部的 count 仍然停留在 -1。它只是在我看来,我的测试在状态设置完成之前正在运行?

enter image description here

NotificationsViewser.jsx 组件

import React from 'react';
import NotificationsService from '../services/NotificationsService';

export default class componentName extends React.Component {
  constructor(...args) {
    super(...args);

    this.state = {
      count: -1
    }
  }

  async componentDidMount () {
    let { count } = await NotificationsService.GetNotifications();
    console.log('count:', count);
    this.setState({
      count
    });
  }

  componentDidUpdate() {
    console.log('componentDidUpdate:', this.state);
  }

  render() {
    return (
      <div className="mt-3 mb-2">
        <div className="notifications">
          {this.state.count != -1 ? `${this.state.count} Notifications Awaiting` : `Loading...`}
        </div>
      </div>
    )
  }
}

NotificationsService.js

import { delay } from 'redux-saga';

export default {
  async GetNotifications() {
    console.warn("REAL NOTIFICATION SERVICE! CONTACTING APIS!");

    await delay(1000);
    return { count: 42 };
  }
}

模拟:NotificationsService.js

let count = 0;

export default {
  __setCount(_count) {
    count = _count;
  },
  async GetNotifications() {
    console.warn("GOOD JOB! USING MOCK SERVICE");
    return { count };
  }
}

最后……

测试

import React from 'react';
import renderer from 'react-test-renderer';
import delay from 'redux-saga';

import NotificationsViewer from '../NotificationsViewer';

jest.mock('../../services/NotificationsService');

const notificationService = require('../../services/NotificationsService').default;

describe('The notification viewer', () => {

  beforeAll(() => {
    notificationService.__setCount(42);
  });

  it('should display the correct number of notifications', async() => {
    const tree = renderer
      .create(
        <NotificationsViewer/>
      );

    await delay();

    const instance = tree.root;
    const component = instance.findByProps({className: `notifications`});
    const text = component.children[0];
    console.log('text is:', text);

    expect(text).toEqual('42 Notifications Awaiting!');
  });
})

最佳答案

事实上,真正的问题出在 isomorphic-react/src/components/__tests__/NotificationsViewer.js 文件中。 delay 以错误的方式导入,这导致了测试错误。

如果像这样导入 delay:import { delay } from 'redux-saga' 解决问题。 =D

关于javascript - 具有异步功能的有状态 React 组件未通过 Jest 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56637899/

相关文章:

javascript - 如何设置多行打字效果以响应行间延迟

asp.net - 单元测试 IdentityDbContext

java - junit 和 psvm 有什么区别

javascript - 在 React 的模板文字中插入 html 标签

reactjs - 使用redux时,我可以在容器组件中调用api吗?

javascript - 如何使用 Jasmine 对链式方法进行单元测试

javascript - 如何在 Ionic 2 中动态创建具有特定类的模态?

javascript - 从 Firebase 获取数据时,来自 Redux Toolkit 的 createAsyncThunk 会产生未定义的负载

javascript - 将 2D 数组的 2D 网格展平为单个 2D 数组,在 JavaScript 中(功能上?)

javascript - 使用 WebCrypto 进行 AES 加密数据长度