Masahiro Okubo

axios.createのテスト

axios.createのテスト

参考記事をベースに作成しました


jest.mock('../../mocks/axios/adapter', () => jest.fn());

const axiosMockAdapter = (mock as unknown) as
  jest.Mock<ReturnType<AxiosAdapter>, Parameters<AxiosAdapter>>;

describe('users API', () => {
  beforeEach(() => axiosMockAdapter.mockClear());
  afterEach(() => jest.restoreAllMocks());
  it('success findAll', async () => {
    const users = [
      { id: 1, name: 'tset' } as User,
      { id: 2, name: 'tset' } as User,
      { id: 3, name: 'tset' } as User,
    ];
    const resp: AxiosResponse<User[]> = { data: users } as AxiosResponse;
    axiosMockAdapter.mockResolvedValueOnce(resp);
    const result = await findAll();
    // const callArgs = axiosMockAdapter.mock.calls[0];
    expect(result).toEqual(resp.data);
  });
});

参考記事

Jestでデフォルト値設定済みのaxiosインスタンスに対するMockテスト


関連記事

copyright© 2016-2021 Masahiro Okubo