【问题标题】:Sinon stubs for chained methods用于链式方法的 Sinon 存根
【发布时间】:2019-09-17 04:12:14
【问题描述】:

我正在寻找天气 API (https://github.com/eliashussary/dark-sky/blob/master/dark-sky-api.js) 的单元测试链式方法。这是我的简化代码。它的作用是针对给定位置(具有经度和纬度的对象)返回所有当前天气警告。

// weather.js

const DarkSky = require('dark-sky');
const darksky = new DarkSky('API_KEY');

async function getWeatherWarnings(location) {
    const data = await darksky
                   .coordinates(location)
                   .exclude('currently,minutely,hourly,daily,flags')
                   .get();

    return data.alerts;
}

module.exports = {
    getWeatherWarnings,
};

请注意,get() 返回一个承诺。我找到了this stackoverflow 的答案,所以我为单元测试做了以下操作:

// test/weather.js

const { getWeatherWarnings } = require('../weather');
const DarkSky  = require('dark-sky');
const darksky = new DarkSky('key');
const { assert } = require('chai');
const sinon = require('sinon');

const result = [{
          title: 'Dust Storm Warning',
          regions: [Array],
          severity: 'warning',
          time: 1568508240,
          expires: 1568509200,
          description: 'A DUST STORM WARNING REMAINS IN EFFECT UNTIL 600 PM MST'
}];

describe('get weather warning', () => {
  it('maricopa county', async () => {

    sinon.stub(darksky, 'coordinates').returns({
      exclude: sinon.stub().returnsThis(),
      get: sinon.stub().resolves(result)  
    });

    const response = await getWeatherWarnings({ lat: 33.0435719, lng: -112.0667759 });
    console.log('response: ' + response);
    assert.equal(response, result);
  });
});

测试失败。我添加了 console.logresponse 返回未定义。这表明存根没有生效。我错过了什么?我用的是sinon 7.4.2。

我知道这是一个人为的例子,但这只是为了说明这一点。

【问题讨论】:

    标签: node.js sinon


    【解决方案1】:

    经过更多的挖掘,我得到了这个解决方案:

    describe('get weather warning', () => {
      it('maricopa county', async () => {
        const darkskystub = sinon.stub(DarkSky.prototype, 'coordinates').returns({
          exclude: sinon.stub().returns({
            get: sinon.stub().resolves(weatherResult)
          })
        });
    
        const response = await getFrostAndRainWarnings({
          lat: 33.0435719,
          lng: -112.0667759
        });
    
        assert.equal(darkskystub.calledOnce, true);
        assert.deepEqual(response, warningResult);
    });
    

    【讨论】:

      猜你喜欢
      • 2016-01-02
      • 2021-06-27
      • 2021-06-10
      • 2015-04-18
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      相关资源
      最近更新 更多