ShEsKo
ShEsKo

Reputation: 157

sinon spy.calledOnce inside a promise returns false

I am trying to test that a function inside a stubbed promise was called. Unfortunately the spy on that function seems to be called only after the tests. Here is a simplified version of my React code.

export default class TheComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  onSend(data) {
    AUtility.aPromise(data).then(() => {
      this.props.onSend(data);
      console.log("Props onSend was called!")
    });
  }

  render() {
    return null;
  }
}

and here is the test I try to run.

it('should call the props function', (done) => {
    const onSendSpy = spy();
    const promiseStub = stub(AUtility, 'aPromise').resolves('mock string');
    wrapper = shallow(<TheComponent onSend={onSendSpy} />
    wrapper.instance().onSend();
    expect(promiseStub.calledOnce).to.be.true;  //this passes
    expect(onSendSpy.calledOnce) //this fails
    done();
});

Whenever I run the test the first assertion passes but not the second. However the print statement in my code still prints the string during the test. It seems that the done() function will make the test finish once the promise returns and not once the then block is fully executed. How can I get this test to pass?

Upvotes: 1

Views: 1251

Answers (1)

gautejohan
gautejohan

Reputation: 428

I'm by no means an expert, but could you try wrapping the two expect statements in a setTimeout function?

setTimeout(() => { expect(promiseStub.calledOnce).to.be.true; expect(onSendSpy.calledOnce); done(); }, 0);

Upvotes: 1

Related Questions