在karma jasmine中测试$ http.post方法

时间:2014-05-21 23:31:04

标签: angularjs unit-testing jasmine karma-jasmine

我的控制器中有一个功能如下:

控制器

'use strict';

define(['angular', 'app/controllers'], function (angular, controllers) {
    console.log("Loading controller:");

    controllers.controller('MyCtrl', function ($scope, $window, $timeout, $log, $location, $route, $routeParams, $http) {

    $scope.saveWorkflowTRIGGERS = function(saveCall) {
        var url = BASE_APP_PATH + "trigger/save";

        $http.post(url, $scope.triggers).success(function(data) {

            console.log("savedTriggers");
            console.log(data);
        });
    };
  });
  });

我如何对此进行单元测试,以便模拟和调用post方法。目前我有以下内容,不包括邮局的成功部分。

define(['angular-mocks', 'jquery', 'app/app'], function(angularmocks, $, app){
describe('Unit: Testing Controller', function(){
    var ctrl;
    var scope;
var rootScope;
var mockHttp;

BASE_APP_PATH='some path/';

beforeEach(angular.mock.module('myApp'));

beforeEach(angular.mock.inject(function($rootScope, $window, $httpBackend){
    scope = $rootScope.$new();
    rootScope = $rootScope;

    mockHttp = $httpBackend;

}));

it ('should save triggers', function(){

    inject(function ($controller) {
        ctrl = $controller('MyCtrl', {
            $scope: scope
        });

        var url = BASE_APP_PATH + 'trigger/save';

        mockHttp.whenPOST(url, 'mockData').respond(201, 'success');
        mockHttp.expectPOST(url).respond(201, 'success');
        scope.save(true); 
        mockHttp.flush();
    });
});

});
});

1 个答案:

答案 0 :(得分:0)

保存呼叫后您应该有scope.$digest(),这将解决待处理的http呼叫。