所以我对整个测试的事情都很陌生(我曾经是那些曾经说'我应该编写单元测试......但从未结束过这样做的人之一:-p)。 我现在正在为这个项目编写单元测试。我正在使用testacular + Jasmine,使用browserify来编译东西。在我开始尝试做很多AngularJS注入之前,我没有遇到任何问题。
现在,我只是试图对ng-model进行测试,以了解所有这些。
我有一个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中设置)
我在这里做错了什么?
答案 0 :(得分:10)
要实现这一目标,您需要执行scope.$apply()
:
it 'should initially equal input value', ->
scope.$apply()
expect(elm.val()).toBe scope.hello
不要测试框架,测试代码
您的测试正在尝试测试Angular的绑定,ng-model
是否有效。您应该相信框架并测试您的代码。
您的代码是:
scope.hello
值)您可以非常轻松地测试第一个,甚至无需触摸任何DOM。这就是AngularJS的美妙之处 - 视觉/逻辑的强烈分离。
在这个控制器中,几乎没有什么可以测试,但是初始值:
it 'should init hello', ->
expect(scope.hello).toBe 'initial'
要测试第二个(模板+绑定),您需要进行e2e测试。你基本上想要测试,模板是否包含绑定等中的任何拼写错误...所以你想测试真正的模板。如果你在测试期间内联了一个不同的html,那么你只测试AngularJS。