【发布时间】:2020-07-29 01:45:02
【问题描述】:
我正在使用 React 16.13.0 并尝试使用 jest 来测试是否调用了方法。我对如何使用模拟感到非常困惑。我有这个方法...
class Missions {
...
async removeVolunteerFromMission(missionId: string) {
const missions = this.repo();
const mission = await missions.findById(missionId);
mission.volunteerId = '';
mission.status = MissionStatus.unassigned;
return this.repo().update(mission);
}
...
export default new Missions();
如何测试我的“findById”方法是否被调用?我有这个测试方法...
it('unassigns volunteer', async() => {
const missionId = "1234";
const mission = new Mission();
mission.missionId = missionId;
const mockFindById = jest.fn().mockResolvedValue(mission);
const mockUpdate = jest.fn().mockResolvedValue(mission);
const baseRepo = {
findById: () => mockFindById,
update: () => mockUpdate
};
jest.spyOn(missions, 'repo').mockReturnValue(baseRepo);
await missions.removeVolunteerFromMission(missionId);
console.log("mission === " + mission);
expect(mockFindById).toHaveBeenCalledTimes(1);
});
但这失败了
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
29 | console.log("mission === " + mission);
30 |
> 31 | expect(mockFindById).toHaveBeenCalledTimes(1)
| ^
我怎么知道这实际上是怎么调用的?
【问题讨论】:
-
this.repo()会发生什么?模拟 3rd 方模块比模拟实例方法更容易(也更可靠) -
findById: mockFindById -
哈,我应该更有信心......只是不确定如何准确地表达问题所在。添加为答案并附有简要说明。
标签: reactjs promise mocking jestjs