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

问题描述 投票:0回答:1

我创建了一个函数,该函数基本上遍历数组并创建文件。我开始使用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();
});

谁能指出我正确的方向?

node.js typescript mocking jestjs fs
1个回答
0
投票

由于您要测试实现,因此可以尝试以下操作:

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,您可以阅读有关自动模拟的更多信息>

© www.soinside.com 2019 - 2024. All rights reserved.