[sinon]export functionをモックしたい時とunexepected callのerror出た時

投稿者:

こんなfunction

export function test1() {}
export function test2() {}

こんな風にstubしたりする

import * as Test from "./fileA"

sinon.stub(Test, "test1").returns([])

// 試してないけどmockはたぶんこう?
sinon.mock(Test).expects("test1").returns(true);

Unexpected callのerror出た時

ついでにメモる

mockでn回目だけ動作を変えたい時に↓みたいにすると2回目の呼び出しでUnexepected call

mock.expects("hello").resolves(true)
mock.expects("hello").resolves(false)

このように書いたらよい

mock.expects("hello").exactly(2).onFirstCall().resolves(true).onSecondCall().resolves(false)

Attempted to wrap “methodName” which is already wrappedが出た時

引数によって返す値を変えたい時に出たerror

もうモックしてあるobjをmockしようとしたら出る

mock(testObj).expects("methodName").withArgs(1).resolves(true);
mock(testObj).expects("methodName").withArgs(2).resolves(false);

このように書いたらよい

const mockTestObj = mock(testObj);
mockTestObj.expects("methodName").withArgs(1).resolves(true);
mockTestObj.expects("methodName").withArgs(2).resolves(false);

単体テストの考え方/使い方