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

时间:2017-10-12 20:50:15

标签: reactjs testing jestjs

任何人都可以告诉我如何在安装调用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()

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调用和生命周期方法还没有通过。

1 个答案:

答案 0 :(得分:1)

Jest嘲笑假time travelling,在你的情况下使用它,我想你可以用以下风格改变你的代码:

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