Anconia Anconia - 1 year ago 102
CoffeeScript Question

Mocha tests for asynchronous functions

I'm writing a node wrapper to interact with an external api and am having a difficult time testing the asynchronous

method. Below is the test case code:

api_key = "test_0dc8d51e0acffcb1880e0f19c79b2f5b0cc"

lob = require('../src/lob')(api_key)
should = require("should")
chai = require("chai")

data =
name: "test name"
to: "Bob"
from: "Alice"
object1: "foo"
object2: "bar"

describe "Job", ->
describe "create", ->
it "should create a job with address_id", (done) -> data, (new_job) ->


The above code resolves the issue

Answer Source

(Answer in coffeescript. If you'd like to convert coffee to js use, then the Try CoffeeScript tab.)

If you're testing asynch code you'll need to use the done pattern:

describe "User", ->
  describe "#save()", ->
    it "should save without error", (done) ->
      user = new User("Luna") done under "Asynchronous code". Looks like createJob is returning true because the test is zipping through the code to send the post etc. and saying "yep, I sent all that stuff like you asked!".

I'd recommend Martin Fowler's article on testing asynch js code with mocha:

I've got a chunk of code that tests retrieval of a user from the database (using sinon for stubbing). The real code connects to the db then calls the onSuccess with the user's configuration: onSuccess(config)

  describe 'Config', ->
    orgId = 'a'
    errorHandler = ((msg) -> (throw msg))
    beforeEach ->
      readConfig = sinon.stub(sdl , 'getConfig')
      readConfig.callsArgOnWithAsync(2, configSource, JSON.parse(jsonConfig))
    afterEach ->

... later

  configSource.getConfig('520bc323de4b6f7845543288', errorHandler, (config) ->'preferences')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download