Overwriting a module import for mocking during tests?

Viewed 85

I am writing unit tests and would like to mock a function in a module but avoid using jest.mock. Is such a thing possible?

If not, how does jest.mock work and will it survive the transition from commonjs to esmodules in Node?

import * as foo from './foo'

describe('foo', () => {
  let mockFn: jest.Mock

  beforeEach(() => {
    mockFn = jest.fn()
    
    Object.defineProperty(foo, 'bar', {
      value: mockFn,
      writable: true,
      configurable: true,
    })
  })

  it('Should not throw', () => {
    const testFunc = () => foo()
    expect(testFunc).not.toThrow()
  })
})
0 Answers
Related