内容简介:翻译自:https://stackoverflow.com/questions/24036867/typeerror-cannot-read-property-then-of-undefined-angularjs-grunt-test
我正在使用$q服务来进行异步调用.我无法使用业力解决单位测试中的“然后”和“推迟”.
以下是我的控制器代码.
scope.filterUrls = [{url:'page1'}, {url: 'page2'}, {url:'page-error'}];
scope.bindFilters = function () {
angular.forEach(scope.filterUrls, function (data) {
scope.getFilterData(data.url, '').then(function (result) {
if (data.url === 'page1') {
scope.moduleData.index = result.data;
} else if (data.url === 'page2') {
scope.moduleData.page2 = result.data;
}
});
});
}
scope.getFilterData = function (filterUrls, params) {
// $q service object
var deferred = q.defer();
// regular ajax request
http({
method: 'GET',
url: app.api.root + filterUrls,
params: params
})
.success(function (result) {
// promise resolve
deferred.resolve(result);
})
.error(function (result) {
// called asynchronously if an error occurs
// or server returns response with an error status.
deferred.reject('Erreur request : ' + result);
});
return deferred.promise;
};
测试规范:
it('should call getFilterData() in bindFilters()', function () {
spyOn(scope, 'getFilterData');
scope.bindFilters();
expect(scope.getFilterData).toHaveBeenCalled();
});
我收到一个名为“TypeError:无法读取属性”然后“未定义”的错误.
如何使用业力为这两种方法编写单元测试.
更新:
1.我们如何测试scope.getFilterData()的成功和错误
2.然后在scope.bindFilters()函数中执行函数.
请帮忙..
如果您只需要查明是否调用了getFilterData,请尝试通过伪造函数返回假承诺:
使用jasmine 1.3,我们可以使用andCallFake:
it('should call getFilterData() in bindFilters()', function () {
spyOn(scope, 'getFilterData').andCallFake(function(){//replace with a fake function
var deferred = $q.defer(); //assume that you already inject $q service in beforeEach and save it as a variable.
return deferred.promise; //returns a fake promise
});
scope.bindFilters();
expect(scope.getFilterData).toHaveBeenCalled();
});
使用jasmine 2.0,我们可以使用and.callFake.
另一个解决方案是使用andReturnValue和$q.when():
it('should call getFilterData() in bindFilters()', function () {
spyOn(scope, 'getFilterData').andReturnValue($q.when());
scope.bindFilters();
expect(scope.getFilterData).toHaveBeenCalled();
});
使用jasmine 2.0,我们可以使用and.returnValue代替.
翻译自:https://stackoverflow.com/questions/24036867/typeerror-cannot-read-property-then-of-undefined-angularjs-grunt-test
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 知识图和神经网络:如何有效读取图节点属性
- javascript – 未捕获的TypeError:无法读取未定义的属性“addMethod”
- Tensorflow数据读取指南
- Python如何读取文件
- Java实时读取日志文件
- 如何读取一个.ini文件?
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Flexible Rails
Peter Armstrong / Manning Publications / 2008-01-23 / USD 44.99
Rails is a fantastic tool for web application development, but its Ajax-driven interfaces stop short of the richness you gain with a tool like Adobe Flex. Simply put, Flex is the most productive way t......一起来看看 《Flexible Rails》 这本书的介绍吧!