typescript - Jest mock 没有从另一个模块 Typescript 导出函数
问题描述
我希望能够模拟未导出但在我要测试的函数中使用的函数。这是小代码示例。
文件.ts
const hello = () => {
console.log('hello');
}
export const say = () =>{
hello ()
return 10;
}
文件.test.ts
import {say } from 'file';
describe("Test ", () => {
it("test", async () => {
// how to mock hello before that ?
say();
})
})
解决方案
Jest 能够模拟 ES 模块(整个 ts/js 文件),但使用您当前的实现是不可能的。
我的建议是提取function hello
到另一个名为的文件hello.ts
中并导入以供function say
使用。然后 jest 可以模拟hello.ts
示例代码:
// hello.ts
export const hello = () => {
console.log('hello');
}
// say.ts
import { hello } from "./hello";
export const say = () =>{
hello();
return 10;
}
// say.test.ts
import { say } from './say';
jest.mock('./hello', () => {
return {
hello: jest.fn().mockImplementation(() => {
console.log('mock hello');
})
};
});
describe('Test ', () => {
it('test', async () => {
// how to mock hello before that ?
say();
});
});
输出:
推荐阅读
- python - 从熊猫数据框创建边缘列表非常慢
- sql - 按列显示数据
- python - 验证键盘输入仅支持 Python 中的单词
- java - 尝试在空对象引用错误时调用虚拟方法“void android.widget.Button.setEnabled(boolean)”
- django - 为某个类别中的每个作者选择页数最少的书
- mysql - 不显示哪个条目具有不需要的值的名称
- php - Laravel 5.8 请求值为 null 而不是默认值
- javascript - 我将如何获得选定的 div 元素颜色变化并将每个选定的 Div elem 存储在 ReactJS 中?
- python - 如何使用 python regex 解析此日志并使用 pandas 导出到 excel(可选)?
- c++11 - 比较“组合”算法的两种实现之间的复杂性