用 Jest 模拟 es6 模块

问题描述 投票:0回答:1

我正在为使用 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__
    中使用手动模拟。
  • 查看github上的几个示例,似乎没有什么与我正在做的事情相去甚远。
  • 添加
     testEnvironment: 'jest-environment-node',
    ,如https://stackoverflow.com/a/52816572/4541769
  • 我什至尝试过随机的巴别塔巫术,如这个问题中所述,年龄可疑是相关的,
  • 以及
    __esModule: true,
    属性,在我的情况下似乎不需要,因为我没有同时使用默认模块和命名模块。

我不认为这是 sendgrid 问题,因为我对 Google 秘密管理器也有同样的问题。我的配置中是否缺少某些内容?我知道我以前写过类似的测试,但无法发现差异。

javascript unit-testing jestjs mocking
1个回答
0
投票

事实证明,问题在于提升,以及对 jest 和 es6 不断发展的支持,这是可以理解的。使用

jest.unstable_mockModule
await import(...
的解决方案有效。

https://stackoverflow.com/a/71044616/4541769

© www.soinside.com 2019 - 2024. All rights reserved.