Javascript 如何在角度测试中触发解析承诺?
我想测试Javascript 如何在角度测试中触发解析承诺?,javascript,angularjs,unit-testing,karma-runner,Javascript,Angularjs,Unit Testing,Karma Runner,我想测试Note.query在self.parentId是承诺时被调用 if (isPromise(self.parentId)) { console.log('DEBUG: outside then'); self.parentId.then(function (parent) { console.log('DEBUG: inside then'); self.parentId = parent.id; self.notes = Note.query({
Note.query在self.parentId
是承诺时被调用
if (isPromise(self.parentId)) {
console.log('DEBUG: outside then');
self.parentId.then(function (parent) {
console.log('DEBUG: inside then');
self.parentId = parent.id;
self.notes = Note.query({
parent_type: self.parentType,
parent_id: self.parentId,
});
});
这不管用。外部日志会发生,但内部日志不会发生。因此,问题大概是承诺没有解决
1) 为什么这样不行?
2) 如何使其工作?为了测试承诺,您需要在承诺返回函数上创建spy。然后用一些模拟数据来解析承诺。
首先在test中注入$q
it('when a promise is passed in', function () {
$controller('NotesController', {}, {
parentId: Lead.get({ id: 1 }).$promise,
parentType: 'leads',
});
expect(Note.query.called).to.equal(true);
});
这应该解决你的承诺。根据您的要求更改字段名称这只是示例,包含相关信息的链接远不如在您的答案中包含相关信息。外部链接可以,而且经常会,下降或改变其结构,使信息不再可用。
deferred = _$q.defer();
spyOn(self, 'parentId').and.returnValue(deferred.promise);
deferred.resolve({ id: 102 });
$scope.$apply();