3

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

控制器

'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();
    });
});

});
});
4

2 回答 2

0

您应该scope.$digest()在 save 调用之后解决挂起的 http 调用。

于 2015-08-27T17:01:41.287 回答
0

乍一看,您似乎正在调用 save 函数,而您的函数被称为saveWorkflowTRIGGERS. 我认为这就是您收到“TypeError:undefined is not a function”的原因

于 2015-08-27T09:30:52.617 回答