如何用sinon js测试`catch`和`then`?

时间:2016-08-09 09:01:26

标签: javascript unit-testing mocha sinon chai

我一直试图存根并模拟我的功能以便能够测试我的功能

SetExample.createCandyBox = function(config) {
    this.getCandies(config.candyUrl)
    .catch(() => {
        return {};
    })
    .then((candies) => {
        Advertisements.pushCandyBox(config, candies);
    });
};

我想在config.candyUrl不正确(404等)的情况下测试一个场景,例如:

it('should return to an empty array when url is incorrect', sinon.test(function() {
    // Fixture is an element I created for testing. 
    var configStub = SetExample.getCandyConfig(fixture);
    var createCandyBoxMock = sinon.mock(config);

    createCandyBoxMock.expects('catch');

    SetExample. createCandyBox(configStub);
}));

当我这样做时,术语是错误=>找不到变量:config。 我做错了什么?有人可以帮忙解释一下吗?我是Sinon的新手:(提前Thx!

1 个答案:

答案 0 :(得分:0)

您可以使用 sinon.stub() 存根 this.getCandies 及其已解决/已拒绝值。并存根 Advertisements.pushCandyBox,然后进行断言以检查它是否已被调用。

例如

SetExample.js

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

function SetExample() {}

SetExample.getCandies = async function (url) {
  return 'your real getCandies implementation';
};

SetExample.createCandyBox = function (config) {
  return this.getCandies(config.candyUrl)
    .catch(() => {
      return {};
    })
    .then((candies) => {
      Advertisements.pushCandyBox(config, candies);
    });
};

module.exports = SetExample;

Advertisements.js

function Advertisements() {}

Advertisements.pushCandyBox = function (config, candies) {
  return 'your real pushCandyBox implementation';
};

module.exports = Advertisements;

SetExample.test.js

const SetExample = require('./SetExample');
const Advertisements = require('./Advertisements');
const sinon = require('sinon');

describe('38846337', () => {
  describe('#createCandyBox', () => {
    afterEach(() => {
      sinon.restore();
    });
    it('should handle error', async () => {
      const err = new Error('timeout');
      sinon.stub(SetExample, 'getCandies').withArgs('wrong url').rejects(err);
      sinon.stub(Advertisements, 'pushCandyBox');
      await SetExample.createCandyBox({ candyUrl: 'wrong url' });
      sinon.assert.calledWithExactly(SetExample.getCandies, 'wrong url');
      sinon.assert.calledWithExactly(Advertisements.pushCandyBox, { candyUrl: 'wrong url' }, {});
    });
  });
});

单元测试结果:

  38846337
    #createCandyBox
      ✓ should handle error


  1 passing (7ms)

-------------------|---------|----------|---------|---------|-------------------
File               | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------------|---------|----------|---------|---------|-------------------
All files          |   81.82 |      100 |   42.86 |   81.82 |                   
 Advertisements.js |   66.67 |      100 |       0 |   66.67 | 4                 
 SetExample.js     |    87.5 |      100 |      60 |    87.5 | 6                 
-------------------|---------|----------|---------|---------|-------------------