这个代码可以用更多功能/下划线样式重构,主要是检查addedEvents
中是否存在actualEvents
的部分吗?
describe 'when removing', ->
it 'should remove all bound events from the window', ->
@view.remove()
addedEvents = ['dragenter', 'drop', 'dragleave', 'register']
actualEvents = _.keys $._data(window, 'events') #=> ['onload', 'drop', 'etc.']
for event in addedEvents
present = _.contains(actualEvents, event)
expect(present).toBe(false)
答案 0 :(得分:1)
如果您特别希望它使用下划线功能,则应执行以下操作。
addedEvents = ['dragenter', 'drop', 'dragleave', 'register']
actualEvents = _.keys $._data(window, 'events')
present = _.reduce addedEvents, ((prev, current) ->
prev or _.contains actualEvents, current
), false)
expect(present).toBe false
当然,您可以在没有下划线的情况下执行此操作,但它需要ES5函数:
addedEvents = ['dragenter', 'drop', 'dragleave', 'register']
actualEvents = Object.keys $._data(window, 'events')
present = addedEvents.reduce, ((prev, current) ->
prev or actualEvents.indexOf(current) > -1
), false)
expect(present).toBe false
答案 1 :(得分:1)
使用Coffee的postfix for
和in
运算符可以使代码更具可读性:
addedEvents = ['dragenter', 'drop', 'dragleave', 'register']
actualEvents = _.keys $._data(window, 'events') #=> ['onload', 'drop', 'etc.']
expect(event not in actualEvents).toBe(true) for event in addedEvents
如果你使用Jasmine作为测试库,你可以使用我认为更具可读性的toContain
:)
expect(actualEvents).not.toContain(event) for event in addedEvents
最后,如果您想使用Underscore寻找更具功能性的风格,您可以将此断言视为检查addedEvents
上是否存在actualEvents
,换句话说,这两个数组的intersection为空:
expect(_.intersection(actualEvents, addedEvents).length).toBe(0)