如何使用Jest测试异步组件? [英] How do test async components with Jest?

查看:517
本文介绍了如何使用Jest测试异步组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能告诉我在安装调用componendDidMount()的组件时如何开玩笑地等待一个模拟的诺言吗?

can anyone tell me how to wait in jest for a mocked promise to resolve when mounting a component that calls componendDidMount()?

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()在我的玩笑测试中被模拟

the API.get() is mocked in my jest test

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调用和生命周期方法尚未通过.

The issue is that I the expect(mountToJson(wrapper)) is returning null because the mocked api call and lifecycle methods of <Something /> haven't gone through yet.

推荐答案

Jest具有模拟假冒

Jest has mocks to fake time travelling, to use it in your case, I guess you can change your code in the following style:

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()

Alternatively to jest.runTimersToTime() you could also use jest.runAllTimers()

这篇关于如何使用Jest测试异步组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆