'Should you mock modules within a beforeEach?

For example should you do something like:

(1)

beforeEach(() => {
  jest.mock('react-router-dom', () => ({
    ...(jest.requireActual('react-router-dom')),
    useLocation: () => ({
      pathName: '/',
      search: '?something=everything'
    })
  }));
})

or is importing react-router-dom like that for every test wasteful (it seems so... if you have hundreds of tests this must cause test slowdown right)?

For example instead you could do this:

(2)

let mockUseLocation;
jest.mock('react-router-dom', () => ({
  ...(jest.requireActual('react-router-dom')),
  useLocation: () => mockUseLocation
}));

beforeEach(() => {
  mockUseLocation = {
    pathName: '/',
    search: '?something=everything'
  }
})

Is there a best practice about something like this? Is my intuition correct that the second option is better than the first?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source