Closed wildone closed 8 months ago
Thank you I've added that to by beforeAll.
And now new error.
[Vuetify] Could not find defaults instance
It never ends :( Ive looked for a concrete way of loading it but nothing works so far.
Ok thank you, for your help @KaelWD got it working. I used this thread as a guide https://github.com/vuetifyjs/vuetify/issues/13936 as well.
import { describe, it, expect } from "vitest"
import { createVuetify } from "vuetify"
import * as components from "vuetify/components"
import * as directives from "vuetify/directives"
import { mount, shallowMount } from "@vue/test-utils"
import HelloWorld from "@/components/HelloWorld.vue"
describe("HelloWorld", () => {
const vuetify = createVuetify({ components, directives })
it("renders properly", () => {
const wrapper = mount(HelloWorld, {
global: {
plugins: [vuetify],
},
props: { title: "Hello Vitest" },
})
expect(wrapper.text()).toContain("Hello Vitest")
})
})
So the lesson is to declare vuetify in all your tests and use it to mount to the component.
@wildone I tried your code and it's not working...
FAIL src/components/tests/HelloWorld.spec.js [ src/components/tests/HelloWorld.spec.js ] ReferenceError: CSS is not defined
Did I miss something? I have a repo to reproduce this issue: https://github.com/mpont91/vue3-vuetify-tests
If you can help me with a PR or anything I would appreciate. Thank you
I'm still trying to solve this problem.
Created vitest.config.js
:
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
setupFiles: 'vuetify.config.js'
},
})
Created vuetify.config.js
:
global.CSS = { supports: () => false };
And now the test is failing with this error:
TypeError: Unknown file extension ".css" for vue3-vuetify-tests/node_modules/vuetify/lib/components/VCode/VCode.css
You can reproduce the problem with my repo: https://github.com/mpont91/vue3-vuetify-tests
I don't know how, after much searching and clicking, I got to here and lo and behold this example works! Hallelujah and thankyou to @wildone https://github.com/governance-foundation/template-electron-vuex-vuetify
I don't know how, after much searching and clicking, I got to here and lo and behold this example works! Hallelujah and thankyou to @wildone https://github.com/governance-foundation/template-electron-vuex-vuetify
Your link shows the following interesting results:
To summarize your findings, which I had success with on multiple levels; the solution is indeed something which solves the OP's problem (CSS not defined) but also instance not defined
meaning Vuetify has not been instantiated as plugin. The latter would be nice to figure out in a global/beforeAll solution (instead on each component mount).
I've commented the plugin and the global approach in my vite config below, may it help anybody in need.
Note: I have not removed anything after Vite setup (left it as untouched as possible), but of course this might include my setup choices like the optional vueJsx plugin.
Note2: curious to understand the impact of the addition of ".css" to the resolve:extensions
section.
import vueJsx from "@vitejs/plugin-vue-jsx";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vuetify from "@vuetify/vite-plugin";
import { fileURLToPath, URL } from "url";
// https://github.com/governance-foundation/template-electron-vuex-vuetify/blob/master/vite.config.ts
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
// Custom plugin entry
{
name: "vitest-plugin-beforeall",
config: () => ({
test: { setupFiles: ["./vitest/beforeAll.ts"] },
}),
},
vue({
// Allows for deconstructing props etc
reactivityTransform: true,
}),
vueJsx(),
// https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vite-plugin
vuetify({
autoImport: true,
}),
],
define: { "process.env": {} },
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
// '@': path.resolve(__dirname, 'src'),
},
extensions: [
".js",
".json",
".jsx",
".mjs",
".ts",
".tsx",
".vue",
".css",
".scss",
],
},
// Global setup functionality
test: {
globals: true,
globalSetup: ["./vitest/setup.ts"],
environment: "jsdom",
deps: {
inline: ["vuetify"],
},
},
/* remove the need to specify .vue files https://vitejs.dev/config/#resolve-extensions
resolve: {
extensions: [
'.js',
'.json',
'.jsx',
'.mjs',
'.ts',
'.tsx',
'.vue',
]
},
*/
});
beforeAll.ts:
import { beforeAll } from "vitest";
(global as any).CSS = { supports: () => false };
beforeAll(() => {
console.log("beforeAll");
global.CSS = {
supports: (str: string) => false,
escape: (str: string) => str,
};
console.log("CSS.support:" + CSS.supports("selector(:focus-visible)"));
});
setup.ts:
export async function setup() {
// global.CSS = {
// supports: (str: string) => false,
// escape: (str: string) => str,
// };
console.log("vitest globalSetup2.");
// console.log("CSS.support:" + CSS.supports("selector(:focus-visible)"));
}
export async function teardown() {
console.log("vitest globalTeardown");
}
Not sure about
define: { "process.env": {} },
in the config. That seems to break the ability to reference VITE_....
environment variables on the client via import.meta.env
same issue with vitest Unknown file extension ".css" for vuetify@3.0.0-beta.1_vue@3.2.33/node_modules/vuetify/lib/components/VBtn/VBtn.css
let me know if I can help with testing anything
here’s a stackblitz for a better understanding of the bug : https://stackblitz.com/edit/vitejs-vite-e8jeuj (with npm run test
)
I'm still stuck on my last reply. When you create a project with default vue3 (with tests) and add the vuetify the first error you encounter when you run the tests is:
ReferenceError: CSS is not defined
To solve this you add:
global.CSS = { supports: () => false };
Then you encounter this another error:
TypeError: Unknown file extension ".css" for vue3-vuetify-tests/node_modules/vuetify/lib/components/VCode/VCode.css
And I'm stuck here, don't know how to solve this. Don't understand the other people who commented on this issue how to solve it.
I finally managed to pass the tests. The last step is add this on vite.config.js
test: {
setupFiles: "vuetify.config.js",
deps: {
inline: ["vuetify"],
},
globals: true,
}
And vuetify.config.js
has the css support false:
global.CSS = { supports: () => false };
I leave my repo reproducing the problem and the last commit solving it, so it can help someone. https://github.com/mpont91/vue3-vuetify-tests
Using Typescript there are some different configuration to put in the settings, the following errors happens here:
Error: [Vuetify] Could not find defaults instance
❯ Module.useDefaults node_modules/vuetify/src/composables/defaults.ts:25:23`
and:
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Unhandled Error ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Error: ENOENT: no such file or directory, open 'xxxxx/dashboard-vue3/node_modules/vuetify/src/composables/defaults.ts'
❯ Object.openSync node:fs:585:3
❯ readFileSync node:fs:453:35
❯ xxxxx/dashboard-vue3/node_modules/vitest/dist/chunk-vite-node-externalize.42b0363f.js:10080:26
❯ printStack xxxxx/dashboard-vue3/node_modules/vitest/dist/chunk-vite-node-externalize.42b0363f.js:10165:32
❯ printError xxxxx/dashboard-vue3/node_modules/vitest/dist/chunk-vite-node-externalize.42b0363f.js:10078:3
❯ processTicksAndRejections node:internal/process/task_queues:96:5
❯ async DefaultReporter.printTaskErrorsxxxxx/dashboard-vue3/node_modules/vitest/dist/chunk-vite-node-externalize.42b0363f.js:8663:7
❯ async DefaultReporter.reportSummary xxxxx/dashboard-vue3/node_modules/vitest/dist/chunk-vite-node-externalize.42b0363f.js:8609:7
❯ async DefaultReporter.onFinished xxxxx/dashboard-vue3/node_modules/vitest/dist/chunk-vite-node-externalize.42b0363f.js:8500:5
❯ async DefaultReporter.onFinishedxxxxx/dashboard-vue3/node_modules/vitest/dist/chunk-vite-node-externalize.42b0363f.js:9290:5
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
Serialized Error: {
"code": "ENOENT",
"errno": -2,
"path": "/xxxxx/dashboard-vue3/node_modules/vuetify/src/composables/defaults.ts",
"syscall": "open",
}
I finally got it working as follows:
// vite.config.js
export default defineConfig(() => {
return {
test: {
environment: 'jsdom',
setupFiles: ['./test/setupVuetify.js', './test/setupPlugins.js'],
deps: {
inline: ['vuetify'],
},
},
};
});
// test/setupVuetify.js
global.CSS = { supports: () => false };
// test/setupPlugins.js
import { config } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { createVuetify } from 'vuetify';
config.global.plugins = [createI18n(), createVuetify()];
I have been struggling with this issue All of the above solution is for Vite. Can someone help me with Vue cli configuration for this issue. I am using cypress for e2e @KaelWD @gkubisa would appreciate your help.
Cypress uses a real browser so shouldn't have this problem.
I created a repository solving this use case:
https://github.com/AntonyRafael/vuetify3beta-vite-ts-basic-tests
@KaelWD when I am running yarn test:unit
I am seeing below error saying CSS not defined
. I am not using Vite but Vue cli
Cypress uses a real browser so shouldn't have this problem.
Sorry for the confusion but the issue was when running unit test
Yeah that's Mocha.
Yeah that's Mocha.
What do you suggest ?
I don't know you'll have to read the mocha documentation to figure out a similar config.
For some reason this is still happening on vuetify@3.0.0-beta.10
while using vitest@0.23.1
.
P.S. Curious why it's mentioning node_modules/src
when there is no src
in the compiled vuetify
... 🤷
TypeError: CSS.supports is not a function
❯ node_modules/vuetify/src/util/globals.ts:4:86
What is typeof CSS
?
there is no src
It's probably using sourcemaps
Logging typeof CSS
in the vitest
setup file results in object
, while checking for typeof CSS.supports
results in undefined
. If I add back the global.CSS = {supports: () => false};
workaround then it works again; however, removing it (as indicated in above fix) causes the same errors to return.
Update:
Was able to verify that node_modules/vuetify/dist/vuetify.js
does contain the above fix:
const SUPPORTS_FOCUS_VISIBLE = IN_BROWSER && typeof CSS !== 'undefined' && CSS.supports('selector(:focus-visible)');
I wonder if there is any relation to https://github.com/jsdom/jsdom/issues/2026, which indicates that some DOM libraries (jsdom
in that case) do not support the supports
property specifically? While I am using happy-dom
environment (and not jsdom
), I wonder if it might be something similar? Should the check be updated to also check that the CSS.supports
function exists (rather than just CSS
object itself)?
Update:
It does appear that happy-dom
has added support; however, not sure about versions (https://github.com/capricorn86/happy-dom/issues/352)
Update 2
Cannot get this to work by patching the dist
builds to also check whether CSS.supports
is not undefined. Have tried updating the vuetify.js
, vuetify.min.js
, and vuetify.esm.js
without any luck of even getting a log statement to fire (which means I'm doing something wrong clearly 🤦).
I use vue-test-utils with jest 27 and TS 4.5
I did a simple test
import { createVuetify } from 'vuetify'
import * as components from 'vuetify/components'
import * as directives from 'vuetify/directives'
describe('TodoList.vue', () => {
const vuetify = createVuetify({ components, directives })
...
const wrapper = shallowMount(TodoList, {
global: {
plugins: [pinia, vuetify]
}
})
But I got this error:
C:\Users\DanielRangel\Desktop\Test\test-ts-jest\test-ts-jest\node_modules\vuetify\lib\framework.mjs:2 import { createDefaults, DefaultsSymbol } from "./composables/defaults.mjs"; ^^^^^^
SyntaxError: Cannot use import statement outside a module
@rangeldor I ended up having to use --experimental-vm-modules to fix that.
node --experimental-vm-modules $(yarn bin jest)
@jssuttles I use vue-cli-service test:unit, npm, jest, ts, and vue-test-utils. This command didn't work for me. Can you help me please?
@rangeldor I'm not familiar with how you might fix that with vue-cli-service test:unit. But perhaps try something like NODE_OPTIONS=--experimental-vm-modules vue-cli-service test:unit
I got this error:
NODE_OPTIONS=--experimental-vm-modules: The term 'NODE_OPTIONS=--experimental-vm-modules' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
@rangeldor you can't set ENV variables like that when using Windows, might want to look into cross-env
or run the command through a package manager like pnpm/yarn berry which supports it out of the box.
example:
cross-env NODE_OPTIONS=--experimental-vm-modules vue-cli-service test:unit
@DRoet, Thank you. I installed cross-env and the command works fine.
But I got this new error:
Must use import to load ES Module: C:\Users\DanielRangel\Desktop\Test\test-ts-jest\test-ts-jest\node_modules\vuetify\lib\framework.mjs
@rangeldor I recently tracked my way through my application again and I removed that --experimental-vm-modules
.
I recommend adding a babel.config.js file with the following:
module.exports = {
presets: ['@babel/preset-env'],
};
And install @babel/preset-env. Hopefully, that helps you as well.
Thank you @jssuttles , but I got the same problem.
SyntaxError: Cannot use import statement outside a module
hmm... I'm going to have to beg off of this soon. But here are some things that I used.
package versions installed with yarn, but can be installed with npm
"vue": "^3.2.39",
"vuetify": "3.0.0-beta.11",
"@babel/core": "^7.19.1",
"@types/webpack-env": "^1.18.0",
"@babel/preset-env": "^7.19.1",
"jest": "29",
"jest-environment-jsdom": "^29.0.3",
"jest-transform-stub": "^2.0.0",
"ts-jest": "29",
"typescript": "^4.8.3",
"@vue/vue3-jest": "29",
"@vue/test-utils": "^2.0.2",
"babel-jest": "29",
jest.config.ts
import type { Config } from 'jest';
import { pathsToModuleNameMapper } from 'ts-jest';
import { compilerOptions } from './tsconfig.json';
const config: Config = {
transform: {
// process *.vue files with vue-jest
'^.+\\.vue$': '@vue/vue3-jest',
'.+\\.(css|styl|less|sass|scss|jpg|jpeg|png|svg|gif|eot|otf|webp|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga|avif)$':
'jest-transform-stub',
'^.+\\.(js|jsx|mjs)$': 'babel-jest',
'^.+\\.ts': 'ts-jest',
},
setupFiles: ['./tests/setupFile.ts'],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' }),
testEnvironment: 'jsdom',
testEnvironmentOptions: {
customExportConditions: ['node', 'node-addons'],
},
transformIgnorePatterns: ['/node_modules/(?!(vuetify)/)'],
};
export default config;
babel.config.js
module.exports = {
presets: ['@babel/preset-env'],
};
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "esnext",
"strict": false,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"useDefineForClassFields": true,
"sourceMap": true,
"baseUrl": ".",
"resolveJsonModule": true,
"types": ["webpack-env", "jest"],
"paths": {
"@/*": ["src/*"]
},
"lib": ["esnext", "dom", "dom.iterable", "scripthost"]
},
"include": ["**/*.ts", "src/**/*.vue"],
"exclude": ["node_modules"]
}
setupFile.ts
class ResizeObserverStub {
observe() {
// do nothing
}
unobserve() {
// do nothing
}
disconnect() {
// do nothing
}
}
window.ResizeObserver = window.ResizeObserver || ResizeObserverStub;
Why is this closed if the issue is not resolved? 🤔 Still no documentation on unit testing...
Thank you @mpont91 for sharing your setup! Works like a charme!
@everyone: you'll find a working setup in this repo --> https://github.com/mpont91/vue3-vuetify-tests
@jssuttles Thank you! Your examples finally got me on the path to a config that works for a Vue CLI project. The only thing I had to change really was to add explicit module name mapping because otherwise it refused to import anything but the top level package in test files:
"moduleNameMapper": {
"^@/(.*)$": "<rootDir>/src/$1",
"^vuetify/components$": "<rootDir>/node_modules/vuetify/lib/components/index.mjs",
"^vuetify/directives$": "<rootDir>/node_modules/vuetify/lib/directives/index.mjs"
}
Having same issue when using vuetify with jest. Any solution?
Running a unit test in vitest, I was getting
TypeError: Unknown file extension ".css" for <project-path>/node_modules/vuetify/lib/components/VApp/VApp.css
I added to vite.config.js
:
export default defineConfig({
...
test: {
environment: 'jsdom',
reporter: 'verbose',
+ deps: {
+ inline ['vuetify']
+ }
}
And now I get
Error: [Vuetify] Could not find defaults instance
❯ Module.useDefaults node_modules/vuetify/src/composables/defaults.ts:38:9
❯ setup node_modules/vuetify/src/util/defineComponent.tsx:65:42
❯ callWithErrorHandling node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:171:22
❯ setupStatefulComponent node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:7194:29
...
None of the suggestions in this thread have fixed this error.
I'm using
vue 3.2.46
vuetify 3.1.11
vite 4.1.4
vite-plugin-vuetify 1.0.2
vitest 0.29.7
@vitejs/plugin-vue 4.0.0
@vue/test-utils 2.0.0
@vue/compat 3.1.0
jsdom 21.1.1
The only way I have found to fix this is to stop using vite-plugin-vuetify
apparently? This means no automatic treeshaking ☹️
The plot thickens. Instead of removing vite-plugin-vuetify
, for some reason I decided to try removing @vue/compat
as I was already using MODE: 3
and had eliminated all the compatibility options by this point. I then got a different error
ReferenceError: ResizeObserver is not defined
❯ Module.layoutSizes node_modules/vuetify/src/composables/resizeObserver.ts:21:20
❯ Module.createLayout node_modules/vuetify/src/composables/layout.ts:188:25
❯ Object.target node_modules/vuetify/src/components/VApp/VApp.tsx:29:11
❯ setup node_modules/vuetify/src/util/defineComponent.tsx:130:41
❯ callWithErrorHandling node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:171:22
❯ setupStatefulComponent node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:7194:29
...
I think this is https://github.com/jsdom/jsdom/issues/3368
Solution is as mentioned in a comment above:
// tests/unit/setup.js
class ResizeObserverStub {
observe () { }
unobserve () { }
disconnect () { }
}
window.ResizeObserver ??= ResizeObserverStub
// vite.config.js
export default defineConfig({
...
test: {
environment: 'jsdom',
reporter: 'verbose',
+ deps: {
+ inline ['vuetify']
+ },
+ setupFiles: ['./tests/unit/setup.js'],
}
Now my tests are working 😮💨
And now the test is failing with this error:
TypeError: Unknown file extension ".css" for vue3-vuetify-tests/node_modules/vuetify/lib/components/VCode/VCode.css
What fixed this error for me was adding the following code into my vitest.config.js
deps: { inline ['vuetify'] },
This SO answer has a minimalist working example straight out of the project scaffolding
foud this in the docs for unit testing
I would prefer a Testing page enabled in the site with placeholder TODOs and links to GitHub, to ambiguity and a witch hunt to figure anything out.
As for the page @subinznz linked. Even if it is not 100% ready or correct I think it will solve 90% of people's problems. It would have saved me several hours. It appears there has been significant effort already put into it. So can we publish it please?
For anyone struggling with TypeError: Unknown file extension ".css" for xxx/node_modules/vuetify/lib/components/VCode/VCode.css
error and has vitest
version 0.31.2:
There is a bug in vitest
that makes deps.inline
being ignored, thus causing this error.
Upgrading to 0.31.4 fixed it for me (configuration described in above comments is still required ofc)
It took me a while to figure this out so I'm sharing it here :D reference: https://github.com/vitest-dev/vitest/issues/3472
If you are seeing errors like so: [Vue warn]: Failed to resolve component
OR
Like so: [Vue warn]: Failed to resolve component: v-container
If you are app is testing without errors but it is not behaving properly on dev
or build
take a look here.
Environment
Vuetify Version: 3.0.0-alpha.12 Vue Version: 3.2.13 Browsers: Chrome 98.0.4758.102 OS: Windows 10
Steps to reproduce
git clone https://github.com/governance-foundation/template-electron-vuex-vuetify.git cd template-electron-vuex-vuetify npm install npm run test:unit
Expected Behavior
unit test pass
Actual Behavior
Reproduction Link
https://github.com/governance-foundation/template-electron-vuex-vuetify
Other comments
I have globals set, and setup files mocking global.CSS.