mocking - jest.mock 与命名导出如何监视

标签 mocking jestjs

假设我在文件中具有以下命名导出 customer.ts

export const saveDetails = ()=>{}
export const loadDetails = ()=>{}

假设我在另一个文件中使用它

import {saveDetails, loadDetails} from './customer.ts'

我想用自定义实现来模拟'./customer.ts'。为此,我使用以下代码
const mockSaveDetails = jest.fn().mockImplementation(() => {});
jest.mock('./customer.ts', () => {
  return {
    saveDetails: mockSaveDetails
  };
});

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

ReferenceError: Cannot access 'mockSaveDetails' before initialization



根据 https://jestjs.io/docs/en/es6-class-mocks 上的文档我知道模拟被提升到顶部,异常(exception)情况是变量具有前缀 mock .因此,根据文档,这应该可以正常工作吗?如果不是,提供模拟实现并监视这些实现的替代方法是什么(例如查看对 saveDetails 的调用次数),并带有某些参数。

最佳答案

这是解决方案:
index.ts :

import { saveDetails, loadDetails } from "./customer";

export function main() {
  saveDetails();
  loadDetails();
}
customer.ts :

export const saveDetails = () => {
  console.log("real save details");
};
export const loadDetails = () => {
  console.log("real load details");
};
index.spec.ts :

import { main } from "./";
import { saveDetails, loadDetails } from "./customer";

jest.mock("./customer.ts", () => {
  return {
    saveDetails: jest.fn(),
    loadDetails: jest.fn()
  };
});

describe("main", () => {
  it("should mock correctly", () => {
    main();
    expect(saveDetails).toBeCalledTimes(1);
    expect(loadDetails).toBeCalledTimes(1);
  });
});

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

PASS  src/stackoverflow/59024742/index.spec.ts
  main
    ✓ should mock correctly (5ms)

----------|----------|----------|----------|----------|-------------------|
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:        5.626s, estimated 9s

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

关于mocking - jest.mock 与命名导出如何监视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59024742/

相关文章:

java - 如何对 Clob 转换为 String 进行单元测试?

java - Easymock:捕获的顺序重要吗?

c++ - 谷歌模拟析构函数

typescript - 在 typescript 中为服务文件编写测试用例

docker - 如何使刻度线显示为绿色?

reactjs - Jest 有时找不到模块

javascript - 类型错误 : Invalid attempt to destructure non-iterable instance React/Jest

python - 如何在 for 循环中重置模拟迭代器?

javascript - 在 JS 中模拟 API 调用

javascript - '.toMatchObject' 和 'objectContaining' 有什么区别