且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Mocha测试异步功能

更新时间:2023-01-16 20:12:24

(coffeescript中的答案.如果要将咖啡转换为js,请使用

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

如果要测试异步代码,则需要使用done模式:

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/在异步代码"下.看起来createJob返回的是true,因为测试正在压缩代码以发送帖子等,然后说是的,我按照您的要求发送了所有内容!".

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!".

我建议马丁·福勒(Martin Fowler)的有关使用Mocha测试异步js代码的文章: http://martinfowler. com/articles/asyncJS.html .

I'd recommend Martin Fowler's article on testing asynch js code with mocha: http://martinfowler.com/articles/asyncJS.html.

我有一大堆代码可以测试从数据库中检索用户(使用sinon进行存根).实际代码连接到数据库,然后使用用户的配置调用onSuccess:onSuccess(config)

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()

...稍后

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