Nodejs: Testing with sinon and async/await

Alex Cauthen picture Alex Cauthen · Dec 14, 2017 · Viewed 9.2k times · Source

Having trouble getting this test to run using sinon and async/await. Here is an example of what I'm doing:

// in file funcs
async function funcA(id) {
    let url = getRoute53() + id
    return await funcB(url);
}

async function funcB(url) {
    // empty function
}

And the test:

let funcs = require('./funcs');

...

// describe
let stubRoute53 = null;
let stubFuncB = null;
let route53 = 'https://sample-route53.com/' 
let id = '1234'
let url = route53 + id;

beforeEach(() => {
    stubRoute53 = sinon.stub(funcs, 'getRoute53').returns(route53);
    stubFuncB = sinon.stub(funcs, 'funcB').resolves('Not interested in the output');
})

afterEach(() => {
    stubRoute53.restore();
    stubFuncB.restore();
})

it ('Should create a valid url and test to see if funcB was called with the correct args', async () => {
    await funcs.funcA(id);
    sinon.assert.calledWith(stubFuncB, url)
})

Via console.log I've verified that funcA is producing the correct URL, however, I'm getting the error AssertError: expected funcB to be called with arguments. When I try calling stubFuncB.getCall(0).args it prints out null. So maybe it is my lack of understanding of async/await, but I cannot figure out why the url is not being passed to that function call.

Thanks

Answer

Alexey Kucherenko picture Alexey Kucherenko · Dec 14, 2017

I think your funcs declaration is not correct. Sinon could not stub getRoute53 and funcB called inside funcA Try this one:

funcs.js

const funcs = {
  getRoute53: () => 'not important',
  funcA: async (id) => {
    let url = funcs.getRoute53() + id
    return await funcs.funcB(url);
  },
  funcB: async () => null
}

module.exports = funcs

tests.js

describe('funcs', () => {
  let sandbox = null;

  beforeEach(() => {
    sandbox = sinon.createSandbox();
  })

  afterEach(() => {
    sandbox.restore()
  })


  it ('Should create a valid url and test to see if funcB was called with the correct args', async () => {
    const stubRoute53 = sandbox.stub(funcs, 'getRoute53').returns('https://sample-route53.com/');
    const stubFuncB = sandbox.stub(funcs, 'funcB').resolves('Not interested in the output');

    await funcs.funcA('1234');

    sinon.assert.calledWith(stubFuncB, 'https://sample-route53.com/1234')
  })
})

P.S. Also, use sandbox. It's easier to clean stubs