cowboybebop
cowboybebop

Reputation: 2345

Assertion fails as it does not wait for promise resolution

I use mocha, sinon and chai to run a set of tests. Here is the method I'm testing

fn.method().then(function(response) {
  console.log(response)
  test()
})

I have stubbed out the method like this

test = sinon.spy()  
fn = { method: sinon.stub().resolves("hello") }

In my test I have

expect(fn.method()).to.have.been.called
console.log("goodbye")
expect(test).to.have.been.called

I expect the tests to pass and print "hello" and "goodbye" in sequence but what I see is expect(test).to.have.been.called fails and further more I see that the "hello" gets printed after "goodbye".

What would be the right way to test that test is called after the promise resolves?

Upvotes: 1

Views: 840

Answers (1)

dmitrydwhite
dmitrydwhite

Reputation: 826

It's failing because (presumably) there is enough asynchronicity in the sinon .resolves hook that your two lines

console.log("goodbye");
expect(test).to.have.been.called;

run before the code within the .then block of your tested method runs. (We know it's running because we see the console being logged, but we know that it must be running after the second expect line.)

I would unwrap your stubbed method from its expect, maybe something like:

// in test.js

fn.method().then(() => {
  expect(test).to.have.been.called;
});

Upvotes: 1

Related Questions