我正在尝试在我的方法中为服务调用创建单元测试。单元测试返回以下错误:
TypeError: Unable to get property 'catch' of undefined or null reference
我正在测试的 Controller 方法:
$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();
});
当我从 Controller 方法中删除“.catch(function (error)”语句时,测试通过。看来我必须在我的 spy 中实现 catch,但我不知道如何实现。
最佳答案
then
和 catch
方法来自于 AngularJS 中由 $q
实现的 Promise 模式。服务。
你的模拟(伪造)方法也应该返回一个 promise 。最简单的方法是使用 $q.when(value)
。它创建的 Promise 会立即解析为给定的值
。
尝试:
var response = {data: asset};
var spy = spyOn(assetFactory, 'getAsset').and.returnValue($q.when(response));
当然,您需要在测试中注入(inject)$q
。
关于angularjs - Jasmine - 类型错误 : Unable to get property 'catch' of undefined or null reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35345606/