我正在尝试测试函数removeBuilding()的错误情况,其中API调用失败。我正在模拟对错误的API调用以进入catch块,然后该catch块调用displayError()。我的测试期望看到displayError被调用,却看不到任何错误,但是该函数正在运行并打印到控制台,因此出于某种原因,开玩笑根本无法告诉它正在被调用。
正在测试的功能:
removeBuilding = index => {
let { allBuildings } = this.state;
const buildings = this.state.allBuildings.filter(building => building.campus_id === this.props.selectedCampus);
if (index >= 0 && index <= buildings.length - 1) {
const building = buildings[index];
axios
.delete(`/api/buildings/${building.id}`)
.then(() => {
allBuildings = allBuildings.filter(function(value) {
return value !== building;
});
this.setState({
allBuildings,
});
})
.catch(error => {
// Test successfully reaches this point!
this.props.displayError(error);
});
}
};
测试:
it.only('fails to make axios delete call, and displays error', () => {
let displayErrorMock = jest.fn(console.log("testing"));
wrapper = shallowWithIntl(
<AddBuildingList
displayError={displayErrorMock}
/>
);
deleteSpy = jest.spyOn(axios, 'delete').mockRejectedValueOnce(error);
wrapper.instance().setState({ allBuildings : [newBuilding] });
wrapper.instance().removeBuilding(0);
expect(displayErrorMock).toHaveBeenCalled();
});
});
测试输出失败:
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
184 | wrapper.instance().setState({ allBuildings : [newBuilding] });
185 | wrapper.instance().removeBuilding(0);
> 186 | expect(displayErrorMock).toHaveBeenCalled();
| ^
187 | });
188 | });
189 | });
at Object.<anonymous> (tests/Components/AddBuildingList/AddBuildingList.test.js:186:32)
console.log tests/Components/AddBuildingList/AddBuildingList.test.js:177
testing
编辑 我使用this答案找出了问题所在。基本上,由于axios调用返回了一个promise,因此.then和.catch中的代码直到promise被解决(或拒绝)后才执行,因此Expect(..)发生在它所期望的函数调用之前。 它通过定义来解决
const flushPromises = () => new Promise(setImmediate)
并放置
await flushPromises();
恰好在正在测试要在.then和.catch中调用的函数的Expect语句之前
此方法起作用的原因与setImmediate behavior有关,并且在JavaScript microtasks queue中处理多个承诺的方式
答案 0 :(得分:0)
函数模拟不正确,为了使函数在调用时调用控制台,应该为:
$ pip install -e "git+https://git.example.com/MyProject.git@v1.0#egg=MyProject"
这不需要确认是否以这种方式被调用,因为jest.fn(() => console.log("testing"))
断言提供了被调用的保证,只要很明显地断言了正确的函数即可。
测试应为toBeCalled
,async
在断言时不应该被调用。 displayErrorMock
无法测试,因为它不会返回可以在测试中链接的承诺。它应包含:
removeBuilding
然后可以等待测试:
return axios
...