javascript - 导出类和函数的 Jest 模拟模块
问题描述
我有一个导出一个类和 2 个函数的模块,并且该模块被导入到一个正在测试的文件中。
someFile.js
const {theclass, thefunction} = require("theModule");
const getSomeFileData = () => {
let obj = new theclass();
//some logic
return obj.getData();
}
在测试文件中,我想模拟模块“theModule”并在调用函数 obj.getData() 时返回一个已知值。在测试文件“someFile.js”时,我将如何模拟这个模块(“theModule”)?
解决方案
编辑:
.spec.ts
import { someFunction } from './index-test';
jest.mock('lodash', () => {
return {
uniqueId: () => 2,
};
});
describe('', () => {
it('', () => {
expect(someFunction()).toBe(2);
});
});
索引测试.ts
import { uniqueId } from 'lodash';
export const someFunction = () => {
return uniqueId();
};
推荐阅读
- html - html5
- javascript - 如何将 javascript 字符串传递给 javascript,然后将输出转换为字符串以传递给函数
- azure - Azure Databricks Notebook 未传递参数
- javascript - 如果我第一次打开模态框,我的第二个模态框的关闭按钮不起作用。但它只有在我打开和关闭我的第三个模式后才有效?
- python - 仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但有一个“Index”实例
- flutter - 可从顶部和底部拖动的可滚动工作表
- javascript - 从两个对象数组追加属性
- html - 如果每个导航元素有元素,则为每个导航元素添加 + 和 - 图标
- windows - 在 Rust 程序中使用 VirtualQueryEx 编辑内存时出现无限循环
- ansi-c - Ansi C如何动态调用一个CONSTANT