Jestを使ってClassのメソッドを一部Mock化する方法

概要

Jestを使ってClassのメソッドを一部Mockにしてテストを回す方法を記載します

結論

prototypeを使い該当メソッドを対象のテストファイルにてjest.fnで更新します

// prototypeを使用してメソッドをmockに更新
Class.prototype.method = jest.fn()

// 戻り値も定義したい場合、mockReturnValueを使用する
Class.prototype.method = jest.fn().mockReturnValue(1)

例えば、MemberクラスのgetNameメソッドをmock化するなら

Member.prototype.getName = jest.fn()

となります。

参考コード

prototypeを実際に使用したテストコードを下記に載せておきます。

リポジトリ

github.com

テストコード

  // outline: Check arguments when run createGrayScotModel
  it('should create gray-scott-model with expected arguments', () => {
    const createMethodMock = jest.fn()
    GrayScotModelFactory.prototype.create = createMethodMock.mockReturnValue({
      materialU: Array.from(new Array(100), () => new Array(100).fill(0)),
      update: () => {}
    })

    const wrapper: any = mount(GrayScotModelSimulator)

    expect(createMethodMock.mock.calls.length).toBe(1);
    expect(createMethodMock.mock.calls[0]).toMatchObject([ 0.022, 0.051, 100, 12 ])
    expect(createMethodMock.mock.results[0]["type"]).toBe("return");
    
    wrapper.vm.createGrayScotModel(0.035, 0.065)

    expect(createMethodMock.mock.calls.length).toBe(2);
    expect(createMethodMock.mock.calls[1]).toMatchObject([ 0.035, 0.065, 100, 12 ])
    expect(createMethodMock.mock.results[1]["type"]).toBe("return");
  })