Jest でモックインポートの動作を変更するにはどうすればよいでしょうか? 質問する

Jest でモックインポートの動作を変更するにはどうすればよいでしょうか? 質問する

Jest でモック モジュールの動作を変更するのに問題があります。さまざまな動作をモックして、さまざまな状況でコードがどのように動作するかをテストしたいのですが、 の呼び出しがjest.mock()ファイルの先頭に引き上げられるため、各テストで を呼び出すことができないため、これを行う方法がわかりませjest.mock()ん。1 つのテストでモック モジュールの動作を変更する方法はありますか?

jest.mock('the-package-to-mock', () => ({
    methodToMock: jest.fn(() => console.log('Hello'))
}))

import * as theThingToTest from './toTest'
import * as types from './types'

it('Test A', () => {
    expect(theThingToTest.someAction().type).toBe(types.SOME_TYPE)
})

it('Test B', () => {
    // I need the-package-to-mock.methodToMock to behave differently here
    expect(theThingToTest.someAction().type).toBe(types.OTHER_TYPE)
})

内部的には、ご想像のとおり、theThingToTest.someAction()をインポートして使用しますthe-package-to-mock.methodToMock()

ベストアンサー1

モジュールをモックし、をmethodToMockスパイに置き換えた後、それをインポートする必要があります。その後、各テストで、methodToMockを呼び出すことでの挙動を変更できます。mockImplementationスパイの方法。

jest.mock('the-package-to-mock', () => ({
    methodToMock: jest.fn()
}))

import { methodToMock } from 'the-package-to-mock'

it('Test A', () => {
    methodToMock.mockImplementation(() => 'Value A')
    // Test your function that uses the mocked package's function here.
})

it('Test B', () => {
    methodToMock.mockImplementation(() => 'Value B')
    // Test the code again, but now your function will get a different value when it calls the mocked package's function.
})

おすすめ記事