LoginSignup
0

More than 5 years have passed since last update.

spyOnした関数の戻り値を、実行された順番で変更する方法。(Jasmine)

Last updated at Posted at 2018-06-04

ある関数の戻り値を1回目と2回目で変更する方法。

いっつも忘れるのでメモ。

こんな時。


hoge = {
  fetchHoge: () => {}, // 何かしらを返す関数
}

// 同一関数を複数回実行する関数 
function fuga(){
  const first = hoge.fetchHoge(); // ← 'a'を返して欲しい
  const second = hoge.fetchHoge(); // ← 'b'を返して欲しい
  return [first, second]
}

以上のような感じで、fugaをテストするときに、hoge.fetchHogeの戻り値を1回目に実行された時と2回目に実行された時で変更したいとします。

方法

it('戻り値変えたいテスト', () => {
  spyOn(hoge, 'fetchHoge').and.returnValues('a', 'b');
  expect(fuga()).toEqual(['a', 'b'])
})

以上。returnValues()を使いましょうという話でした。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0