Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

ある関数の戻り値を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()を使いましょうという話でした。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away