单元测试 – 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值) 您可以非常轻松地测试第一个,甚至无需触摸任何DOM.这就是AngularJS的美妙之处 – 强烈的视图/逻辑分离. 在这个控制器中,几乎没有什么可以测试,但初始值: it 'should init hello',-> expect(scope.hello).toBe 'initial' 要测试第二个(模板绑定),您需要进行e2e测试.你基本上想要测试,模板是否包含绑定等中的任何拼写错误…所以你想测试真正的模板.如果你在测试期间内联了一个不同的html,那么你只测试AngularJS. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- macos – OSX终端:如何杀死具有相同名称的所有进程
- angularjs – 如何显示/隐藏如果变量为null
- bootstrap-带链接的列表组
- yum出错Error: Cannot find a valid baseurl for repo: bas
- webservice-之使用axis+spring开发(转自勇哥的BLOG)
- Bootstrap响应式前端框架笔记一——强大的栅格布局
- 【JAX-WS入门系列】第03章_使用SAAJ创建SOAP消息
- 在bash中退出管道
- scala – VarArgs A * vs Seq [A]参数的功能
- 套接字 – Pycharm Docker Unix / TCP套接字(使用unix://