问题
I am testing a service function which makes numerous $http.get()
calls. The actual function under test returns a promise. Currently, the test is failing with response is undefined
.
Here is the test:
it('should return the list of catalogues', inject(function ($q, bookService) {
var list;
var deferred = $q.defer();
var promise = deferred.promise;
promise.then(function (response) {
list = response.success; // Cannot read property 'success' of undefined
});
bookService.getCatalogues().then(function (response) {
deferred.resolve(response); // this line is hit first
});
$httpBackend.flush();
expect(list).toEqual(listOfBooks); // listOfBooks is defined outside test
}));
What am I doing wrong?
回答1:
Based on this post I have resolved my problem with the following code (please forgive the change in context from book to user):
describe('user-service', function () {
var $httpBackend, $q, $rootScope;
var mockUserData = { "d": { "firstName": "Matt", "lastName": "Lenny" };
beforeEach(module('users'));
beforeEach(inject(function (_$httpBackend_,_$q_,_$rootScope_) {
$httpBackend = _$httpBackend_;
$q = _$q_;
$rootScope = _$rootScope_;
$httpBackend.when('GET', /(.*)\/user\/api/).respond(200, mockUserData);
}));
it('should return the user object', inject(function (userService) {
var user;
var deferred = $q.defer();
var promise = deferred.promise;
promise.then(function (response) {
user = response;
});
userService.getUserInfo().then(function (response) {
deferred.resolve(response);
});
$rootScope.$digest();
$httpBackend.flush();
expect(user).toEqual(mockUserData.d);
}));
});
来源:https://stackoverflow.com/questions/46039953/cannot-read-property-of-undefined-in-angular-karma-test