AngularJS + Jasmine mock unit test $http factory of POST method

匿名 (未验证) 提交于 2019-12-03 09:52:54

问题:

How I can make unit-test of $http factory, if it using post method, for example:

// controller    $scope.logOut = function (){     logOutFactory.logOut().then(function(resp){     });   };   // service   app.factory('logOutFactory', ['$http', '$q', 'CONST', function ($http, $q, CONST){     var logoutApiUrl = CONST.URL+'logout';     return {         logOut: function() {             var deferred = $q.defer();                 $http({                     method: "post",                     url: logoutApiUrl                 })                 .success(function (data) {                     deferred.resolve(data);                 })                 .error(function (data) {                 deferred.reject('error in $http request');                 console.log(data, status, headers, config);                 });             return deferred.promise;         }     } }]);  // unit test  describe("myApp", function () {   beforeEach(module('app')); describe("Ctrl", function () {     var scope, httpBackend, fakedMainResponse;       beforeEach(inject(function ($rootScope, $controller, $httpBackend, $http) {         scope = $rootScope.$new();         httpBackend = $httpBackend;         httpBackend.expectPOST('https://url/logout').respond(200);         $controller('Ctrl', {             $scope: scope,             $http: $http         });     }));       it("success response - empty array from server", function () {        //httpBackend.flush();     }); }); });

How i can mock $http response in Jasmine test ??? I'm trying but i see an error "Error: Unexpected request: POST /url/logout No more request expected "

回答1:

You want to write a unit-test for the $http factory, but in your test, there is a $controller inside. Maybe you should separate this test to 2 unit-tests, one for the controller, one for the factory.

When you test the logOutFactory, you should create a $httpBackend for mocking the back end, and also logOutFactory.

var logOutFactory, httpBackend; 

In the beforeEach, it just need to initialize these 2 variables :

beforeeach(inject(function($httpBackend, logOutFactory) {     httpBackend = $httpBackend;     logOutFactory = logOutFactory; })); 

And mock the httpBackend in the test method :

it("success response - empty array from server", function () {     httpBackend.expectPOST('https://url/logout').respond(200);     var success;     // call logOut     logOutFactory.logOut().then(function () {         success = true;     });             httpBackend.flush();     // verification     expect(succeeded).to.be.true; }); 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!