所以我是整个测试的新手(我曾经是那些曾经说’我应该编写单元测试……但从未结束过这样做的人之一:-p).
我现在正在为这个项目编写单元测试.我正在使用testacular Jasmine,用browserify来编译东西.在我开始尝试做很多AngularJS注入之前,我没有遇到任何问题.
我现在正在为这个项目编写单元测试.我正在使用testacular Jasmine,用browserify来编译东西.在我开始尝试做很多AngularJS注入之前,我没有遇到任何问题.
现在我只是试图对ng模型进行测试,以便了解所有这些.
我有一个testacular.conf文件,其中包含所有必需的内容:
files = [ '../lib/jquery.js','../lib/angular.js','./lib/jasmine.js','./lib/angular-mocks.js',JASMINE_ADAPTER,'./tests.js' //compiled by browserify ];
我定义了我的控制器(MainCtrl.coffee)
MainCtrl = ($scope,$rootScope) -> $scope.hello = 'initial' module.exports = (angularModule) -> angularModule.controller 'MainCtrl',['$scope','$rootScope',MainCtrl] return MainCtrl
我有自己的测试:(_ MainCtrlTest.coffee,与MainCtrl.coffee在同一目录中)
testModule = angular.module 'MainCtrlTest',[] MainCtrl = require('./MainCtrl')(testModule) describe 'MainCtrlTest',-> scope = null elm = null ctrl = null beforeEach inject ($rootScope,$compile,$controller) -> scope = $rootScope.$new() ctrl = $controller MainCtrl,$scope: scope elm = $compile('<input ng-model="hello"/>')(scope) describe 'value $scope.hello',-> it 'should initially equal input value',-> expect(elm.val()).toBe scope.hello it 'should change when input value changes',-> scope.$apply -> elm.val('changedValue') expect(scope.hello).toBe elm.val()
测试立即失败,输入的elm.val()返回空白,scope.hello返回预期值(‘initial’,在MainCtrl.coffee中设置)
我在这做错了什么?
解决方法
要使其正常工作,您需要执行范围.$apply():
it 'should initially equal input value',-> scope.$apply() expect(elm.val()).toBe scope.hello
不要测试框架,测试你的代码
您的测试试图测试Angular的绑定和ng-model是否有效.您应该相信框架并测试代码.
你的代码是:
>控制器(设置初始scope.hello值)
> html模板(以及那里的所有绑定,指令)
您可以非常轻松地测试第一个,甚至无需触摸任何DOM.这就是AngularJS的美妙之处 – 强烈的视图/逻辑分离.
在这个控制器中,几乎没有什么可以测试,但初始值:
it 'should init hello',-> expect(scope.hello).toBe 'initial'
要测试第二个(模板绑定),您需要进行e2e测试.你基本上想要测试,模板是否包含绑定等中的任何拼写错误…所以你想测试真正的模板.如果你在测试期间内联了一个不同的html,那么你只测试AngularJS.