我已经创建了一个函数,它基本上在数组上循环并创建文件。我开始使用Jest进行测试,以获得一些额外的安全性,以确保一切正常运行,然而,我在试图模拟Node.js文件系统时遇到了一些问题。
这是我想测试的函数- function.ts
export function generateFiles(root: string) {
fs.mkdirSync(path.join(root, '.vscode'));
files.forEach((file) => {
fs.writeFileSync(
path.join(root, file.path, file.name),
fs.readFileSync(path.join(__dirname, 'files', file.path, file.name), 'utf-8')
);
});
}
const files = [
{ name: 'tslint.json', path: '' },
{ name: 'tsconfig.json', path: '' },
{ name: 'extensions.json', path: '.vscode' },
];我一直在阅读,但实际上不知道如何用玩笑来测试这个。没有例子可看。我尝试过安装mock-fs,这应该是使用模拟版本的Node.js FS模块启动和运行的一种简单方法,但老实说,我不知道从哪里开始。这是我第一次尝试做一个简单的测试-这会导致错误,说‘没有这样的文件或目录’- function.test.ts
import fs from 'fs';
import mockfs from 'mock-fs';
beforeEach(() => {
mockfs({
'test.ts': '',
dir: {
'settings.json': 'yallo',
},
});
});
test('testing mock', () => {
const dir = fs.readdirSync('/dir');
expect(dir).toEqual(['dir']);;
});
afterAll(() => {
mockfs.restore();
});有谁能为我指明正确的方向吗?
发布于 2019-10-16 13:39:59
由于您想测试您的实现,所以可以尝试如下:
import fs from 'fs';
import generateFiles from 'function.ts';
// auto-mock fs
jest.mock('fs');
describe('generateFiles', () => {
beforeAll(() => {
// clear any previous calls
fs.writeFileSync.mockClear();
// since you're using fs.readFileSync
// set some retun data to be used in your implementation
fs.readFileSync.mockReturnValue('X')
// call your function
generateFiles('/root/test/path');
});
it('should match snapshot of calls', () => {
expect(fs.writeFileSync.mock.calls).toMatchSnapshot();
});
it('should have called 3 times', () => {
expect(fs.writeFileSync).toHaveBeenCalledTimes(3);
});
it('should have called with...', () => {
expect(fs.writeFileSync).toHaveBeenCalledWith(
'/root/test/path/tslint.json',
'X' // <- this is the mock return value from above
);
});
});这里,您可以阅读更多关于自动模拟的内容。
https://stackoverflow.com/questions/58413428
复制相似问题