如何测试' catch '和' then '与sinon js

How to test `catch` and `then` with sinon js?

本文关键字:then sinon js catch 何测试 测试      更新时间:2023-09-26

我一直在尝试存根和模拟我的函数,以便能够测试我的函数

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

我想测试一个场景,当配置。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:(提前谢谢!

您可以使用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                 
-------------------|---------|----------|---------|---------|-------------------