Vue.js testing - Renders error message TypeError: $setup.t is not a function

1.4k Views Asked by At

I use Vue.js 3, setup syntax, typescript and vue-i18n. For the testing I use vitest and Vue Testing Library. I try to mock i18n's t function, but looks like component doesn't see it. How can I solve this?

My test:

import { describe, test, expect } from "vitest";
import { render } from "@testing-library/vue";

import TheError from "@/components/TheError.vue";

describe("TheError", () => {
  test("Renders error message", () => {
    const message = "Something went wrong!";
    const t = (msg: string): string => msg;

    const wrapper = render(TheError, {
      props: { message },
      global: {
        mocks: { t },
      },
    });

    const errorMessage = wrapper.getByText(message);
    expect(errorMessage.textContent).toBe(message);
  });
});

The error I'm getting:

src/components/tests/TheError.test.ts > TheError > Renders error message
TypeError: $setup.t is not a function
1

There are 1 best solutions below

1
Explicit On
vi.mock("vue-i18n", () => ({
  useI18n: () => ({ t: (key: string) => key }),
}));