有人能告诉我如何在挂载调用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调用和生命周期方法还没有完成。
发布于 2017-10-12 21:05:10
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()
发布于 2021-12-07 11:58:49
作为解决办法,将其从异步转换为同步。
jest.spyOn(Api, 'get').mockReturnValue({
then: fn => fn('hello');
});https://stackoverflow.com/questions/46718663
复制相似问题