1

I am running into an issue where my tests inside a describe block aren't getting all API calls reset between tests. If I run an *.only test, then the expected fetch.mock.calls[i] index changes.

I would have expected each test to have the same number of calls because of the beforeEach(jest.clearAllMocks); block:

describe('Account Info', () => {

  beforeEach(jest.clearAllMocks);

  test('edit names', async () => {
    const { findByDisplayValue, findByTestId, getByRole } = render(
      <AccountInfo />,
      {},
      { ...mockGetUserData }
    );
...
    expect(fetch).toHaveBeenCalledTimes(3));
    expect(fetch.mock.calls[0][1]).toMatchInlineSnapshot(`...`);
  });

  test('edit phone', async () => {
    const { findByTestId, getByRole } = render(
      <AccountInfo />,
      {},
      { ...mockGetUserData }
    );
...
    expect(fetch).toHaveBeenCalledTimes(2));  // notice it's 2, not 3 like above
    expect(fetch.mock.calls[0][1]).toMatchInlineSnapshot(`...`);

  });

This works fine, however, let's say I am working on updating the "edit phone" spec. So I change the test to say test.only and now it fails on:

    expect(fetch).toHaveBeenCalledTimes(2));  // notice it's 2, not 3 like above

Since now fetch was called 3 times.

It seems that a hook inside the AccountInfo component which calls my organization API is the culprit. It's not being cleared, and I don't understand why.

I have resolved the flakiness by putting all the tests into a single spec which is what @kentcdodds recommends, but I'd like to understand more about why Jest might not be resetting as expected.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Phil Lucks
  • 2,704
  • 6
  • 31
  • 57

0 Answers0