How to write jasmine test case for angularjs?

How to write a karma-jasmine test case for $http.get in angularJS?

  • I have a service: (function () { angular.module('app').service('MyAppService', MyAppService); MyAppService.$inject = ['$http', 'testUrl']; function MyAppService($http, testUrl) { var service = { testFunction: testFunction }; return service; function testFunction() { /*testurl is my backend API*/ return $http.get(testUrl) .error(function(){ return; }) .then(function (response) { return response.data; }); } } })(); I call this in my controller as: testControllerFunction(); function testControllerFunction() { MyAppService.testFunction().then(function (response) { app.testResponse = response; //This my http response console.log(app.testResponse); }); } I am writing a karma test case for successful $http.get request in the MyAppService as: describe('MyAppService', function () { var MyAppService,http; beforeEach(function() { module('app'); inject(function ($injector) { MyAppService = $injector.get('MyAppService'); testUrl = $injector.get('testUrl'); http = $injector.get('$httpBackend'); }); }); it('should call the backend testurl ', function () { MyAppService.testFunction(); http.expectGET(testUrl); }); }); But this does not seem to be working? Where did I go wrong? Thanks!

  • Answer:

    You have to https://docs.angularjs.org/api/ngMock/service/$httpBackend#flushing-http-requests the $httpBackend it('should call the backend testurl ', function () { http.expectGET(testUrl); MyAppService.testFunction(); http.flush(); });

user3500989 at Stack Overflow Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.