Typescript と Jest: モック関数の型エラーを回避する 質問する

Typescript と Jest: モック関数の型エラーを回避する 質問する

jest.mock()Jest を使用して外部モジュールをモックする場合、モジュール上の関数を自動的にモックするメソッドを使用できます。

その後、必要に応じて、モック モジュール上のモック関数を操作および照会できます。

たとえば、axios モジュールをモックするための次の不自然な例を考えてみましょう。

import myModuleThatCallsAxios from '../myModule';
import axios from 'axios';

jest.mock('axios');

it('Calls the GET method as expected', async () => {
  const expectedResult: string = 'result';

  axios.get.mockReturnValueOnce({ data: expectedResult });
  const result = await myModuleThatCallsAxios.makeGetRequest();

  expect(axios.get).toHaveBeenCalled();
  expect(result).toBe(expectedResult);
});

上記は Jest では問題なく実行されますが、Typescript エラーが発生します。

プロパティ 'mockReturnValueOnce' は、タイプ '(url: string, config?: AxiosRequestConfig | undefined) => AxiosPromise' に存在しません。

の typedef にはaxios.get当然、プロパティは含まれていません。を としてラップすることで、Typescript にオブジェクトリテラルとしてmockReturnValueOnce処理するように強制できますが、次のようになります。axios.getObject(axios.get)

型の安全性を維持しながら関数をモックする慣用的な方法は何ですか?

ベストアンサー1

次のコード行を追加しますconst mockedAxios = axios as jest.Mocked<typeof axios>。次に、mockedAxios を使用して mockReturnValueOnce を呼び出します。コードでは、次のように実行する必要があります。

import myModuleThatCallsAxios from '../myModule';
import axios from 'axios';

jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;

it('Calls the GET method as expected', async () => {
  const expectedResult: string = 'result';

  mockedAxios.get.mockReturnValueOnce({ data: expectedResult });
  const result = await myModuleThatCallsAxios.makeGetRequest();

  expect(mockedAxios.get).toHaveBeenCalled();
  expect(result).toBe(expectedResult);
});

おすすめ記事