角單元測試的測試讓我們開始與控制器代碼:
angular
.module('hc.hotelContent')
.controller('NameLocationController', nameLocationCtrlFn); //Todo change hotelDataService
nameLocationCtrlFn.$inject = ['$stateParams', 'hotelDataService'];
function nameLocationCtrlFn($stateParams, hotelDataService) {
var vm = this,
hotelId = $stateParams.hotelId;
vm.Keys = {
Name: 'Name',
Street: 'Street',
City: 'City',
State: 'State',
Zip: 'Zip',
Country: 'Country'
}
}
我確實有一些更多的代碼,但它的irellevant邏輯,我的測試工作正常,當我不注入$ stateParmas到控制器。
所以繼承人的測試文件:
describe('nameLocation component Controller', function() {
var $controller,
hotelDataServiceMock,
stateParams,
hotelId = "4611";
Keys = {
Name: 'Name',
Street: 'Street',
City: 'City',
State: 'State',
Zip: 'Zip',
Country: 'Country'
}//@
beforeEach(module('hc.hotelContent'));
beforeEach(module('hc.app.core'));
beforeEach(inject(injectFn));
function injectFn(_$controller_, $stateParams, _hotelDataService_) {
$controller = _$controller_;
stateParams = $stateParams;
hotelDataServiceMock = _hotelDataService_;
} //controller injection fn
function initCtrl() {
controller = $controller('NameLocationController', {
$stateParams: stateParams,
hotelDataService: hotelDataServiceMock
});
}
describe('inserting a new hotel', function() {
it('should populate Keys object', function() {
var controller = initCtrl();
expect(controller.Keys).toEqual(Keys);
});
}
}
即時得到未知提供程序錯誤。這與我的控制器沒有任何關係,所有在控制器中進行的操作都是將變量設置爲$ stateParams變量。 我如何使用這種注射劑? 我karma.conf文件配置爲加載了jQuery,棱角分明,UI路由器,嘲笑在這個特定的順序,所有的JS和HTML
編輯後:我沒有看到this post這篇文章之前,但即時通訊使用的UI路由器在我的主應用程序模塊中,所以ive添加beforeEach(module('hc.app'));代碼,但仍然沒有什麼
不,它只是一個類型,我改變了。 ui路由器被注入,但被注入到另一個模塊 –
angular.module('hc.app',[0126] templateHtml', 'ngMdIcons', 'ngMaterial', 'ui.router' ]); –
編輯 - 澄清,您將不得不_load_一個具有ui-router作爲依賴項的模塊。 ('beforeEach(模塊( 'hc.app'));')。我還添加了一個模擬$ stateParams的方法。 –