jon*_*nes 5 mocking fs node.js typescript jestjs
我创建了一个函数,它基本上循环遍历数组并创建文件。我开始使用 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' },
];
Run Code Online (Sandbox Code Playgroud)
我一直在阅读周围的内容,但无法真正弄清楚如何用笑话来测试它。没有例子可看。我尝试安装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();
});
Run Code Online (Sandbox Code Playgroud)
谁能指出我正确的方向?
既然你想测试你的实现,你可以尝试这个:
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
);
});
});
Run Code Online (Sandbox Code Playgroud)
在这里您可以阅读有关自动模拟的更多信息
| 归档时间: |
|
| 查看次数: |
12048 次 |
| 最近记录: |