链式方法的 Sinon 存根

Sinon stubs for chained methods

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

// 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() returns 一个承诺。我找到了 Whosebug 答案,所以我对单元测试做了以下操作:

// 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 returns undefined。这表明存根没有生效。我错过了什么?我正在使用 sinon 7.4.2.

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

经过进一步挖掘,我得到了这个解决方案:

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