Search code examples
node.jsunit-testingmocha.jsmiddleware

Mocha call all "it" callbacks simulations (Testing middleware)


I try to test a middleware in mocha. The problem is, that all "it" calls waiting for the previous one to finish, before executing their callback.

it(`should trigger pre hook 1`, (done) => {
    use((next) => {
        setTimeout(() => {
            done();
            next();
        }, 1000);
    });
});

it(`should trigger pre hook 2`, (done) => {
    use((next) => {
        setTimeout(() => {
            done();
            next();
        }, 1000);
    });
});

start(() => {
  // middleware done
});

The second it(...) waits for the first to complete.
And thats exactly the problem, since the second use(...) is not called before i fire the start(...) function, so it never gets executed and the test fails.

How can i tell mocha to execute all "it" callbacks and wait not for the previous one to complete (or fails)?


Solution

  • Try a spy instead of done so you can layout the tests as needed without relying on mocha to control the flow.

    describe('middleware', function(){
    
        // initialise use/start for this test
    
        const m1 = sinon.spy()
        const m2 = sinon.spy()
        use((next) => {
            setTimeout(() => {
                m1();
                next();
            }, 1000);
        });
        use((next) => {
            setTimeout(() => {
                m2();
                next();
            }, 1000);
        });
    
        it(`should process a request through middleware`, function(done){
            start(() => {
                // middleware done
                expect(m1.calledOnce, `m1`).to.equal(true)
                expect(m2.calledOnce, `m2`).to.equal(true)
                done()
            });
        })
    
    })
    

    The spy will also let you check on more complex call scenarios in the middleware when you have functional code in there.