0

I have an existing application that I am trying to write tests for. I have a component function that uses a window.confirm box to get user input (not my code) like this:

if (window.confirm('Are you sure to unassign?')) {
    NetworkWebAPIUtils.unassignSeat(this.state.seatnetwork.seat.id, this.state.seatnetwork.network.id, this.props.rank);
}

I am trying to write tests for both paths:

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();
});

The problem is that global.confirm will not update for the second test. If I set the first test to false then it obviously fails but the second one passes. If I set the first to true then the first passes but the second fails because global.confirm = jest.fn(() => false) doesn't actually cause window.confirm to evaluate to false. If I comment out the first then the second passes just fine.

I have tried mocking window.confirm and I get the exact same behavior.

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
Gremash
  • 8,158
  • 6
  • 30
  • 44

1 Answers1

1

It was an obvious issue. I forgot to clear the mock calls from NetworkWebAPIUtils.unassignSeat.

afterEach(function () {
    NetworkWebAPIUtils.unassignSeat.mockClear();
});
Gremash
  • 8,158
  • 6
  • 30
  • 44