LoginSignup
0
1

More than 3 years have passed since last update.

Jestで同一ファイル内で異なる振る舞いのモックを使用したい場合(axios)

Posted at

初めに

メモ書きようです。
ざっくりと書いていますのでご了承ください。

同一ファイル内で異なる振る舞いのモックを使用したい場合

例えば以下のようなAPIがあったとします。

test.ts
async hoge(): Promise<Hoge> {
    const res = await $axios.$get('/hoge');
}

async fuga(): Promise<Fuga> {
    const res = await $axios.$get('/fuga');
}

異なる振る舞いのモックを作成する場合は以下のように書けます。

test.spec.ts
import { $axios } from '@/store/utils/api.ts';

jest.mock('@/store/utils/api.ts', () => ({
  $axios: {
    $get: jest.fn(),
  }
}));

describe('Test', () => {
  test('hoge', async () => {
    ($axios.$get as jest.Mock).mockImplementation(() =>
      Promise.resolve({
        ~
    }));
  });
  await hoge()
});

describe('Test', () => {
  test('fuga', async () => {
    ($axios.$get as jest.Mock).mockImplementation(() =>
      Promise.resolve({
        ~
    }));
  });
  await fuga()
});


0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1