如何使用 Jest 测试异步组件?

IT技术 reactjs testing jestjs
2021-04-23 22:04:12

谁能告诉我在安装调用的组件时如何开玩笑地等待解决的模拟PromisecomponendDidMount()

class Something extends React.Component {
    state = {
      res: null,
    };

    componentDidMount() {
        API.get().then(res => this.setState({ res }));
    }

    render() {
      if (!!this.state.res) return
      return <span>user: ${this.state.res.user}</span>;
    }
}

API.get()在我的笑话嘲笑测试

data = [
  'user': 1,
  'name': 'bob'
];

function mockPromiseResolution(response) {
  return new Promise((resolve, reject) => {
    process.nextTick(
      resolve(response)
    );
  });
}

const API = {
    get: () => mockPromiseResolution(data),
};

然后我的测试文件:

import { API } from 'api';
import { API as mockAPI } from '__mocks/api';

API.get = jest.fn().mockImplementation(mockAPI.get);

describe('Something Component', () => {
  it('renders after data loads', () => {
    const wrapper = mount(<Something />);
    expect(mountToJson(wrapper)).toMatchSnapshot();
    // here is where I dont know how to wait to do the expect until the mock promise does its nextTick and resolves
  });
});

问题是我expect(mountToJson(wrapper))正在返回,null因为<Something />尚未通过模拟的 api 调用和生命周期方法

2个回答

Jest 模拟了伪造时间旅行,在您的情况下使用它,我想您可以按以下样式更改代码:

import { API } from 'api';
import { API as mockAPI } from '__mocks/api';

API.get = jest.fn().mockImplementation(mockAPI.get);

jest.useFakeTimers(); // this statement makes sure you use fake timers

describe('Something Component', () => {
  it('renders after data loads', () => {
    const wrapper = mount(<Something />);

    // skip forward to a certain time
    jest.runTimersToTime(1);

    expect(mountToJson(wrapper)).toMatchSnapshot();
  });
});

或者jest.runTimersToTime()你也可以使用jest.runAllTimers()

作为一种解决方法,将其从异步转换为同步

jest.spyOn(Api, 'get').mockReturnValue({
  then: fn => fn('hello');
});