【问题标题】:jest.mock() method returns undefined when passing a valid module namejest.mock() 方法在传递有效的模块名称时返回 undefined
【发布时间】:2021-08-29 21:56:54
【问题描述】:

我有一个依赖项,我试图用 jest.mock() 方法模拟,但它返回 undefined。

我已经检查过它是一个有效的导入,因为我的测试使用依赖项而不是模拟运行,但不知何故它不断返回 undefined

我的 .spec.ts 文件如下所示:

import validator from 'validator';

jest.mock('validator', () => ({
  isEmail(): boolean {
    return true;
  },
}));

describe('EmailValidator Adapter', () => {
  test('Should return false if validator returns false', () => {
    const sut = new EmailValidatorAdapter();
    jest.spyOn(validator, 'isEmail').mockReturnValueOnce(false);
    const isValid = sut.isValid('invalid_email@mail.com');
    expect(isValid).toBe(false);
  });
});

我的 jest.config.js 文件如下所示:

module.exports = {
  roots: ['<rootDir>/src', '<rootDir>/node_modules'],
  collectCoverageFrom: [
    '<rootDir>/src/**/*.ts',
    '!<rootDir>/src/**/*-protocols.ts',
    '!**/protocols/**',
  ],
  moduleDirectories: ['node_modules', '<rootDir>'],
  coverageProvider: 'babel',
  coverageDirectory: 'coverage',
  testEnvironment: 'node',
  transform: {
    '.+\\.ts': 'ts-jest',
  },
};

如你所见,我已经将我的 node_modules 文件夹放在了 jest 配置文件的 roots 数组中

【问题讨论】:

    标签: node.js typescript unit-testing jestjs ts-jest


    【解决方案1】:

    我在这里找到了解决方法:https://github.com/kulshekhar/ts-jest/issues/120

    这似乎与 Typescript 处理默认导出的方式有关

    所以,我将代码更改为:

    jest.mock('validator', () => {
      return {
        default: {
          isEmail: jest.fn().mockImplementation(() => true),
        },
      };
    });
    
    

    【讨论】:

    • 谢谢!我被困在这个变化上几个小时。在我的情况下,我正在执行像 import { ModuleName } from '../path/..' 这样的导入,并且必须确保我正在返回:{ ModuleName: { ... my mocked object ... } }
    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 2020-03-16
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多