Mocking es6 imported default module with Jest

I am writing a test for a function sendEmail that uses npm package @sendgrid/mail. I’d like to mock @sendgrid/mail in my function and then make assertions on the mocked functions, but for some reason I can’t get my code to use the mocked version. The version imported in the test is always the real one, and the actual module is used in my sendEmail.

Based on the docs it seems like

import { jest } from '@jest/globals';
import sgMail from '@sendgrid/mail';
import { sendEmail } from './functions.js';

jest.mock('@sendgrid/mail');
describe('functions.js', () => {
  test('email subject is generated correctly', async () => {
    console.log(sgMail);

    await sendEmail('test');
    // expect(sgMail.send).toHaveBeenCalledWith('hi');
  });
});

I have tried:

  • providing factory functions
  • using manual mocks in __mocks__ instead.
  • Looking at several examples on github,nothing seems too far from what I am doing.
  • adding testEnvironment: 'jest-environment-node', like https://stackoverflow.com/a/52816572/4541769
  • I have even tried random babel voodoo as described in this question of dubious age to be relevant,
  • as well as the __esModule: true, property which doesn’t seem to be required in my case as I’m not using both default and named modules.

I don’t think this is a sendgrid issue as I have the same problem with Google secret manager. Is there something in my configuration I’m missing? I know I’ve written similar tests before, but can’t spot the difference.