Mocha tests for asynchronous functions

时光怂恿深爱的人放手 提交于 2019-12-13 16:25:32

问题


I'm writing a node wrapper to interact with an external api and am having a difficult time testing the asynchronous createJob 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", ->
  @timeout(50000)
  describe "create", ->
    it "should create a job with address_id", (done) ->
      lob.jobs.createJob data, (new_job) ->
        new_job.should.not.be.empty
        new_job['name'].should.equal(data['name'])
        done()

Edit

The above code resolves the issue


回答1:


(Answer in coffeescript. If you'd like to convert coffee to js use http://coffeescript.org/, 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")
      user.save done

http://visionmedia.github.io/mocha/ 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: http://martinfowler.com/articles/asyncJS.html.

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 ->
      configSource.getConfig.restore()

... later

  configSource.getConfig('520bc323de4b6f7845543288', errorHandler, (config) ->
      config.should.not.be.null
      config.should.have.property('preferences')
      done()
  )



回答2:


Don't consider this like an answer to the op but a bonus for the one marked as correct.

Just to complete @jcollum answer here's the Javascript version of him code:

describe('User', function(){
    describe('#save()', function(){
        it("should save without error", function(done){
            var _user = new User("Moon");
            _user.save;
            done();
        });
    });
 });

It's pretty evident but maybe some newbies would need this addendum.



来源:https://stackoverflow.com/questions/21223093/mocha-tests-for-asynchronous-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!