Javascript 尝试存根函数

Javascript 尝试存根函数,javascript,unit-testing,mocha.js,sinon,chai,Javascript,Unit Testing,Mocha.js,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;

我试图存根一个函数,返回一个承诺,但它不工作。。。我正在使用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
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;
最后,测试中的关键是使用“”模块

通过运行npm测试,您应该获得:

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

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