0
我已經寫了一個角度測試應用程序。試着用它學習測試。測試Angularjs控制器服務作爲依賴時的困難
控制器看起來像這樣
var EmployeeModule = EmployeeModule || {};
(function (currentModule) {
EmployeeModule.EmployeeController = function ($scope, $routeParams, $location, Employees) {
this.RegEmployees = Employees.GetEmployees();
this.currentEmployee = {};
if ($routeParams.Id != undefined) {
console.log("to check $route"+$routeParams);
this.currentEmployee = Employees.GetEmployeeById($routeParams.Id);
}
this.Id = "";
this.firstname = "";
this.lastname = "";
this.email = "";
this.dob = "";
this.department = "";
this.RegisterEmployee = function() {
Employees.RegisterEmployee(this.firstname, this.lastname, this.email, this.dob, this.department);
if ($scope.employeeForm.$valid)
$location.path("/Employees");
}
EmployeeModule.Employee = function (firstname, lastname, email, dob, department) {
this.Id = Date.now();
this.FirstName = firstname;
this.LastName = lastname;
this.Email = email;
this.DOB = dob;
this.Department = department;
}
})(EmployeeModule);
和我的角度服務看起來這
var app = angular.module('angularApp2App');
app.factory('Employees', function() {
var RegEmployees = {};
var Employees = [];
//Service
RegEmployees.RegisterEmployee = function (firstname, lastname, email, dob, department) {
var newEmployee = new EmployeeModule.Employee(firstname, lastname, email, dob, department);
Employees.push(newEmployee);
}
return RegEmployees;
});
app.controller('EmployeeController', ['$scope', '$routeParams', '$location', 'Employees', EmployeeModule.EmployeeController]);
我想要編寫單元測試控制器,但不知道,我怎麼能注入服務爲單元測試中對控制器的依賴性。
請在此 幫助和我的單元測試代碼是
describe('Controller: EmployeeController', function() {
// load the controller's module
beforeEach(module('angularApp2App'));
var empCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, $injector) {
scope = $rootScope.$new();
var employeeService = $injector.get('Employees');
console.log(employeeService);
spyOn(employeeService , 'RegisterEmployee');
empCtrl = $controller('EmployeeController', {
$scope: scope
// place here mocked dependencies
});
}));
it('checking default values', function() {
expect(empCtrl.currentEmployee).toEqual({});
});
it('checking RegisterEmployee Method',function() {
expect(RegisterEmployee).toHaveBeenCalled();
});
});
感謝
請指出你的問題中單元測試的當前代碼。 – estus
更新測試邏輯,但不知道如果這是正確的做法 – Geeky