promise & mocha: done() in before or not?

前端 未结 3 1388
生来不讨喜
生来不讨喜 2021-01-19 23:42

I am reading some tutorials on promise tests in mocha. There is a piece of codes:

before(function(done) {
  return Promise.resolve(save(article)).then(functi         


        
3条回答
  •  遥遥无期
    2021-01-19 23:56

    The first code snippet with the before hook returns a promise and calls done. In Mocha 3.x and over, it will result in this error:

    Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.
    

    It used to be that it did not particularly matter if you used done and returned a promise, but eventually the Mocha devs figured that specifying both done and returning a promise just meant the test designer made a mistake and it was better to have Mocha pitch a fit rather than silently allow it.

    In your 2nd snippet, you have the done argument and return a promise but Mocha will still wait for done to be called and will timeout. (It really should detect the argument and raise an error like in the 1st case, but it doesn't...)

    Generally, if you are testing an asynchronous operation that produces a promise, it is simpler to return the promise than use done. Here's an example illustrating the problem:

    const assert = require("assert");
    
    // This will result in a test timeout rather than give a nice error
    // message.
    it("something not tested properly", (done) => {
        Promise.resolve(1).then((x) => {
            assert.equal(x, 2);
            done();
        });
    });
    
    // Same test as before, but fixed to give you a good error message
    // about expecting a value of 2. But look at the code you have to
    // write to get Mocha to give you a nice error message.
    it("something tested properly", (done) => {
        Promise.resolve(1).then((x) => {
            assert.equal(x, 2);
            done();
        }).catch(done);
    });
    
    // If you just return the promise, you can avoid having to pepper your
    // code with catch closes and calls to done.
    it("something tested properly but much simpler", () => {
        return Promise.resolve(1).then((x) => {
            assert.equal(x, 2);
        });
    });
    

    With regards to the completion of asynchronous operations, it works the same whether you are using it, before, beforeEach, after or afterEach so even though the example I gave is with it, the same applies to all the hooks.

提交回复
热议问题