0

这段代码能否以更具功能性/下划线风格进行重构,主要是检查 in 是否存在的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)
4

2 回答 2

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
于 2013-05-17T21:44:07.037 回答
1

Maybe using Coffee's postfix for and in operator can make the code more readable:

addedEvents = ['dragenter', 'drop', 'dragleave', 'register']
actualEvents = _.keys $._data(window, 'events') #=> ['onload', 'drop', 'etc.']
expect(event not in actualEvents).toBe(true) for event in addedEvents

If you're using Jasmine as your testing library, you can use the toContain which i think is more readable :)

expect(actualEvents).not.toContain(event) for event in addedEvents

Finally, if you want to go for a more functional style with Underscore, you can think of this assertion as checking that none of the addedEvents is present on the actualEvents, in other words, that the intersection of those two arrays is empty:

expect(_.intersection(actualEvents, addedEvents).length).toBe(0)
于 2013-05-18T11:04:11.980 回答