【问题标题】:Nodejs: Testing with sinon and async/awaitNodejs:使用 sinon 和 async/await 进行测试
【发布时间】:2018-05-27 23:27:00
【问题描述】:

无法使用 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 生成的URL 正确,但是,我收到了错误AssertError: expected funcB to be called with arguments。当我尝试调用stubFuncB.getCall(0).args 时,它会打印出空值。所以也许是我对 async/await 缺乏了解,但我无法弄清楚为什么 url 没有被传递给那个函数调用。

谢谢

【问题讨论】:

    标签: javascript node.js async-await sinon


    【解决方案1】:

    我认为您的 funcs 声明不正确。 Sinon 无法存根 getRoute53funcBfuncA 内部调用,试试这个:

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

    附:另外,使用沙盒。清理存根更容易

    【讨论】:

    • 这非常有用,帮助我解决了很多单元测试问题!我将开始在对象内的文件中导出我的所有函数!感谢您的帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多