Javascript 为需要ng模型的angular指令编写单元测试
我不熟悉单元测试,并试图弄清楚如何设置它。我有以下指示:Javascript 为需要ng模型的angular指令编写单元测试,javascript,angularjs,unit-testing,Javascript,Angularjs,Unit Testing,我不熟悉单元测试,并试图弄清楚如何设置它。我有以下指示: (function () { 'use strict'; angular .module('hntb-utils') .directive('notZero', notZero); //notZero.$inject = []; function notZero() { return { require: 'ngModel',
(function () {
'use strict';
angular
.module('hntb-utils')
.directive('notZero', notZero);
//notZero.$inject = [];
function notZero() {
return {
require: 'ngModel',
link: link,
restrict: 'A',
scope: '='
};
function link(scope, element, attributes, ngModelCtrl) {
ngModelCtrl.$validators.notZero = function (value) {
return value != 0;
}
}
}
})();
此指令(如果作为属性not zero添加到也使用ng模型的元素中)通过向ngModelController添加验证器来确保模型值不为零
我正在试图找出如何测试这个指令。我想我应该有这样的东西:
it("should ensure model is not zero", function () {
...
});
我真的被困在实现上了。我知道我应该用有角度的模仿,但是怎么做呢?我要模拟什么
提前谢谢 您可以使用该服务编译带有ngModel
指令和notZero
指令的输入元素。使用以下方法获取该元素的ngModelController
。然后,操纵该元素的范围模型以应用多个测试用例
这里有一个
describe('notZero', function() {
var scope,
ngModel;
beforeEach(module('hntb-utils'));
beforeEach(inject(function($compile, $rootScope) {
scope = $rootScope.$new();
var input = $compile('<input type="number" ng-model="model" not-zero />')(scope);
ngModel = input.controller('ngModel');
}));
it("should validate a non-zero number as a valid number", function () {
scope.model = -1;
scope.$apply();
expect(ngModel.$error.notZero).toBeFalsy();
scope.model = 1;
scope.$apply();
expect(ngModel.$error.notZero).toBeFalsy();
});
it("should validate a zero number as an invalid number", function() {
scope.model = 0;
scope.$apply();
expect(ngModel.$error.notZero).toBeTruthy();
});
});
description('notZero',function(){
var范围,
ngModel;
之前(模块('hntb-utils'));
beforeach(注入函数($compile,$rootScope){
scope=$rootScope.$new();
变量输入=$compile(“”)(范围);
ngModel=input.controller('ngModel');
}));
它(“应将非零数字验证为有效数字”,函数(){
scope.model=-1;
作用域:$apply();
expect(ngModel.$error.notZero).toBeFalsy();
scope.model=1;
作用域:$apply();
expect(ngModel.$error.notZero).toBeFalsy();
});
它(“应将零数字验证为无效数字”,函数(){
scope.model=0;
作用域:$apply();
expect(ngModel.$error.notZero).toBeTruthy();
});
});
谢谢,谢谢。测试正在进行,我真的很感谢你的帮助。不过我有一个问题。我想知道为什么需要角模拟。我想我很难理解对角度模拟的依赖从哪里结束,对角度模拟的依赖从哪里开始。我的意思是,注入是一个茉莉花函数?然后通过角度模拟将$compile和$rootscope添加为全局变量?哪个库提供模块功能?有什么方法可以从哪个依赖项在做什么的意义上对测试进行一点分解吗?module()
和inject()
函数都来自angular mocks
库。好的,再重复一个问题,我该如何调试测试?有没有什么工具可以让我指定依赖项(有点像karma)和测试,它会打开一个网页(比如在chrome中),让我可以逐步完成测试?这可以通过karma完成吗(当我运行karma任务时,它会打开然后关闭浏览器…谢谢。你为什么要指定依赖项?客户端依赖项,如第三方angularjs模块?我是指运行测试所需的任何文件,包括我自己的模块、第三方模块、角度模拟/角度源等。