カクカクしかじか

技術的なアレコレ

Nuxt.jsでComposition API利用時にcontextの中身をjestでmockしたい時の解決法

結論

📝 shallowMount(mount) のプロパティの mocks の中に $nuxt -> context -> mockしたいコンテキスト の順番で定義すれば良い

describe("Component", () => {
  let localVue: typeof Vue;
  let wrapper: ReturnType<typeof shallowMount<Vue>>;

  beforeEach(() => {
    localVue = createLocalVue();
    localVue.use(Vuex);
    wrapper = shallowMount(Component, {
      localVue,
      propsData: {
        currentUser: createCurrentUser(),
      },
      mocks: {
        $nuxt: {
          context: {
            $AppUtil: { # MEMO: contextの中身はplugins配下に定義し、nuxt.config.jsで読み込んだプロパティたち
              isDevelopment: jest.fn(() => true),
            },
          },
        },
      },
    });
  });

補足

📝 Composition APIを使っていない場合は、mocks 直下に定義でOK 👌

const wrapper = shallowMount(Component, {
  mocks: {
    $hoge: hoge
  }
})