0

Consider the following mocha+chai+sinon test:

it("will invoke the 'then' callback if the executor calls its first argument", function(done){
    let executor = function(resolve, reject){
        resolve();
    }
    let p = new Promise(executor);
    let spy = sinon.spy();

    p.then(spy);

    spy.should.have.been.called.notify(done);
});

As described in the assertion, I expected that the spy should have been called. However, mocha reports:

1) A Promise
   will invoke the 'then' callback if the executor calls its first argument:
    AssertionError: expected spy to have been called at least once, but it was never called

Substitution of the spy with a console.log demonstrates the expected flow, so I am confused as to why mocha reports the negative.

How do I change the test to prove the expected behaviour?

2 Answers2

0

I found that the solution is to use async/await, as follows:

it("will invoke the 'then' callback if the executor calls its first argument", async() => {
    let executor = function(resolve, reject){
        resolve();
    }
    let p = new Promise(executor);
    let spy = sinon.spy();

    await p.then(spy);

    spy.should.have.been.called;
});
0

Another way of achieving the same would be:

it("will invoke the 'then' callback if the executor calls its first argument", function(){
    let p = new Promise(function(resolve, reject){ resolve(); });
    let resolver = sinon.spy();

    p.then(resolver);

    return p.then( () => { resolver.should.have.been.called; });
});