【发布时间】:2019-03-04 14:52:01
【问题描述】:
我正在尝试测试我编写的库函数(它在我的代码中有效),但无法使用 fs 的模拟进行测试。我有一系列函数用于处理封装在函数中的操作系统,因此应用程序的不同部分可以使用相同的调用。
我尝试按照 this question 模拟文件系统,但它似乎对我不起作用。
下面是一个简短的示例来演示我的问题的基本情况:
import * as fs from 'fs';
export function ReadFileContentsSync(PathAndFileName:string):string {
if (PathAndFileName === undefined || PathAndFileName === null || PathAndFileName.length === 0) {
throw new Error('Need a Path and File');
}
return fs.readFileSync(PathAndFileName).toString();
}
所以现在我正在尝试使用 Jest 测试这个功能:
import { ReadFileContentsSync } from "./read-file-contents-sync";
const fs = require('fs');
describe('Return Mock data to test the function', () => {
it('should return the test data', () => {
const TestData:string = 'This is sample Test Data';
// Trying to mock the reading of the file to simply use TestData
fs.readFileSync = jest.fn();
fs.readFileSync.mockReturnValue(TestData);
// Does not need to exist due to mock above
const ReadData = ReadFileContentsSync('test-path');
expect(fs.readFileSync).toHaveBeenCalled();
expect(ReadData).toBe(TestData);
});
});
我收到一个文件不存在的异常,但我预计不会调用 fs.readFileSync 的实际调用,而是使用了 jest.fn() 模拟。
ENOENT: no such file or directory, open 'test-path'
我不知道怎么做这个模拟?
【问题讨论】:
-
尝试在您的
tsconfig中启用esModuleInterop并使用import fs from 'fs'并尝试agin。import * as fs ...正在复制,因此您的直接模拟将不起作用。 -
您可以使用
jest中的 lib 模拟来模拟,而不是模拟一个函数。或者,考虑使用函数式编程模式/OO 来管理您的依赖关系。 -
@unional 我尝试了您的建议以启用 esModuleInterop,然后是
import fs from 'fs',但模拟并未发生,因为未返回模拟数据,但尝试访问明显不存在的文件。ENOENT: no such file or directory, open test-path -
那么你必须使用开玩笑的绕过模拟。就我个人而言,我不是它的朋友。我宁愿遵循函数式编程约定。
标签: typescript testing mocking jestjs