希诺存根用于链接方法

时间:2019-09-17 04:12:14

标签: node.js sinon

我正在寻求对气象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.log,而response返回的是undefined。这表明存根没有生效。我想念什么?我正在使用sinon 7.4.2。

我意识到这是一个人为的例子,但这只是为了说明这一点。

1 个答案:

答案 0 :(得分: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);
});