试图存根函数

时间:2018-01-04 10:31:17

标签: javascript unit-testing mocha sinon chai

我试图存根一个返回承诺的函数,但它不起作用......我使用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

1 个答案:

答案 0 :(得分:1)

我已经能够使它发挥作用。

// 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;

最后,测试中的关键是使用&#34; mock-require&#34;模块

// 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)