问题
Trying to run a unit test for my angular httpbased service:
angular.module('myApp').factory('httpService',function($http)
{
return {
sayHello:function(usr){
$http.get('/api/doit').then(
function(result){
return 'hello '+usr;
});
}
}
});
This is the test:
it('should say hello from httpservice', function() {
var returnData = 'hello Tomss';
httpBackend.expectGET('/api/doit').respond(returnData);
var returnedPromise = httpService.sayHello('Tom');
var result;
returnedPromise.then(function(response) {
result = response;
});
httpBackend.flush();
expect(result.data).toEqual('hello Tom');
});
I get an error:
TypeError: Unable to get property 'then' of undefined or null reference
How to fix this?
plunkr:http://plnkr.co/edit/6Uqa1GC4x7HzLhVgtdsD?p=preview
回答1:
return {
sayHello:function(usr){
return $http.get('/api/doit').then(
function(result){
return 'hello '+usr;
});
}
}
Notice the return in sayHello function.
来源:https://stackoverflow.com/questions/31602155/unable-to-get-property-then-of-undefined