Jest: Testing modules with side effects

Node.js and Jest will cache modules you require. To test modules with side effects you’ll need to reset the module registry between tests:

const modulePath = '../module-to-test'

afterEach(() => {
  jest.resetModules()
})

test('first test', () => {
  // Prepare conditions for the first test
  const result = require(modulePath)
  expect(result).toMatchSnapshot()
})

test('second text', () => {
  // Prepare conditions for the second test
  const fn = () => require(modulePath)
  expect(fn).toThrow()
})

Leave a Reply

Your email address will not be published. Required fields are marked *