gpt4 book ai didi

node.js - Jest - 模拟和测试 node.js 文件系统

转载 作者:行者123 更新时间:2023-12-04 12:10:46 26 4
gpt4 key购买 nike

我创建了一个函数,它基本上遍历数组并创建文件。我开始使用 Jest 进行测试以获得一些额外的安全性以确保一切正常,但是我在尝试模拟 Node.js 文件系统时遇到了一些问题。

这是我想测试的功能 - 函数.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' },
];

我一直在阅读,但无法真正弄清楚如何用 Jest 来测试这个。没有例子可以看。我试过安装 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();
});

谁能指出我正确的方向?

最佳答案

既然你想测试你的实现,你可以试试这个:

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
);
});
});

Here您可以阅读有关自动模拟的更多信息

关于node.js - Jest - 模拟和测试 node.js 文件系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58413428/

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