0
2

More than 1 year has passed since last update.

jest でスタブする方法まとめ

Last updated at Posted at 2022-11-04

基本的には jest.spyOn() だけでほとんどのユースケースをカバーできる。

グローバル関数のスタブ

const spy = jest.spyOn(global, 'parseInt')
            .mockReturnValue(10)

クラスメソッドのスタブ

const spy = jest.spyOn(Date, 'now')
            .mockReturnValue(1577804400000);

インスタンスメソッドのスタブ

const spy = jest.spyOn(MyClass.prototype, 'myMethod')
            .mockReturnValue('mocked');

メソッドが getter/setter の場合、第 3 引数に get or set を指定する。

jest.spyOn(MyClass.prototype, 'myMethod', 'get')

特定のインスタンスのメソッドのスタブ

↑ は MyClass の全てのインスタンスが対象なのに対して、特定のインスタンスに絞ってメソッドをスタブする。

const ins1 = new MyClass();
const ins2 = new MyClass();
const spy = jest.spyOn(ins1, 'myMethod')
            .mockReturnValue('mocked');

ins1.myMethod();  // スタブされている
ins2.myMethod();  // こちらはスタブされない

プロパティのスタブ

インスタンスの getter メソッドのスタブ方法と同じで、第 3 引数に get を指定してやる必要がある

const spy = jest.spyOn(HTMLElement.prototype, 'offsetTop', 'get')
            .mockReturnValue(10);

const element = document.querySelector('div');
element.offsetTop;  // 10

export default / named export のスタブ

スタブ対象のモジュール

myModule.js
export function foo() { ... }
export default function() { ... }

スタブの方法。ES Module の場合 import * する必要がある。

import * as myModule as fn from './myModule';

// named export の Stub
const spy = jest.spyOn(myModule, 'foo')
            .mockImplementation(() => 'mocked');

// export default の Stub
const spy = jest.spyOn(myModule, 'default')
            .mockImplementation(() => 'mocked');
0
2
0

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
2