Skip to content

Instantly share code, notes, and snippets.

@camerond
Last active December 29, 2015 00:19
Show Gist options
  • Save camerond/7585443 to your computer and use it in GitHub Desktop.
Save camerond/7585443 to your computer and use it in GitHub Desktop.
Qunit helper assertions, e.g. $.shouldBe('.awesome')
# Used by assertions.
# $("<div class='hammer'>Pants</div>").selectorText()
# outputs the following:
# "%div.hammer with text of 'Pants'"
$.fn.selectorText = () ->
selector = "%#{@[0].tagName.toLowerCase()}"
@attr('id') && selector += "##{@.attr('id')}"
@attr('class') && selector += ".#{@.attr('class')}"
text = if @text().length > 20 then "#{@text().slice(0, 20)}..." else @text()
if text then selector = selector + " with text of '#{text}'"
selector
# Assert a value of an input
# $input.shouldHaveValue('pants')
$.fn.shouldHaveValue = (val, msg) ->
equal @.val(), val, msg or "#{@selectorText()} should have a value of #{val}"
@
# Assert state
# $element.shouldBe(':visible')
# $element.shouldBe('.active')
#
# (If passed a set of elements, only returns true if all elements pass assertion)
$.fn.shouldBe = (attr, msg) ->
state = true
@each ->
state = $(@).is(attr)
ok state, msg or "#{$(@).selectorText()} should be #{attr}"
state
@
$.fn.shouldNotBe = (attr, msg) ->
state = true
@each ->
state = !$(@).is(attr)
ok state, msg or "#{$(@).selectorText()} should not be #{attr}"
state
@
# Assert text
# $element.shouldSay('Hammertime!')
$.fn.shouldSay = (text, msg) ->
equal @text(), text, msg or "#{text} is displayed within #{@selectorText()}"
@
# Assert (loose) equality of elements
# e.g. check that an element has been appended properly (once)
$.fn.shouldEqual = ($el) ->
ok $(@).length == 1 && $el.length == 1, 'checking for element duplication'
equal $(@)[0], $el[0], "#{$(@).selectorText()} is equal to #{$el.selectorText()}"
@
# Assert that a set of elements are the only ones of their siblings
# with a certain state.
#
# For example, check to see that a <li> with the class of 'active' is
# the only 'active' item in that list.
#
# Can also accept a set of
# elements, e.g. $('.visible_thing, .other_visible_thing').shouldBeOnly(':visible')
$.fn.shouldBeOnly = (attr, msg) ->
state = true
$set = @
$set.each ->
state = $(@).is(attr)
if state
state = !$(@).siblings().not($set).is(attr)
ok state, msg or "#{$(@).selectorText()} should be one of the only #{attr} elements"
state
@
# Simulate a keypress on an element.
# e.g. $(input).pressKey(27, 'escape')
$.fn.pressKey = (k, msg) ->
if (msg)
ok(true, "I press " + msg);
$e = $.Event('keydown')
$e.keyCode = $e.which = k
$(@).trigger($e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment