Nodejs:使用sinon和async / await进行测试

时间:2017-12-13 23:40:56

标签: javascript node.js async-await sinon

无法使用sinon和async / await运行此测试。以下是我正在做的事情的一个例子:

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

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

测试:

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)
})

通过console.log我已经确认funcA正在生成正确的网址,但是,我收到错误AssertError: expected funcB to be called with arguments。当我尝试调用stubFuncB.getCall(0).args时,它会打印出null。所以也许是我对async / await缺乏了解,但我无法弄清楚为什么url没有被传递给那个函数调用。

由于

1 个答案:

答案 0 :(得分:7)

我认为你的funcs声明不正确。 Sinon无法在getRoute53内调用funcBfuncA,请尝试以下内容:

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.sandbox.create();
  })

  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。另外,使用沙箱。清理存根更容易