单元测试 – AngularJS – 带注射的基本测试

所以我是整个测试的新手(我曾经是那些曾经说’我应该编写单元测试……但从未结束过这样做的人之一:-p).
我现在正在为这个项目编写单元测试.我正在使用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.

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...