angularjs – jasmine – TypeError:无法获取未定义或空引用的
发布时间:2020-12-17 17:15:52 所属栏目:安全 来源:网络整理
导读:我正在尝试在我的方法中为服务调用创建单元测试.单元测试返回以下错误: TypeError: Unable to get property 'catch' of undefined or null reference 控制器方法我正在测试: $scope.getAsset = function (id) { if ($scope.id != '0') { assetFactory.getA
我正在尝试在我的方法中为服务调用创建单元测试.单元测试返回以下错误:
TypeError: Unable to get property 'catch' of undefined or null reference 控制器方法我正在测试: $scope.getAsset = function (id) { if ($scope.id != '0') { assetFactory.getAsset($scope.id) .then(function (response) { $scope.asset = response.data; }) .catch(function (error) { alertService.add('danger','Unable to load asset data: ' + error.statusText + '(' + error.status + '). Please report this error to the application administrator'); }); } }; 我的单元测试如下: it('method getAsset() was called',function () { var asset = { AssetId: 'TEST123' }; var spy = spyOn(assetFactory,'getAsset').and.callFake(function () { return { then: function (callback) { return callback(asset); } }; }); // call the controller method var result = scope.getAsset(); // assert that it called the service method. must use a spy expect(spy).toHaveBeenCalled(); }); 当我从我的控制器方法中删除“.catch(function(error)”语句时,测试通过了.看来我必须在我的间谍中实现catch,但我无法弄清楚如何. 解决方法
then和catch方法来自于承诺模式,它由
$q 服务在AngularJS中实现.
你的模拟(伪造)方法也应该返回一个承诺.最简单的方法是使用$q.when(value).它创造了立即解析为给定价值的承诺. 尝试: var response = {data: asset}; var spy = spyOn(assetFactory,'getAsset').and.returnValue($q.when(response)); 当然,你需要在测试中注入$q. 它也值得阅读How to unit-test promise-based code in Angular. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |