Skip to content

Instantly share code, notes, and snippets.

@arktisklada
Last active December 16, 2015 16:54
Show Gist options
  • Save arktisklada/4049ef71587cde5db0e7 to your computer and use it in GitHub Desktop.
Save arktisklada/4049ef71587cde5db0e7 to your computer and use it in GitHub Desktop.
Demo exercise for unit testing a basic JavaScript class in coffeescript. We have links on the page. Instead of following the link, we want to handle those requests with ajax and console.log the ajax response.
// /app/assets/javascripts/application.js
//= require TestClass
# /app/assets/javascripts/TestClass.coffee
class @TestClass
constructor: ->
@ajaxLink = $(".ajax-link")
@_initEvents()
_initEvents: ->
@ajaxLink.on "click", (e) ->
e.preventDefault()
linkText = @.text
window.alert(linkText)
linkUrl = $(@).attr("href")
$.ajax(
url: linkUrl
dataType: "json"
).done (a, b, c) ->
console.log a, b, c
# /spec/javascripts/TestClass_spec.coffee
#= require spec_helper
describe "TestClass", ->
it "disables normal link-clicking for .ajax-link links", ->
setDefaultFixture()
event = jQuery.Event("click")
eventSpy = sinon.spy(event, "preventDefault")
new TestClass()
$(".ajax-link").trigger(event)
expect(eventSpy).to.have.been.called
it "triggers an alert with the link text", ->
linkText = "Try clicking me"
setFixtures """
<a href="" class="ajax-link">#{linkText}</a>
"""
alertSpy = sinon.spy(window, "alert")
new TestClass()
clickAjaxLink()
expect(alertSpy).to.have.been.calledWith(linkText)
alertSpy.restore()
it "launches an ajax request with the link href URL", ->
linkUrl = "link-url-to-nowhere-special"
setFixtures """
<a href="#{linkUrl}" class="ajax-link">Blah blah blah</a>
"""
ajaxSpy = sinon.spy($, "ajax")
new TestClass()
clickAjaxLink()
expect(ajaxSpy).to.have.been.calledWithMatch(url: linkUrl)
ajaxSpy.restore()
it "logs the ajax response arguments", ->
setDefaultFixture()
consoleSpy = sinon.spy(console, "log")
deferred = new $.Deferred
ajaxStub = sinon.stub($, "ajax").returns(deferred)
new TestClass()
methodStub = sinon.stub()
clickAjaxLink()
deferred.resolveWith(null, [methodStub, 2, 3])
expect(consoleSpy).to.have.been.calledWith(methodStub)
consoleSpy.restore()
ajaxStub.restore()
setDefaultFixture = ->
setFixtures """
<a href="" class="ajax-link">Try clicking me</a>
"""
clickAjaxLink = ->
$(".ajax-link").trigger("click")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment