Jest - Mocking and testing the node.js filesystem

Viewed 8222

I have created a function which basically loops over an array and create files. I'm starting to get into testing using Jest to have some extra security in place to make sure everything works however I'm experiencing some issues trying to mock the Node.js filesystem.

This is the function I wish to test - 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' },
];

I've been reading around but can't really figure out how to test this with jest. No examples to look at. I've tried to install mock-fs which should be a simple way of getting up and running with a mock version of the Node.js FS module but I honestly don't know where to start. This is my first attempt at making a simple test - which causes an error, says 'no such file or directory' - 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();
});

Anyone who can point me in the right direction?

1 Answers

Since you want to test you implementation you can try this:

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 you can read more about the auto-mocking

Related