【发布时间】:2019-09-18 09:18:08
【问题描述】:
我很难在我的单元测试覆盖范围内覆盖整个承诺链。我确实找到了给我最近解决方案的文章,但挑战在于最后一个“然后”我需要调用三个不返回承诺的函数。
以下是我尝试过的示例/示例
async = jest.fn(() => {
return Promise.resolve('value');
});
async1 = jest.fn(() => {
return Promise.resolve('value1');
});
async2 = jest.fn(() => {
return Promise.resolve('Final Value');
});
it('test my scenario', (done) => {
someChainPromisesMethod()
.then(data => {
expect(async1).toBeCalledWith('value');
expect(async2).toBeCalledWith('value1');
expect(data).toEqual('Final Value');
done();
});
});
下面是返回另一个带有嵌套“then”函数的函数的函数。我需要有关测试用例的帮助以涵盖所有内容。
function consolidatedReport(param1, param2){
const somedata = param1.data;
const someOtherData = param2.data;
if(true){
doThisthing();
}
return promiseChainBegin(somedata, someOtherData)
.then(response => response && functionOne(somedata, someOtherData)
.then(response => response && functionTwo(somedata, someOtherData)
.then(response => response && functionThree(somedata, someOtherData)
.then(response => response && functionFour(somedata, someOtherData)
.then(response => {
if(response) {
notApromiseFuncOne(somedata)(someOtherData);
notApromiseFuncTwo(somedata)(someOtherData);
notApromiseFuncThree(somedata)(someOtherData);
} else{
notApromiseFailCase(someOtherData);
}
});
}
我很难覆盖嵌套的 then 函数。
【问题讨论】:
-
您能否使用更准确地显示您要测试的内容的代码更新您的问题?在上面的代码中,最终的
then回调没有返回任何内容,因此data在您的测试中永远不会是Final Value...我猜consolidatedReport已针对问题进行了简化,但其功能在过程。 -
@brian-lives-outdoors 在电子商务网站中,当用户点击结帐时。 concurrentReport 被调用,promiseChainBegin 返回购物车中的项目。 functionOne 正在获取他的首选地址。 FunctionTwo 正在获取他的首选付款。 functionThree 正在检查他的首选交货时间等。伊斯坦布尔覆盖率报告显示 functionOne、functionTwo、3、4 等都没有被覆盖。我只是想确保它们被调用并包含在覆盖率报告中。
-
听起来您在测试中模拟了这些函数,因此实际上并未调用它们。如果你想对它们进行代码覆盖,你必须让它们真正被调用,而不是模拟它们正在做什么(听起来他们进行 API 调用,所以你需要模拟它们)
标签: reactjs unit-testing ecmascript-6 jestjs