//我的用于调用的单元测试用例。我正在尝试模拟提取呼叫。当时我正在检查状态是否正在更新。我该怎么办
it('button press fetch data from json placeholder', async () => {
global.fetch = jest.fn(
() =>
new Promise(resolve =>
resolve({
ok: true,
json: () => Promise.resolve([1]),
}),
),
);
const button = wrapper.find('[testID="inputButton"]');
button.props().onPress();
wrapper.update();
console.log(wrapper.instance());
expect(wrapper.instance().state.responseData.length).toBe(1);
});
//错误
Expected: 1
Received: 0
44 | wrapper.update();
45 | console.log(wrapper.instance());
> 46 | expect(wrapper.instance().state.responseData.length).toBe(1);
| ^
47 | });
48 | });
//组件中的实际代码
buttonPress = () => {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(res => res.json())
.then(response => {
this.setState({
responseData: response,
});
});
};
答案 0 :(得分:0)
尝试像这样解决承诺:
global.fetch = jest.fn(() => new Promise.resolve({ok: true, json: <resolved value>})
您通常想通过以下方式来兑现您的所有承诺:
return expect(Promise).resolves/rejects.<assertion>
或等待结果。
答案 1 :(得分:0)
//在应用setTimeout()之后,我可以期望更新后的状态值
it('button press fetch data from json placeholder', async done => {
global.fetch = jest.fn(
() =>
new Promise(resolve =>
resolve({
ok: true,
json: () => Promise.resolve([1, 2]),
}),
),
);
const button = wrapper.find('[testID="inputButton"]');
button.props().onPress();
wrapper.update();
setTimeout(() => {
expect(wrapper.instance().state.responseData.length).toBe(2);
done();
});
});