React & Jest global.confirm 测试之间没有更新

React & Jest global.confirm not updating between tests

我有一个正在尝试为其编写测试的现有应用程序。我有一个组件函数,它使用 window.confirm 框来获取用户输入(不是我的代码),如下所示:

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.confirm 不会为第二次测试更新。如果我将第一个测试设置为 false 那么它显然失败了,但第二个测试通过了。如果我将第一个设置为 true,则第一个通过但第二个失败,因为 global.confirm = jest.fn(() => false) 实际上不会导致 window.confirm 评估为 false。如果我注释掉第一个,那么第二个就可以通过了。

我试过模拟 window.confirm,我得到了完全相同的行为。

这是一个明显的问题。我忘了清除来自 NetworkWebAPIUtils.unassignSeat.

的模拟调用
afterEach(function () {
    NetworkWebAPIUtils.unassignSeat.mockClear();
});