I have a project configured as follows:
I'm able to write and run tests for simple JavaScript functions, but when I try doing the same for my components, I get the following error:
src/build/PartSelector.test.js [ src/build/PartSelector.test.js ]
Error: Failed to parse source for import analysis because the content contains invalid JS syntax. Install @vitejs/plugin-vue to handle .vue files.
❯ formatError node_modules/vite/dist/node/chunks/dep-bb8a8339.js:44062:46
❯ TransformContext.error node_modules/vite/dist/node/chunks/dep-bb8a8339.js:44058:19
❯ TransformContext.transform node_modules/vite/dist/node/chunks/dep-bb8a8339.js:41784:22
❯ Object.transform node_modules/vite/dist/node/chunks/dep-bb8a8339.js:44352:30
❯ loadAndTransform node_modules/vite/dist/node/chunks/dep-bb8a8339.js:55026:29
I tried installing the plugin mentioned in the error message via npm install "@vitejs/plugin-vue"
(without doing anything else), but that did not resolve the error.
Is there a way to resolve this error without having to switch over to Vite? Perhaps there's some additional config required after installing vite-plugin-vue that I don't know about?
Also, here is my vitest.config.ts
, if that helps:
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
globals: true,
},
});
I figured it out. Installing the plugin is not enough; it also needs to be included in defineConfig()
inside your config (which in my case is vitest.config.ts).
Solution: run npm install "@vitejs/plugin-vue"
, and then edit vitest.config.ts to include the plugin (see below).
import { defineConfig } from "vitest/config";
import vue from "@vitejs/plugin-vue"; // Import the plugin here
export default defineConfig({
test: {
environment: "jsdom",
globals: true,
},
plugins: [vue()], // Include it in your array of plugins here
});
Note that I also needed to set my environment
variable inside defineConfig()
. If you don't do this, you'll run into a different type of error later on telling you that "document is not defined". More information on that here.