Vue testing a component that uses composables

189 Views Asked by At

I'm using vitest to put together unit tests for components in my web app. I've run into an issue where my component uses a composable to get some state variables, and the composable is undefined when I run the test. Here is how the component uses the company composable:

const coreValueOptions = company()?.core_values.map((value: any) =>
  value.label.replace(/#/gi, ""),
);

I've tried mocking the composable here in the test, and this doesn't quite work, it only makes it so if I call the composable directly it returns 100, but if the composable is called through the CoreModalFilters component, it doesn't work.

import { describe, test, expect } from "vitest";
import { shallowMount } from "@vue/test-utils";
import CoreModalFilters from "../../components/core/modal/CoreModalFilters.vue";
import { company } from "../../composables/store";

const mock = vi.hoisted(() => {
    return {
      company: vi.fn(),
    };
  });

  vi.mock("../../composables/store", () => ({
    company: mock.company,
  }));
  vi.mocked(company).mockReturnValue(100);

describe("CoreModalFilters and all variants render correctly", async () => {

  test("correctly renders CoreModalFilter with default props", async () => {
    const wrapper = shallowMount(CoreModalFilters, {
      propsData: {
        showModal: true,
      },
    });
    // const html = wrapper.html();
  });
});

and here are the composables

export const company = () => {
  return useStore().company;
};

error stack

 FAIL  tests/components/CoreModalFilters.test.js > CoreModalFilters and all variants render correctly > correctly renders CoreModalFilter with default props
ReferenceError: company is not defined
 ❯ setup components/core/modal/CoreModalFilters.vue:49:26
     47|   : ["Office Location", "Team", "Core Value"];
     48| 
     49| const coreValueOptions = company()?.core_values.map((value: any) =>
       |                          ^
     50|   value.label.replace(/#/gi, ""),
     51| );
 ❯ callWithErrorHandling node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:156:18
 ❯ setupStatefulComponent node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:7190:25
 ❯ setupComponent node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:7151:36
 ❯ mountComponent node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5555:7
 ❯ processComponent node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5521:9
 ❯ patch node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5007:11
 ❯ ReactiveEffect.componentUpdateFn [as fn] node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5664:11
 ❯ ReactiveEffect.run node_modules/@vue/reactivity/dist/reactivity.cjs.js:182:19
 ❯ instance.update node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5770:51
0

There are 0 best solutions below