Should mocks created in beforeEach or reset in afterEach?

Viewed 29

In order to reset the mocks, should we use beforeEach and create the mock again or define mock in one place and use afterEach to reset mocks? Does creating mocks in beforeEach have huge impact on the test performance? In general what would be the best practice in unit testing: reseting the mock or creating a new one?

Here is an example with beforeEach:

interface X {
  getX(): string;
}

describe('withBeforeEach', () => {
  let mockX: X;
  beforeEach(() => {
    mockX = {
      getX: jest.fn()
    };
  });
});

Here is an example with afterEach:

interface X {
  getX(): string;
}

describe('withAfterEach', () => {
  const mockX: X = {
    getX: jest.fn()
  };
  afterEach(() => {
    jest.resetAllMocks();
  });
});
0 Answers
Related