我正在为使用 npm 包
sendEmail
的函数 @sendgrid/mail
编写测试。我想在我的函数中模拟 @sendgrid/mail
,然后对模拟函数进行断言,但由于某种原因,我无法让我的代码使用模拟版本。测试中导入的版本始终是真实的,我的sendEmail
中使用的是实际模块。
根据文档看起来像
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');
});
});
我已经尝试过:
__mocks__
中使用手动模拟。 testEnvironment: 'jest-environment-node',
,如https://stackoverflow.com/a/52816572/4541769__esModule: true,
属性,在我的情况下似乎不需要,因为我没有同时使用默认模块和命名模块。我不认为这是 sendgrid 问题,因为我对 Google 秘密管理器也有同样的问题。我的配置中是否缺少某些内容?我知道我以前写过类似的测试,但无法发现差异。
事实证明,问题在于提升,以及对 jest 和 es6 不断发展的支持,这是可以理解的。使用
jest.unstable_mockModule
和 await import(...
的解决方案有效。