Jest で静的メソッドをモックアップする 質問する

Jest で静的メソッドをモックアップする 質問する

静的メソッドを冗談でモックアップするのに苦労しています。静的メソッドを持つクラス A があると想像してください。

export default class A {
  f() {
    return 'a.f()'
  }

  static staticF () {
    return 'A.staticF()'
  }
}

そしてAをインポートするクラスB

import A from './a'

export default class B {
  g() {
    const a = new A()
    return a.f()  
  }

  gCallsStaticF() {
    return A.staticF()
  }
}

ここで、A をモックアップします。f() をモックアップするのは簡単です。

import A from '../src/a'
import B from '../src/b'

jest.mock('../src/a', () => {
  return jest.fn().mockImplementation(() => {
    return { f: () => { return 'mockedA.f()'} }
  })
})

describe('Wallet', () => {
  it('should work', () => {
    const b = new B()
    const result = b.g()
    console.log(result) // prints 'mockedA.f()'
  })
})

しかし、A.staticF をモックアップする方法に関するドキュメントは見つかりませんでした。これは可能ですか?

ベストアンサー1

モックを静的メソッドに割り当てるだけでよい

import A from '../src/a'
import B from '../src/b'

jest.mock('../src/a')

describe('Wallet', () => {
    it('should work', () => {
        const mockStaticF = jest.fn().mockReturnValue('worked')

        A.staticF = mockStaticF

        const b = new B()

        const result = b.gCallsStaticF()
        expect(result).toEqual('worked')
    })
})

おすすめ記事