Skip to content Skip to sidebar Skip to footer

How To Mock $http.post Method That Has Been Called In Other Service Method In Jasmine?

I have and angular service that I want to test. In one of his methods I am using $http of angular service. I am simply want to mock that function (to be more specific mock $http.po

Solution 1:

this sounds like exactly what $httpBackend is for.

You might also be able to mock only $http.post by doing something like $http.post = jasmine.createSpy(); if you inject $http in your test, but I don't know.

If you do use $httpBackend, perhaps this example helps you, in your jasmine test do something like this

beforeEach(inject(function(_$httpBackend_){
  // The injector unwraps the underscores (_) from around the parameter names when matching$httpBackend = _$httpBackend_;

  $httpBackend.whenRoute('POST', 'url')
    .respond(function(method, url, data, headers, params) {

      expect(somevariable).toContain(params.something);

      return [200, '{"progress":601}'];
    });
}));

the $httpBackend will intercept all $http.post's to url and execute this function. It should be just like the methodToTest submitted to the actual url and got your fake return value.

The return value indicates a success http status code (200) and returns whatever you put in the second argument as the data property of the response (here response.data == '{"progress":601}'). Which will be in the then function. See How do I mock $http in AngularJS service Jasmine test?

The expect function there is just an example (not needed), to show you that you can put an expect clause there if you want.

Solution 2:

P.S please remember that $http.post() returns promise so I think that I need to consider in that.

The service needs to return that promise:

angular.module('app').service('MyService' , function (dependencies) {
    let service = this;
    service.methodToTest = function () {
        //$http.post('url').then(function () {//vvvv RETURN http promisereturn $http.post('url').then(function () {
            // Do something
        });
    }
}

When a function omits a return statement, it a returns a value of undefined. There is no way that the service can indicate success or failure to the user.

Post a Comment for "How To Mock $http.post Method That Has Been Called In Other Service Method In Jasmine?"