mocha with nodejs assert hangs/timeouts for assert(false) instead of error

前端 未结 3 1805
醉梦人生
醉梦人生 2021-01-17 20:56

I have this kind of a mocha test:

describe \'sabah\', →
    beforeEach →
        @sabahStrategy = _.filter(@strats, { name: \'sabah2\' })[0]
            .str         


        
相关标签:
3条回答
  • 2021-01-17 21:45

    Because that's what you're telling it you want to do, when you add the 'done' callback.

    The way to actually do this test is to call return done(err) if the assertion would fail, where err is any string or error object you want reported.

    First, when your assertion fails, the program throws an exception and never reaches done(), which is why you're not seeing done get called. This is how assertions are supposed to work, however since you're in an async test, the result is that the callback never fires, which is why you hit the timeout.

    Second, as my original answer said err is any error you want to send out from the test. It can be a string error message or a full-on Error object subclass. You create it and then pass it to done() to indicate the test failed.

    The better way to structure your code in an asynchronous test is to use your tests as simple booleans, rather than as assertions. If you really want to use assert, then wrap it in a try..catch. Here's a couple examples:

    if(err) return done(err); // in this case, err is defined as part of the parent callback signature that you have in your code already.
    
    if(result.length < 1) return done('Result was empty!'); 
    

    Finally, if you really want to assert, then you can:

    try{
      assert(!err);
    }catch(e){
      return done(e);
    }
    

    I'm calling return done(err) rather than done(err) because it stops the rest of the code from executing, which is normally what you want.

    0 讨论(0)
  • 2021-01-17 21:47

    When I use Highland.js with a super simple test, Mocha catches the failing assert without any problem:

    var _ = require("highland");
    var fs = require("fs");
    var assert = require("assert");
    
    describe("test", function () {
        it("test", function (done) {
            var s = _([1, 2, 3, 4]);
            s.pull(function (err, result) {
                console.log(result);
                assert(false);
                done();
            });
        });
    });
    

    This suggests that the problem in your example is not Mocha, nor Highland.js. If the articleLinkStream object (or articleSream; it seems to change from snippet to snippet) is custom code then maybe that code is buggy and actually swallows exceptions rather than let them move up the stack.

    0 讨论(0)
  • 2021-01-17 21:54

    For anyone with same issue: You should make sure that done() gets called even after an assert fails, like in the following code:

    try {
      // your asserts go here
      done();
    } catch (e) {
      done(e);
    }
    
    0 讨论(0)
提交回复
热议问题