tj / should.js

BDD style assertions for node.js -- test framework agnostic
MIT License
2.75k stars 195 forks source link

asynchronous throw #42

Closed quangv closed 11 years ago

quangv commented 12 years ago

What's the best way to test for throw() (great addition btw) asynchronously? using with mocha.

Example...

it('works sync', function() {
  (function() {
    throw {message: 'error'};
  }).should.throw();
});

this works.
it('should throw async', function(done) {
  (function() {
    setTimeout(function() {
      throw {message: 'error'};
    }, 200);
  }).should.throw();
});     

AssertionError: expected an exception to be thrown
tj commented 12 years ago

those callsites will have come and gone so you can't try/catch async stuff, that's why node does callback(err)

tj commented 12 years ago

also: devthought.com/2011/12/22/a-string-is-not-an-error/

you wont want to throw { message: 'here' }, even though it's not a string, same stuff applies

quangv commented 12 years ago

hey TJ, thanks for the link, yeh I still don't know how to read those stacktraces... I should figure that out.

correct me if I'm wrong, but if you throw new Error doesn't mocha just stop and returns?


nvm I was wrong

suite 'Test', ->
    test 'throw Error', ->
        (->
            throw new Error 'Cat'
        ).should.throw()

works fine... reason i thought so was because I was having trouble using .should.throw() with superagent (detecting failure) but maybe it's more to do with it being async...


var request = require('superagent');

it('tests connection failure', function(done) {
  (function() {
    request.get('blahblah', function(res) {
      res.status.should.eql(200);
      done();
    });
  }).should.throw();
});

  AssertionError: expected an exception to be thrown

excuse the coffee-script... hope you don't mind, I was too lazy to copy/paste into cs compiler :)

tj commented 12 years ago

what do you mean? you dont know how to read stack traces? but the thing is that exceptions just "unwind" the stack, so when you're in a callback from something async it's not the same stack anymore so try/catch doesn't work

quangv commented 12 years ago
Error
    at Object.<anonymous> (/private/tmp/error.js:2:11)
    at Object.<anonymous> (/dir/errorLoop.coffee:6:4)
    at Module._compile (node.js:462:23)

might be cause I predominantly use coffee-script, but those :2:11 never matches up for me lol... so I usually disregard the error outputs...

tj commented 12 years ago

ah.. yeah that would be coffeescript for you lol aren't you glad it's so helpful

quangv commented 12 years ago

hah... yes... but coffee has it's perks... !