1

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
6
  • Shouldn’t the function Name be $t? Commented Mar 1, 2023 at 17:52
  • Yes, but if it were options api, I access t via vue-i18n composable. And I've tried to declare it as $t in the test, it doesn't work either. Commented Mar 1, 2023 at 18:15
  • If you work with composables, mocks will not work like this. You need to mock the imports Commented Mar 1, 2023 at 18:52
  • How can I do this or where can I read about this? I don't see anything in vue testing library docs. Commented Mar 1, 2023 at 18:57
  • 1
    Okay, I've mocked it with vi.mock, but how can I pass it to component now? Commented Mar 1, 2023 at 21:53

1 Answer 1

-2
vi.mock("vue-i18n", () => ({
  useI18n: () => ({ t: (key: string) => key }),
}));
Sign up to request clarification or add additional context in comments.

1 Comment

Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.