Skip to content

Instantly share code, notes, and snippets.

@johanlunds
Forked from henrik/fake_server.coffee
Created April 18, 2014 19:57
Show Gist options
  • Save johanlunds/11061752 to your computer and use it in GitHub Desktop.
Save johanlunds/11061752 to your computer and use it in GitHub Desktop.
describe "Using a fake server for Ajax", ->
server = null
beforeEach -> server = sinon.fakeServer.create()
afterEach -> server.restore()
context "when Ajax succeeds", ->
beforeEach -> respondWithJSON("/url/123", 200, '{"city": "Palm Springs"}')
it "does stuff", ->
server.respond()
context "when Ajax fails", ->
beforeEach -> respondWithJSON("/url/123", 404)
it "does stuff", ->
server.respond()
respondWithJSON = (url, status, body) ->
server.respondWith(
"GET",
url,
[status, { "Content-Type": "application/json" }, (body || "")]
)
assertThereWereNoAjaxRequests = ->
server.requests.should.be.empty()
expectToAlert = (cb) ->
fakeAlert = sinon.stub(window, "alert")
cb()
assert fakeAlert.calledOnce, "Expected alert."
# jQuery ":focus" didn't work for some reason.
assertFocused = ($element) ->
$element[0].should.eq(document.activeElement)
# Debug.
window.showHtml = ->
console.log "-----"
console.log $(document.body).html()
console.log "-----"
# FIXME: Not sure if this is a good pattern. Would be more unit-y to decouple tests from the ready event.
# Wrap jQuery.ready so we can trigger it in
# our mocha tests, which replace the body after
# the original ready event.
window.domReadyFunctions = []
window.fakeDomReady = ->
fn() for fn in domReadyFunctions
$.fn.oldReady = $.fn.ready
$.fn.ready = (fn) ->
domReadyFunctions.push(fn) if fn
$.fn.oldReady.apply(this, arguments)
# Similar to RSpec's "let".
# TODO: Make it more similar.
describe "Foo", ->
$thing = undefined
beforeEach ->
$thing = $("#thing")
it "works", ->
$thing.should.be("#thing")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment