Reputation: 65
I am trying to mock HTTP requests for AngularJS in Jest.
I have a service like this
public UserService(user) {
let url = this.env.getUserEndpoint("/users");
let deferred = this.$q.defer<any>();
this.$http.post<{ user: IUser }>(url,user).then( (result) => {
deferred.resolve(result.data.user);
}, (error) => {
deferred.reject(this.httpErrorHandlingService.handleHttpError(error, "creating new user"));
});
return deferred.promise;
}
Test:
beforeEach(angular.mock.module("test"));
var userService;
beforeEach(angular.mock.inject(function (UserService) {
userService = UserService;
}));
it('should create new user', function () {
const newUser = {
name: "testUser",
password: "12345"
};
return userService.createNewUser(newUser).then(user => expect(user.name).toEqual("testUser")
});
The error I get is Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout
What am I doing wrong, and how can I mock AngularJS HTTP requests the easiest way?
Upvotes: 0
Views: 399
Reputation: 7521
You don't need to create your own promise - $http.post()
returns one for you. Then you can return the response data in your success and error function callbacks in your then
method, and these will be handed to the promise returned by $http.post()
. This should simplify your service code a bit:
public UserService(user) {
public createNewUser(user) {
let url = this.env.getUserEndpoint("/users");
return this.$http.post<{ user: IUser }>(url, user).then((result) => {
return result.data.user;
}, (error) => {
this.httpErrorHandlingService.handleHttpError(error, "creating new user");
});
}
}
Upvotes: 1