玩笑fs.unlink函数测试

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

我想开玩笑地使用ock.fs测试此deleteFile函数,但不确定如何。

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

这是我根据Stackoverflow上已发布的内容尝试过的内容,但该函数未返回。

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)

})
javascript node.js unit-testing jestjs fs
1个回答
0
投票

这是单元测试解决方案:

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

具有100%覆盖率的单元测试结果:

 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

源代码:https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61082732

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