0

在下面的代码中,我有一个函数根据提供的配置在文件系统中查找文件。

const fs = require('fs');
const { promisify } = require('util');

const lstat = promisify(fs.lstat);

async function doSomething(someFilePath) {
    try {
       const stats = await lstat(someFilePath);
    } catch (err) {
       throw err;
    }

    // do something with the file stats
}

module.exports = doSomething;

从这里我试图测试该doSomething功能,但它失败了,因为我提供的文件路径实际上并不存在。当我lstatSync使用promisify.

const fs = require('fs');
const sinon = require('sinon');

const doSomething = require('./doSomething');

describe('The test', function() {

    let lstatStub;

    beforeEach(function() {
        lstatStub = sinon.stub(fs, 'lstatSync');
    });

    afterEach(function() { sinon.restore() });

    it('should pass', async function() {
        lstatStub.withArgs('image.jpg').returns({
            isFile: () => true,
            isDirectory: () => false,
        });

        assert(await doSomething('image.jpg')).ok();
    });

})

它现在失败了,因为Error: ENOENT: no such file or directory, lstat 'image.jpg'. 我尝试将存根包装或将ed 函数promisify导出到测试中以存根。promisify两者都没有工作。

我如何存根一个promisifyedfs方法?

4

1 回答 1

0

您可以使用Link Seams 和proxyquire包来存根promisify函数。

例如

main.js

const fs = require('fs');
const { promisify } = require('util');

const lstat = promisify(fs.lstat);

async function doSomething(someFilePath) {
  return await lstat(someFilePath);
}

module.exports = doSomething;

main.test.js

const sinon = require('sinon');
const proxyquire = require('proxyquire');
const { expect } = require('chai');

describe('61412987', () => {
  it('should pass', async () => {
    const lstatStub = sinon.stub().resolves('fake data');
    const utilStub = { promisify: sinon.stub().callsFake(() => lstatStub) };
    const doSomethng = proxyquire('./main', {
      util: utilStub,
    });

    const actual = await doSomethng('/root/avatar.jpg');
    expect(actual).to.be.equal('fake data');
    sinon.assert.calledOnce(utilStub.promisify);
    sinon.assert.calledWithExactly(lstatStub, '/root/avatar.jpg');
  });
});

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

  61412987
    ✓ should pass (1894ms)


  1 passing (2s)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 main.js  |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------

源代码:https ://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/61412987

于 2020-04-25T02:48:39.333 回答