Home > Software engineering >  How do I stub a callback function inside object parameter using sinon?
How do I stub a callback function inside object parameter using sinon?

Time:01-17

Working on project that uses a STOMP library called stompit. Had to make a change that adds the onReceipt callback which is provided via options parameter.

Basically the code looks like this:

       const promise = new Promise((resolve) => {
            const frame = client.send(headers, {onReceipt: () => {
                client.disconnect();
                resolve();
            }});
            frame.write('something');
            frame.end();
        });

I am having issues stubbing out onReceipt part. I have tried the following in my tests but it doesn't work:

        const fakeFrame = {
            write: sinon.stub(),
            end: sinon.stub()
        };

        const fakeClient = {
            send: sinon.stub().withArgs(sinon.match.any, {onReceipt: sinon.stub().yields()}).returns(fakeFrame),
            connect: sinon.stub(),
            disconnect: sinon.stub()
        };

Any ideas what I might be doing wrong? The project is using Sinon 8.0.4 btw.

CodePudding user response:

So turns out I needed to use callsFake to fake the function from sinon.stub() to do the trick.

Basically I ended up with this:

        fakeClient = {
            send: sinon.stub().callsFake((headers, options) => {
                options.onReceipt();
                return fakeFrame;
             }),
            connect: sinon.stub(),
            disconnect: sinon.stub(),
        };
  • Related