我正在为我的一个指令创建一个测试,它工作正常,直到我添加了以下代码,以便当用户按下回车时我可以调用一个函数:
document.getElementById('selectableAdvancedValue').addEventListener('keydown',function(ev){
if(ev.keyCode == 13 && ev.target.value.length > 0){
scope.addQuery(scope.query);
}
scope.$apply();
});
当我再次运行测试时,它会给我以下错误:
TypeError: Cannot read property 'addEventListener' of null
at GumgaAdvancedSearch.link (/home/igorsantana/gumga/gumga-framework-frontend/app/modules/gumga/directives/GumgaSearch/directives/GumgaAdvancedSearch.js:89:67)
at $ (/home/igorsantana/gumga/gumga-framework-frontend/bower_components/angular/angular.min.js:70:197)
at B (/home/igorsantana/gumga/gumga-framework-frontend/bower_components/angular/angular.min.js:59:255)
at g (/home/igorsantana/gumga/gumga-framework-frontend/bower_components/angular/angular.min.js:51:335)
at /home/igorsantana/gumga/gumga-framework-frontend/bower_components/angular/angular.min.js:50:444
at Object.<anonymous> (/home/igorsantana/gumga/gumga-framework-frontend/test/modules/gumga/directives/GumgaAdvancedSearchSpec.js:41:50)
at Object.e [as invoke] (/home/igorsantana/gumga/gumga-framework-frontend/bower_components/angular/angular.min.js:36:315)
at Object.workFn (/home/igorsantana/gumga/gumga-framework-frontend/bower_components/angular-mocks/angular-mocks.js:2436:20)
Error: Declaration Location
at window.inject.angular.mock.inject (/home/igorsantana/gumga/gumga-framework-frontend/bower_components/angular-mocks/angular-mocks.js:2407:25)
at Suite.<anonymous> (/home/igorsantana/gumga/gumga-framework-frontend/test/modules/gumga/directives/GumgaAdvancedSearchSpec.js:35:24)
at /home/igorsantana/gumga/gumga-framework-frontend/test/modules/gumga/directives/GumgaAdvancedSearchSpec.js:6:9
at Object.context.execCb (/home/igorsantana/gumga/gumga-framework-frontend/node_modules/requirejs/require.js:1665:33)
at Object.Module.check (/home/igorsantana/gumga/gumga-framework-frontend/node_modules/requirejs/require.js:874:51)
at Object.<anonymous> (/home/igorsantana/gumga/gumga-framework-frontend/node_modules/requirejs/require.js:1121:34)
at /home/igorsantana/gumga/gumga-framework-frontend/node_modules/requirejs/require.js:132:23
我的代码: https://gist.github.com/opsigor/bafbf9d1843c77278ce8
有人知道我该如何解决这个问题?我是Jasmine的新手!
答案 0 :(得分:0)
您的测试失败的原因是您要么没有正确设置测试(创建模板并将其编译到范围/ templateCache中),要么找不到对文档的正确引用。
无论哪种方式,您都需要使用$document
provider as a best practice,因为参考与测试中的window.document
不同。
所以使用这个:
$document.getElementById('selectableAdvancedValue')
.addEventListener('keydown',function(ev){
if(ev.keyCode == 13 && ev.target.value.length > 0){
scope.addQuery(scope.query);
}
scope.$apply();
});
请注意,如果#selectableAdvancedValue是输入值,为什么不使用ng-model并绑定更改?您选择采用的方法是针对Angular最佳实践。这不是jQuery,利用它! Take a look at common pitfalls