Monday, 4 October 2021

Trouble mocking ES6 Module using jest.unstable_mockModule

I'm attempting to mock a call to a class instance function on an ES6 module being imported by the code under test. I've followed the progress of the ES6 support and eventually stumbled onto this PR https://github.com/facebook/jest/pull/10976 which mentioned that in 27.1.1 support for jest.unstable_mockModule was added. I upgraded my version of Jest to take advantage and while the test doesn't error, it also doesn't seem to actually mock the module either.

This is the module under test:

// src/Main.mjs

import Responder from './Responder.mjs'
import Notifier from './Notifier.mjs'

export default {
  async fetch(request, environment, context) {
    let response

    try {
      response = new Responder(request, environment, context).respond()
    } catch (error) {
      return new Notifier().notify(error)
    }

    return response
  }
}

Here is the test:

// test/Main.test.mjs

import { jest } from '@jest/globals'
import main from '../src/Main.mjs'

describe('fetch', () => {
  test('Notifies on error', async () => {
    const mockNotify = jest.fn();
    
    jest.unstable_mockModule('../src/Notifier.mjs', () => ({
      notify: mockNotify
    }))

    const notifierMock = await import('../src/Notifier.mjs');
    
    await main.fetch(null, null, null)

    expect(mockNotify).toHaveBeenCalled()
  })
})

I'm trying to mock the call to Notify to expect it to have been called and while this will run, it raises an exception from inside the Notifier.notify() that is supposed to be mocked, so it appears that it isn't being mocked at all.

What am I missing? Any help is much appreciated. 🙏



from Trouble mocking ES6 Module using jest.unstable_mockModule

No comments:

Post a Comment