我有以下控制器: -
appControllers.controller("TaskAddController", function ($scope, $timeout, taskService) {
$scope.task = {};
$scope.messages = {
error: false
};
$scope.actions = {
save : function() {
if ($scope.frmAddTask.$valid) {
taskService.insert($scope.task)
.then(
function() {
$scope.messages.success = true;
$scope.task = {};
$scope.frmAddTask.$setPristine();
$timeout(function() {
$scope.messages.success = false;
}, 3000);
},
function() {
$scope.messages.error = true;
}
);
} else {
$scope.messages.error = true;
}
}
};
});
使用此单元测试: -
/// <reference path="../../../../src/tasks.web/scripts/angular-1.2.10.js" />
/// <reference path="../../../../src/tasks.web/scripts/angular-route-1.2.10.js" />
/// <reference path="../../../../src/tasks.web/scripts/app.js" />
/// <reference path="../../../../src/tasks.web/scripts/services.js" />
/// <reference path="../../../../src/tasks.web/scripts/controllers.js" />
/// <reference path="../lib/angular/angular-mocks.js" />
describe("TaskAddController", function() {
var createController, scope, deferred, mockTaskService;
beforeEach(function () {
module('appControllers');
module('appServices');
inject(function ($rootScope, $q, taskService) {
scope = $rootScope.$new();
scope.frmAddTask = {
$valid: true
};
deferred = $q.defer();
mockTaskService = taskService;
spyOn(mockTaskService, "insert").andReturn(deferred.promise);
});
inject(function ($controller) {
createController = function () {
return $controller("TaskAddController", {
$scope: scope,
taskService: mockTaskService
});
};
});
});
it("when actions.save is called then messages.success should be true", function () {
var task = {
title: "Title",
description: "Description"
};
createController();
scope.task = task;
scope.actions.save();
deferred.resolve("insert");
scope.$root.$digest();
expect(scope.messages.success).toEqual(true);
});
});
错误消息TypeError: 'undefined' is not a function (evaluating '$scope.frmAddTask.$setPristine()')
我认为这是因为单元测试仅测试控制器,$scope.frmAddTask
仅在视图存在时才存在。所以我的问题是如何正确地对其进行单元测试?
答案 0 :(得分:12)
是的,通常$scope.frmAddTask
对象将由ngForm
指令创建。但是,在这种情况下,它是由您在测试中创建的:
scope.frmAddTask = {
$valid: true
};
由于您无论如何都在使用此模拟对象,我建议在其上删除$setPristine
方法:
scope.frmAddTask = {
$valid: true,
$setPristine: function() {}
};