gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 18:20:55 34 4
gpt4 key购买 nike

假设我在文件中具有以下命名导出 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com