首页 > 解决方案 > 开玩笑模拟exports.name 无法正常工作

问题描述

我有以下js代码

exports.setupUserAccounts = config => {
  //Implementation
};

它位于“共享/用户”文件夹中。现在在测试文件中,我正在尝试使用 jest 模拟此方法(我没有使用 DI)

我正在为此编写以下代码

jest.mock('shared/user')

现在,当我运行代码时,出现以下错误

setupUserAccounts不是一种方法

我也尝试以下

jest.mock('shared/user', () => ({
  setupUserAccounts: jest.fn()
}));

现在,当我运行测试时,该函数根本没有被模拟。补充一点,我的源代码是 TypeScript 代码,我正在运行ts-jest.

标签: mockingjestjs

解决方案


这是一个单元测试工作示例:

index.ts

const { setupUserAccounts } = require('./shared/user');

export function main() {
  return setupUserAccounts();
}

shared/user/index.ts

exports.setupUserAccounts = config => {
  console.log('setupUserAccounts');
};

index.spec.ts

const { main } = require('./');
const { setupUserAccounts } = require('./shared/user');

jest.mock('./shared/user', () => {
  return {
    setupUserAccounts: jest.fn()
  };
});

test('should mock setupUserAccounts correctly', () => {
  expect(jest.isMockFunction(setupUserAccounts)).toBeTruthy();
  (setupUserAccounts as jest.MockedFunction<typeof setupUserAccounts>).mockReturnValueOnce('fake data');
  const actualValue = main();
  expect(actualValue).toBe('fake data');
});

覆盖率 100% 的单元测试结果:

 PASS  src/stackoverflow/56961691/index.spec.ts
  ✓ should mock setupUserAccounts correctly (4ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.885s, estimated 8s

源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56961691


推荐阅读