【发布时间】:2018-05-02 05:27:31
【问题描述】:
我的 React 组件使用 Axios 调用 API。在我的单元测试中,我试图通过使用来自 Sinon 的 Sandbox 存根来模拟 Axios,如下所示:
sandbox1 = sandbox.create();
const resolved = new Promise((r) => r([{ id: 1, name: 'PetA' }, { id: 2, name:'PetB' }]));
sandbox1.stub(axios, 'get').returns(resolved);
我想测试下面这段代码
this.setState(
({ testing }) => ({
testing: {
...testing,
[testKey]: {
isExecuting: true,
response: null
}
}
}),
() => {
axios(req)
.then(r => {
this.setState(state => {
const cancelled =
state.testing &&
state.testing[testKey] &&
state.testing[testKey]['cancelled'];
return !cancelled
? {
test: {
...state.test,
[testKey]: {
isExecuting: false,
cancelled: false,
response: r
}
}
}
: undefined;
});
})
this is followed by catch block
and closed paranthesis of setState
问题是当我使用 stubbed axios 运行测试时,如开头所示,我总是得到以下结果状态
{ testing: { 'get_/pets': { isExecuting: true, response: null } } }
这意味着 axios 没有解决承诺,尽管在存根时给出了指令。请帮忙。
【问题讨论】:
标签: reactjs unit-testing axios sinon