我有一个我试图编写测试的现有应用程序。我有一个使用窗口的组件函数。
if (window.confirm('Are you sure to unassign?')) {
NetworkWebAPIUtils.unassignSeat(this.state.seatnetwork.seat.id, this.state.seatnetwork.network.id, this.props.rank);
}
我正在尝试为这两种路径编写测试:
it('should call endpoint when user selects yes', function () {
global.confirm = jest.fn(() => true);
seatUpdateRow.instance().handleChangeAssigned({target: {value: true}});
expect(NetworkWebAPIUtils.unassignSeat.mock.calls.length).toBe(1);
expect(NetworkWebAPIUtils.unassignSeat.mock.calls[0].length).toBe(3);
expect(NetworkWebAPIUtils.unassignSeat.mock.calls[0][0]).toBe(1234);
expect(NetworkWebAPIUtils.unassignSeat.mock.calls[0][1]).toBe(5678);
expect(NetworkWebAPIUtils.unassignSeat.mock.calls[0][2]).toBe(1);
});
it('should not call endpoint when user selects no', function () {
global.confirm = jest.fn(() => false);
seatUpdateRow.instance().handleChangeAssigned({target: {value: true}});
expect(NetworkWebAPIUtils.unassignSeat).not.toHaveBeenCalled();
});
问题是Global.Confirs不会更新第二个测试。如果我将第一个测试设置为false
,那么它显然会失败,但第二个通过。如果我将第一个设置为true
,则第一个通过,但是第二次失败,因为global.confirm = jest.fn(() => false)
实际上并没有导致窗口。如果我发表第一个,那么第二次通过就可以了。
我尝试了模拟窗口。
这是一个明显的问题。我忘了从Networkwebapiutils.unassignseat中清除模拟电话。
afterEach(function () {
NetworkWebAPIUtils.unassignSeat.mockClear();
});