0
目前,在我的反應應用程序中,我有一個ajax調用方法,它有setState
如果ajax調用成功,我已經嘲笑api響應,似乎該方法不會執行任何操作,除了返回響應React |單元測試如何在成功的AJAX調用中測試方法?
例如,
// This is the ajax method
getProductData(productId) {
// I already successfully mocked the response
getProductById(productId).then(productResponse => {
// I am trying make sure that the state is being updated with response data
this.setState({
product: productResponse.data
})
});
}
這是我的測試
test('Make sure my state is being updated with response data', async() => {
const component = shallow(
<MyComponent />
);
component.instance().getProductData(1);
// This is where my test failed, as it's not updating anything
expect(component.state().product).to.equal('SOMETHING');
});
使用setTimeout
異步測試該方法試圖通過約拿Pereira的建議
test('Make sure my state is being updated with response data', async() => {
const component = shallow(
<MyComponent />
);
component.instance().getProductData(1);
// Using settimeout still not solving the problem,
setTimeout(() => {
expect(component.state().product).to.equal('SOMETHING');
// Not even this, that means the test totally ignored the setTimeout
expect('abc').to.equal('cba');
}, 0)
});
它真的有用嗎?我嘗試使用'setTimeout',它看起來像我的測試完全忽略它。 –