2

我有一个模块

const b = require(./b);

function aGetResult() {
  return b.getInfo();
}

模块 B

const c = require(./c);
    
function getInfo() {
  return getDetailInfo();
}

function getDetailInfo() {
    const result = c.getApiResult();
    return result
}

模块 C

function getApiResult() {
  return api.get(/test/1);
}

我已经为模块 A 编写了一个测试,但是遇到了存根依赖项的问题。我只想存根c.getApiResult()而不是b.getInfo()or b.getDetailInfo()。我尝试过选择性地存根使用proxyquire,但遇到了问题。有什么帮助吗?

4

1 回答 1

3

您应该使用包的全局覆盖要求proxyquire

a取决于bb取决于c。现在您想在测试时模拟间接c 依赖而不是直接b依赖a不建议这样做。但无论如何,这是解决方案:

例如

a.js

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

function aGetResult() {
  return b.getInfo();
}

exports.aGetResult = aGetResult;

b.js

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

function getInfo() {
  return getDetailInfo();
}

function getDetailInfo() {
  const result = c.getApiResult();
  return result;
}

module.exports = { getInfo };

c.js

const api = {
  get(url) {
    return 'real result';
  },
};

function getApiResult() {
  return api.get('/test/1');
}

module.exports = { getApiResult };

a.test.js

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

describe('63275147', () => {
  it('should pass', () => {
    const stubs = {
      './c': {
        getApiResult: sinon.stub().returns('stubbed result'),
        '@global': true,
      },
    };
    const a = proxyquire('./a', stubs);
    const actual = a.aGetResult();
    expect(actual).to.be.eq('stubbed result');
    sinon.assert.calledOnce(stubs['./c'].getApiResult);
  });
});

单元测试结果:

  63275147
    ✓ should pass (2630ms)


  1 passing (3s)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   83.33 |      100 |      60 |   83.33 |                   
 a.js     |     100 |      100 |     100 |     100 |                   
 b.js     |     100 |      100 |     100 |     100 |                   
 c.js     |      50 |      100 |       0 |      50 | 3-8               
----------|---------|----------|---------|---------|-------------------
于 2020-08-07T04:21:22.463 回答