我正在尝试为一个功能编写单元测试,我知道该功能可以通过彻底的测试工作,但我一生都无法弄清楚为什么我的单元测试不起作用
该函数非常简单,我有一个初始函数,它执行一些预处理,然后调用第二个辅助异步函数。第二个函数发出一个 post 请求来启动一项作业,这需要一些时间,然后它发出一个 get 请求以从作业中获取结果。:
_this.getFormula = async function() {
//does some preprocessing and sets improvedformula
const resultFromService = await _this.getFormulaFromService();
//does some postprocessing and sets improvedformula to result
};
_this.getFormulaFromService = async function() {
try {
// Request 1:
const firstResponse = await $http.post(url, query, headers);
// Request 2:
// We need to wait to let it finish
const jobId = firstResponse.data.job_id;
let finalResult;
finalResult = await $http.get(newurl);
return finalResult.data.results[0].result.formula || NO_FORMULA_FOUND_MESSAGE;
} catch (e) {
return 'Error!';
}
};
我的单元测试:
it('gets formula from service', function (done) {
ctrlInstance.searchQuery = 'query';
const jobIDResponse = {
job_id: 'dummyJobID',
};
const jobResultResponse = {
results: [
{
result: {
formula: 'formula',
},
},
],
};
$httpBackend
.whenPOST(/.*/)
.respond(jobIDResponse);
$httpBackend
.whenGET(/.*/)
.respond(jobResultResponse);
ctrlInstance.getFormula().then(() => {
expect(ctrlInstance.improvedFormula).toEqual('formula');
done();
});
$httpBackend.flush();
});
单元测试应该非常简单,但它似乎永远不会超越 POST,我不确定解决该承诺是否出了问题,但它似乎从未达到目标。我添加了一些调试来修改各个部分的改进公式,当我运行测试时,它将返回一个值,以至于它甚至从未通过 POST
我尝试在测试中使用 async/await,但这只是导致超时
我尝试将内容包装在 rootscope.apply 中以强制摘要,但这只是说它已经在尝试应用
我尝试使用超时,但随后该函数就挂起了
我尝试使用 async/await 并一起完成,但这也不起作用
https://dev.to/vantanev/async-functions-and-angularjs-1-x-do-not-mix-3kb3
基本上你不能将 async/await 与 angularjs 一起使用。这是不可能的。使用像这样的老式承诺
function updateItem(item) {
return $http.put(`/items/${item.id}`, item).then(({ data }) => data)
}