nuxt / nuxt/test-utils

How to mock custom imports while using mountSuspended to test

Open
#935 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug pending triage vitest-environment
Dominant language
TypeScript
Stars
437
Forks
120
Avg merge
22h 52m
Merged PRs (30d)
23

Description

Environment

"dependencies": {
"nuxt": "3.12.4",
"vue": "latest"
},
"devDependencies": {
"@nuxt/test-utils": "3.14.1",
"@vue/test-utils": "2.4.6",
"happy-dom": "14.12.3",
"jest-image-snapshot": "6.4.0",
"playwright-core": "1.46.0",
"vitest": "2.0.5"
}

Reproduction

Default.vue

<template>
  <NuxtPage />
</template>
<script setup lang="ts"></script>

App.vue

<template>
  <div>Message: {{ getMessage("Hello World") }}</div>
</template>
<script setup lang="ts">
import { getMessage } from "@/service/message-service";

App.test.ts

import { it, expect, vi } from "vitest";
import { mountSuspended } from "@nuxt/test-utils/runtime";
import App from "../../layouts/default.vue";

vi.mock("@/service/message-service", () => {
  return {
    getMessage: () => "hello from mock!!",
  };
});


it("nuxt unit testing", async () => {
  const component = await mountSuspended(App, { route: "/" });
  expect(component.html()).toMatchInlineSnapshot(
    `"<div>Message: hello Hello World</div>"`
  );
});

message-service.ts

export function getMessage(message: string): string {
  console.log("FROM ACTUAL");
  return `hell ${message}`;
}
Describe the bug

I was expecting vitest vi.mock should be able to mock imports to provide custom/mock implementation, however it seems that vi.mock is not working in the context of nuxt test?

If so, how are we suppose to create unit tests and/or E2E using nuxt/test-utils package and be able to provide flexible mocking mechanism?

Additional context

No response

Logs

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the reproduction in App.test.ts with mountSuspended from @nuxt/test-utils/runtime, then inspect how the runtime entry point handles Vitest vi.mock and the import in message-service.ts. Compare the rendered result with the expected mock output; done means the supported mocking behavior is fixed or clearly documented for this reproduction.

Written by the indexing model from the issue text.

Assessment

Tech stack
nuxtjs, typescript
Domain
frontend, testing
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.