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

任何人都可以告诉我如何在安装调用组件时开玩笑地等待一个模拟的诺言解决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调用和生命周期方法。

回答:

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测试异步组件? 的全部内容, 来源链接: utcz.com/qa/415525.html

回到顶部