2017-12-13 20 views
0

sinonとasync/awaitを使ってこのテストを実行するのに問題があります。Nodejs:sinonとasync/awaitによるテスト

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

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

とテスト:私はfuncAが正しいURLを生成していることを確認したconsole.log経由

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

しかし、私は取得しています、ここで私がやっているものの例でありますエラーAssertError: expected funcB to be called with argumentsstubFuncB.getCall(0).argsと呼ぶと、nullが出力されます。だから、async/awaitの理解が不足しているかもしれませんが、なぜurlがその関数呼び出しに渡されていないのかわかりません。

ありがとうございました

答えて

1

あなたのfuncs宣言が正しくないと思います。

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

:Sinonは funcA内部で呼び出さ getRoute53funcBはこの1つを試してみてくださいスタブことができませんでした

P.S.また、サンドボックスを使用します。スタブをきれいにするのは簡単です

+1

これは非常に役に立ち、私のユニットテストに関する多くの問題を解決するのに役立ちました!オブジェクト内のファイルにすべての関数をエクスポートし始めます。ご協力いただきありがとうございます :) –

関連する問題