Javascript 单元测试角/离子项目
我有一个非常简单的控制器,看起来像这样Javascript 单元测试角/离子项目,javascript,angularjs,unit-testing,ionic-framework,Javascript,Angularjs,Unit Testing,Ionic Framework,我有一个非常简单的控制器,看起来像这样 timeInOut.controller('timeInOutController', function($scope, $filter, $ionicScrollDelegate){ ... }); 每当我尝试为它创建一个单元测试时,就像这样 (function() { 'use strict'; var scope, controller, filter; describe('timeInOutController'
timeInOut.controller('timeInOutController', function($scope, $filter, $ionicScrollDelegate){
...
});
每当我尝试为它创建一个单元测试时,就像这样
(function() {
'use strict';
var scope, controller, filter;
describe('timeInOutController', function () {
beforeEach(module('common.directives.kmDateToday'));
beforeEach(inject(function ($rootScope, $controller, $filter) {
scope = $rootScope.$new();
filter = $filter;
controller = $controller('timeInOutController', {
$scope: scope
});
}));
describe('#date setting', function(){
...
});
});
})();
我得到一个错误:
[$injector:unpr]未知提供程序:$ionicScrollDelegateProvider如果要通过angular实例化控制器,则需要传入所有参数。通过添加参数,您可以告诉angular,无论何时创建这些控制器中的一个,我也需要这些东西,因为我依赖于它们 因此,我的建议是模拟这些依赖项的一些表示,并在创建控制器时将它们注入。它们不一定(也不应该)是单元测试的实际服务。Jasmine使您能够创建可以注入的间谍对象,以便验证该单元的行为
(function() {
'use strict';
var scope, controller, filter, ionicScrollDelegate;
describe('timeInOutController', function () {
beforeEach(module('common.directives.kmDateToday'));
beforeEach(inject(function ($rootScope, $controller, $filter) {
scope = $rootScope.$new();
filter = $filter;
// func1 and func2 are functions that will be created as spies on ionicScrollDelegate
ionicScrollDelegate = jasmine.createSpyObj('ionicScrollDelegate', ['func1', 'func2']
controller = $controller('timeInOutController', {
$scope: scope,
$filter: filter,
$ionicScrollDelegate: ionicScrollDelegate
});
}));
describe('#date setting', function(){
...
});
});
})();
您可以通过找到有关间谍的更多信息。您需要为控制器正在使用的所有依赖项创建模拟对象 以该控制器为例:
angular.module('app.module', [])
.controller('Ctrl', function($scope, $ionicLoading) {
$ionicLoading.show();
});
这里您使用的是$ionicLoading
服务,因此如果您想测试此控制器,您必须模拟该对象,指定您在控制器中使用的方法:
describe('Test', function() {
// Mocks
var $scope, ionicLoadingMock;
var ctrl;
beforeEach(module('app.module'));
beforeEach(function() {
// Create $ionicLoading mock with `show` method
ionicLoadingMock = jasmine.createSpyObj('ionicLoading', ['show']);
inject(function($rootScope, $controller) {
$scope = $rootScope.$new();
ctrl = $controller('Ctrl', {
$scope: $scope,
$ionicLoading: ionicLoadingMock
});
});
});
// Your test goes here
it('should init controller for testing', function() {
expect(true).toBe(true);
});
});
我有点理解你的意思,但是你能给出一个快速的代码示例吗?你的意思是像一个单独的文件夹/文件那样模拟一些离子依赖项并注入它们吗?这是有效的,我唯一需要更改的是createSpyObject(…到createSpy)(…,不确定createSpyObject是否为实际函数。非常感谢!我在没有查看文档的情况下添加了该函数,但我所指的方法是createSpyObj,它有助于在对象上创建多个间谍。信息很好。再次感谢!