モジュールをモック化するときにjest.mock(...)
関数を使えばモックにすることができる
Jestのドキュメントにはaxiosを使った例がある
// users.test.js import axios from 'axios'; import Users from './users'; jest.mock('axios'); test('should fetch users', () => { const users = [{name: 'Bob'}]; const resp = {data: users}; axios.get.mockResolvedValue(resp); // or you could use the following depending on your use case: // axios.get.mockImplementation(() => Promise.resolve(resp)) return Users.all().then(data => expect(data).toEqual(users)); });
しかしこのとき、Typescriptを使っている場合、axios.get.mockResolvedValue
の箇所で型チェックエラーになるのでこれを修正したい
以下の記事が参考になった
結論、jest.Mockのジェネリックでモック化したいモジュールを渡し、新しい変数を作成するとよいことがわかった
const mockedUseFooContext = useFooContext as jest.Mock<FooContext>;