经历了karma-jasmine测试角度app的一些特殊行为。
在一个套件中进行测试,报告失败但是消息来自另一个测试套件文件中的单独测试。
测试结果:
factory: page should uncheck all items FAILED
Expected undefined to contain '<div class="ui-select-container ui-select-bootstrap dropdown ng-valid" ng-class="{open: $select.open}" ng-model="test.slctbx.selected" theme="bootstrap" ng-disabled="disabled"></div>'
该测试实际上是:
describe 'factory: page', () ->
...
it 'should check all items', () ->
Page.checkAll null
expect(Page.actions).toEqual {checkAll: false}
错误实际上来自:
describe 'directive: select', () ->
...
it 'should replace select box', () ->
replacementMarkup = '<div class="ui-select-container ui-select-bootstrap dropdown ng-valid" ng-class="{open: $select.open}" ng-model="test.slctbx.selected" theme="bootstrap" ng-disabled="disabled"></div>'
setTimeout () ->
expect($('select').length).toEqual 0
expect($('form').html()).toContain replacementMarkup
return
, 0
如果我删除了工厂:页面套件,这种行为只是存在,而是另一个测试套件。
超时是臭的,但这只是因为该指令在其中有一个等待任意时间的超时,因此它要替换的元素已被填充...(这本身有点臭!)< / p>
====编辑+指令代码====
link: (scope, element, attrs) ->
items = []
name = element.attr('name').replace '[]', ''
placeholder = ''
for index, el of element.find('option') when typeof el is 'object' and index isnt '0'
if index == '1'
placeholder = el.innerHTML
else if typeof el[0] == 'undefined'
items.push {value: el.getAttribute('value'), label: el.innerHTML}
if typeof scope.$parent.test != 'object'
scope.$parent.test = {}
scope.$parent.test[name] = items
select = '<ui-select ng-model="test.' + name + '.selected" theme="bootstrap" ng-disabled="disabled">
<ui-select-match placeholder="' + placeholder + '">{{ $select.selected.label }}</ui-select-match>
<ui-select-choices repeat="item in test[\'' + name + '\'] | filter: $select.search">
<div ng-bind-html="item.label | highlight: $select.search"></div>
</ui-select-choices>
</ui-select>'
newSel = $compile(select)(scope.$parent)
setTimeout () ->
element.replaceWith angular.element(newSel)
, 10
return false
答案 0 :(得分:1)
为什么不在指令和测试中使用$timeout
而不是setTimeout()
?您可以在测试中使用$timeout.flush()
来验证指令是否等待了任意时间而无需等待它。
您的指令应使用$timeout(func, arbitraryAmountOfTime)
而不是setTimeout(func, arbitraryAmountOfTime)
,然后测试变为:
it 'should replace select box', ->
inject ($timeout) ->
$timeout.flush()
expect($('select').length).toEqual 0
expect($('form').html()).toContain replacementMarkup
我认为在当前的代码中,jasmie会继续进行下一个测试,然后你的计时调用将无法通过当前正在执行的测试失败。但这只是一种预感。