Ali Stoltz
Ali Stoltz

Reputation: 1

jest testing fs.unlink function

I would like to use a mock.fs in jest to test this deleteFile function but I am not sure how.

function deleteFile(fileName) {
  fs.unlink(fileName, (err) => {
    if (err) throw err;
    console.log('file was deleted.')
  }) 
};

This is what I have attempted based on what is already posted on Stackoverflow, but the function is not returning.

const fs = require('fs')

jest.mock('fs');

test('mock delete', () => {
  const mockDelete = jest.fn(fs.unlink(fs, (err) => {
    if (err) throw err;

    else {
      console.log('file was deleted.');
      return True;
    }

  }))

  expect(mockDelete).toHaveReturnedWith(1)

})

Upvotes: 0

Views: 2025

Answers (1)

Lin Du
Lin Du

Reputation: 102337

Here is the unit test solution:

index.js:

const fs = require('fs');

export function deleteFile(fileName) {
  fs.unlink(fileName, (err) => {
    if (err) throw err;
    console.log('file was deleted.');
  });
}

index.test.js:

const { deleteFile } = require('./');
const fs = require('fs');

jest.mock('fs', () => {
  const mFs = { unlink: jest.fn() };
  return mFs;
});

describe('61082732', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  it('should unlink file', () => {
    fs.unlink.mockImplementationOnce((filename, callback) => {
      callback(null);
    });
    const logSpy = jest.spyOn(console, 'log');
    const filename = 'avatar.jpg';
    deleteFile(filename);
    expect(fs.unlink).toBeCalledWith(filename, expect.any(Function));
    expect(logSpy).toBeCalledWith('file was deleted.');
  });

  it('should throw an error', () => {
    const mError = new Error('not found');
    fs.unlink.mockImplementationOnce((filename, callback) => {
      callback(mError);
    });
    const logSpy = jest.spyOn(console, 'log');
    const filename = 'avatar.jpg';
    expect(() => deleteFile(filename)).toThrowError(mError);
    expect(fs.unlink).toBeCalledWith(filename, expect.any(Function));
    expect(logSpy).not.toBeCalled();
  });
});

unit test results with 100% coverage:

 PASS  stackoverflow/61082732/index.test.js (8.797s)
  61082732
    ✓ should unlink file (14ms)
    ✓ should throw an error (1ms)

  console.log node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866
    file was deleted.

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.js |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        10.169s

source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61082732

Upvotes: 3

Related Questions