search

Home  >  Q&A  >  body text

How to write component unit tests using vitest in Nuxt 3?

I'm trying to migrate from Vue 3 to Nuxt 3. I have written unit tests for my components using vitest and these tests are working fine in my Vue application but the same tests in Nuxt application are giving the following error :

Error: The source cannot be parsed for import analysis because the content contains invalid JS syntax.

Install @vitejs/plugin-vue to handle .vue files.

I have installed

@vitejs/plugin-vue as a development dependency but nothing happens.

Here is an example of my test file:

import { describe, it, expect } from "vitest";

import { mount } from "@vue/test-utils";
import AtomsButton from "./AtomsButton.vue";

describe("AtomsButton", () => {
  it("button renders properly", () => {
    const wrapper = mount(AtomsButton, { slots: { default: "Button" } });
    expect(wrapper.html()).toContain("Button");
  });
});

This is my

package.json file:

{
  "private": true,
  "scripts": {
    "build": "nuxt build",
    "dev": "nuxt dev",
    "generate": "nuxt generate",
    "preview": "nuxt preview",
    "test:unit": "vitest --environment jsdom"
  },
  "devDependencies": {
    "@nuxt/test-utils-edge": "^3.0.0-rc.3-27571095.9379606",
    "@vitejs/plugin-vue": "^2.3.3",
    "@vue/test-utils": "^2.0.0",
    "jsdom": "^19.0.0",
    "nuxt": "3.0.0-rc.3",
    "vitest": "^0.13.1"
  }
}

I do not know what I did wrong. Any help would be greatly appreciated.

Here is the copy link

P粉953231781P粉953231781272 days ago583

reply all(1)I'll reply

  • P粉038161873

    P粉0381618732024-03-26 12:09:32

    I also ran into this issue and was able to make it work by just using a custom Vite profile from Vitest.

    package.json File:

    {
      "scripts": {
        "build": "nuxt build",
        "dev": "nuxt dev",
        "generate": "nuxt generate",
        "test:unit": "vitest --config ./vitest.config.js",
        "preview": "nuxt preview"
      },
      "devDependencies": {
        "@nuxtjs/tailwindcss": "^5.1.2",
        "@vitejs/plugin-vue": "^2.3.3",
        "@vue/test-utils": "^2.0.0",
        "jsdom": "^19.0.0",
        "nuxt": "3.0.0-rc.4",
        "vitest": "^0.14.2"
      }
    }

    vitest.config.js File:

    import vue from '@vitejs/plugin-vue';
    
    export default {
      plugins: [vue()],
      test: {
        globals: true,
        environment: 'jsdom',
      },
    }

    reply
    0
  • Cancelreply