Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better way of testing asynchronous code? #110

Closed
ncri opened this issue Feb 15, 2013 · 6 comments
Closed

Better way of testing asynchronous code? #110

ncri opened this issue Feb 15, 2013 · 6 comments

Comments

@ncri
Copy link

ncri commented Feb 15, 2013

This works, but is rather ugly because of the try catch block:

suite 'hide_flash', ->
  test 'should hide message div after delay', (done) ->
    $("body").append $('<div>').attr('id', 'message')
    hide_message_after_delay()
    setTimeout ->
      try
        $('#message').is(':hidden').should.be.true
        done()
      catch err
        done err
    , 1000

Is there a better way of doing this? Also, the message when the test fails is not very pretty:

Error: done() invoked with non-Error: "actual error is here"

Related is this mocha pull request I think: mochajs/mocha#278

@matthijsgroen
Copy link
Collaborator

Use promises and mocha as promised?

@jfirebaugh
Copy link
Owner

I would use sinon's fake timers.

@ncri
Copy link
Author

ncri commented Feb 15, 2013

Thanks, for the hints. Promises looks, well, promising. :) But I think in this cases fake timers suit really well, I'll give them a try. I still hope though, there is going to be a way built into Mocha to fo asynchronous stuff more cleanly... But I guess it's a Mocha rather then Konacha issue? Or can something be done in Konacha? Otherwise I guess we shall close this?

@matthijsgroen
Copy link
Collaborator

I extend mocha (the test runner) with the mocha-as-promised lib (also found in the konacha-chai-matchers gem) and test these things using chai-as-promised, plain .then => assert or the sinon fakeTimers.

All solutions work really well, but I prefer to write all async code as promises :-)

@jfirebaugh
Copy link
Owner

Yeah, this is a need that 3rd party tools (promises or fake timers) solve pretty well without needing coordination from the testing framework. You could raise it with mocha, but I suspect you'll likely get a similar response there.

@jamesmacwilliam
Copy link

in the event that you have an app that relies on a deferred block of code:
I also noticed that if you set the timeout or delay (using underscore) to 1 and put the expectation within the delayed block, the result gets picked up by the suite the same as it otherwise would

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants