【发布时间】: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.log 和 response 返回未定义。这表明存根没有生效。我错过了什么?我用的是sinon 7.4.2。
我知道这是一个人为的例子,但这只是为了说明这一点。
【问题讨论】: