试图存根一个函数

Trying to stub a function

我正在尝试对 returns 承诺的函数进行存根,但它不起作用...我正在使用 Node.js、Mocha、Chai 和 Sinon。

// index.js
const toStub = () => {
  return Promise.resolve('foo');
};

const toTest = () => {
  return toStub()
    .then((r) => {
      console.log(`THEN: ${r}`);
      return 42;
    })
    .catch((e) => {
      console.log(`CATCH: ${e}`);
      throw 21;
    });
};

module.exports = { toStub, toTest };

通过此测试实施:

// index.spec.js
let chai = require('chai')
  , should = chai.should();

let sinon = require('sinon');

let { toStub, toTest } = require('../src/index');

describe('test the toTest function', () => {
  it('should be rejected', (done) => {
    toStub = sinon.stub().rejects('foofoo'); // <---------- here
    toTest()
      .then(r => {
        console.log(`THEN_2 ${r}`);
      })
      .catch(e => {
        console.log(`CATCH_2 ${e}`);
      });
      done();
  });
});

这是我 运行 这个单元测试时得到的:

$ npm t
  test the toTest function
    ✓ should be rejected
THEN: foo
THEN_2 42

它应该在下面打印出来:

$ npm t
  test the toTest function
    ✓ should be rejected
CATCH: foofoo
CATCH_2 21

我已经成功了。

// tostub.js       
function toStub() {
   return Promise.resolve('foo');
}
module.exports = toStub

您的 index.js 变为:

const toStub = require('./tostub')
const toTest = () => {
  return toStub()
    .then((r) => {
      console.log(`THEN: ${r}`);
      return 42;
    })
    .catch((e) => {
      console.log(`CATCH: ${e}`);
      throw 21;
    });
};
module.exports = toTest;

最后,测试中的关键是使用“mock-require”模块

// index.spec.js
const mock = require('mock-require');
let chai = require('chai')
  , should = chai.should();

let sinon = require('sinon');
mock('../src/tostub', sinon.stub().rejects('foofoo'))
let toTest = require('../src/index');

describe('test the toTest function', () => {
  it('should be rejected', (done) => {
    toTest()
      .then(r => {
        console.log(`THEN_2 ${r}`);
      })
      .catch(e => {
        console.log(`CATCH_2 ${e}`);
      });
      done();
  });
});

通过运行 npm test,你应该得到:

→ npm test

> stub@1.0.0 test /Users/kevin/Desktop/main/tmp/stub
> mocha



  test the toTest function
    ✓ should be rejected
CATCH: foofoo
CATCH_2 21


  1 passing (12ms)