如何使用 Jest 测试异步组件? [英] How do test async components with 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 has mocks to fake 时间旅行,要在您的情况下使用它,我想您可以按以下样式更改代码:
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屋!