从导入的文件中模拟函数,同时检查它是否已被调用

Mocking a function from an imported file, but also checking that it has been called

我正在测试的文件从另一个文件导入了一个函数。为了阻止来自 运行ning 的外部函数,我模拟了导入:

jest.mock("./anotherFile", () => ({
  outsideFunc: jest.fn()
}));

但是我现在需要为一个函数编写单元测试来检查 outsideFunc 是否被调用。不关心 return,只是它被调用了。

正在测试的系统

function myFunc() {
  outsideFunc();
}

测试

describe("Testing myFunc", () => {
    it("Should call outsideFunc", () => {
      myFunc();
      expect(outsideFunc).toHaveBeenCalled();
    });
  });

当我 运行 测试时,我得到:

ReferenceError: outsideFunc is not defined

我明白为什么我会收到这个错误,通常我会有类似的东西

const outsideFuncMock = jest.fn() 

但在这种情况下,我在导入时已经模拟了该函数以阻止它被调用,所以我有点迷茫。

我的测试套件

jest.mock("./anotherFile", () => ({
  outsideFunc: jest.fn()
}));

describe("Testing myFunc", () => {
  it("Should call outsideFunc", () => {
    myFunc();
    expect(outsideFunc).toHaveBeenCalled();
  });
});

你快完成了,这是解决方案:

文件夹结构:

.
├── anotherFile.ts
├── index.spec.ts
└── index.ts

0 directories, 3 files

index.ts:

import { outsideFunc } from './anotherFile';

export function myFunc() {
  outsideFunc();
}

anotherFile.ts:

export const outsideFunc = () => 1;

index.spec.ts:

import { myFunc } from './';
import { outsideFunc } from './anotherFile';

jest.mock('./anotherFile.ts', () => ({
  outsideFunc: jest.fn()
}));

describe('Testing myFunc', () => {
  it('Should call outsideFunc', () => {
    myFunc();
    expect(jest.isMockFunction(outsideFunc)).toBeTruthy();
    expect(outsideFunc).toHaveBeenCalled();
  });
});

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

 PASS  src/Whosebug/58413956/index.spec.ts
  Testing myFunc
    ✓ Should call outsideFunc (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.129s, estimated 7s

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