【发布时间】:2017-11-30 21:42:32
【问题描述】:
我有一个 UI 组件,它调用一个方法 getUserInfo(),它返回一个承诺链。当我第一次构建这个时,我认为这是一个好主意,我写了一堆
未经测试的代码。 getUserInfo() 接受几个输入参数并返回以下内容。它是解析为字符串数组的一长串 Promise 的开始。
现在我正在尝试测试,但我遇到了很多麻烦......
utilities.js
...
// function geocodeLocation(zipcode){...};
// function getPlace(coordinates){...};
// ... etc
...
const utilities = {
getUserInfo: function (zipcode, gender) {
return geocodeLocation(zipcode)
.then(coordinates => getPlaces(coordinates))
.then(placeData => getDistanceFromEachPlace(origin, placeData))
.then(places => getMembersFromPlaces(places, gender))
.then(members => sortMembersByAge(members))
.then(sortedMembers => selectMembers(sortedMembers, gender))
}
};
module.exports = utilities;
getUserInfo 位于 utilities 模块内,是唯一公开的函数。在进行测试时,我有点迷茫。 getUserInfo 是一个开始
长长的功能链。大多数被链接的函数都会进行外部 API 调用,其中一些是围绕 Promise 进行的。如果这些函数没有进行外部 API 调用,它们就是在修改
数据并创建新的数据集(换句话说,应该进行单元测试的函数)。存根和模拟在这里似乎很合适,但我对存根和模拟什么感到困惑。
我应该模拟出每个功能,并测试承诺的最终结果吗?
另外,由于getUserInfo 是模块中唯一公开的函数,因此单独的单元测试在这里似乎不可行。我如何去测试所有的中间函数,比如 getDistanceFromEachPlace
他们没有暴露?
testfile.js
import utilities from '../util/utilities'
import sinon from 'sinon'
import mocha from 'mocha'
describe('___api', () => {
it('should return a promise', () => {
const zipcode = '90210'
const gender = 'male'
// stub( other api functions here?? )
expect(utilities.getUserInfo(zipcode, gender).to.be.a('promise')
});
});
我现在还能测试这个东西吗?
【问题讨论】:
-
我不明白这个问题。要允许代码的任何部分使用模块中的函数,只需通过
module.exports导出它,例如module.export = { utilities, geocodeLocation, getPlace }。有什么阻碍你这样做吗?
标签: javascript mocha.js es6-promise sinon