Open leopradac opened 2 weeks ago
Hello there, @leopradac! I'm here to help you with any bugs, questions, or contributions. Let's work together to solve the issue you're facing.
To resolve the issue where Vitest fails when the baseURL
is defined in the nuxt.config.ts
file, causing a 404 error for a specific path, you can modify the Vitest configuration to handle the baseURL
correctly.
In the src/environments/vitest/index.ts
file, adjust the setup
function to ensure that the baseURL
is taken into account. Here is a snippet showing how you can modify the configuration:
import { joinURL } from 'ufo';
export default <Environment>{
name: 'nuxt',
transformMode: 'web',
async setup(global, environmentOptions) {
const url = joinURL('http://localhost:3000', environmentOptions?.nuxtRuntimeConfig.app?.baseURL || '/');
const environmentName = environmentOptions.nuxt.domEnvironment as NuxtBuiltinEnvironment;
const environment = environmentMap[environmentName] || environmentMap['happy-dom'];
const { window: win, teardown } = await environment(global, defu(environmentOptions, {
happyDom: { url },
jsdom: { url },
}));
win.__NUXT_VITEST_ENVIRONMENT__ = true;
win.__NUXT__ = {
serverRendered: false,
config: {
public: {},
app: { baseURL: '/' },
...environmentOptions?.nuxtRuntimeConfig,
},
data: {},
state: {},
};
const app = win.document.createElement('div');
app.id = environmentOptions.nuxt.rootId;
win.document.body.appendChild(app);
if (environmentOptions?.nuxt?.mock?.intersectionObserver) {
win.IntersectionObserver = win.IntersectionObserver || class IntersectionObserver {
observe() {}
unobserve() {}
disconnect() {}
};
}
if (environmentOptions?.nuxt?.mock?.indexedDb) {
win.indexedDB = indexedDB;
}
const h3App = createApp();
if (!win.fetch) {
await import('node-fetch-native/polyfill');
win.URLSearchParams = globalThis.URLSearchParams;
}
const localCall = createCall(toNodeListener(h3App));
const localFetch = createLocalFetch(localCall, win.fetch);
const registry = new Set<string>();
win.fetch = (init, options) => {
if (typeof init === 'string') {
const base = init.split('?')[0];
if (registry.has(base) || registry.has(init)) {
init = '/_' + init;
}
}
return localFetch(init.toString(), {
...options,
headers: Array.isArray(options?.headers) ? new Headers(options?.headers) : options?.headers,
});
};
win.$fetch = createFetch({ fetch: win.fetch, Headers: win.Headers });
win.__registry = registry;
win.__app = h3App;
const { keys, originals } = populateGlobal(global, win, {
bindFunctions: true,
});
const timestamp = Date.now();
const routeRulesMatcher = toRouteMatcher(
createRadixRouter({ routes: environmentOptions.nuxtRouteRules || {} }),
);
const matcher = exportMatcher(routeRulesMatcher);
const manifestOutputPath = joinURL(
'/',
environmentOptions?.nuxtRuntimeConfig.app?.buildAssetsDir || '_nuxt',
'builds',
);
const manifestBaseRoutePath = joinURL('/_', manifestOutputPath);
h3App.use(
`${manifestBaseRoutePath}/latest.json`,
defineEventHandler(() => ({
id: 'test',
timestamp,
})),
);
h3App.use(
`${manifestBaseRoutePath}/meta/test.json`,
defineEventHandler(() => ({
id: 'test',
timestamp,
matcher,
prerendered: [],
})),
);
h3App.use(
`${manifestBaseRoutePath}/meta/dev.json`,
defineEventHandler(() => ({
id: 'test',
timestamp,
matcher,
prerendered: [],
})),
);
registry.add(`${manifestOutputPath}/latest.json`);
registry.add(`${manifestOutputPath}/meta/test.json`);
registry.add(`${manifestOutputPath}/meta/dev.json`);
return {
teardown() {
keys.forEach(key => delete global[key]);
originals.forEach((v, k) => (global[k] = v));
teardown();
},
};
},
};
This modification ensures that the baseURL
defined in the nuxt.config.ts
file is correctly handled by Vitest, preventing the 404 error for the specific path [1].
To continue talking to Dosu, mention @dosu.
Environment
Build Modules: -
Reproduction
https://stackblitz.com/edit/github-ichjfp?file=nuxt.config.ts&view=editor
Describe the bug
Quite simple as the title describes, when
app > baseURL
is defined atnuxt.config.ts
vitest starts failing, at least at those tests using the nuxt environment with the// @vitest-environment nuxt
at the beginning of the file.Additional context
Logs shared below are for
"baseURL": "/admin/"
. Also, for those struggling with this, by the time being a workaround would be modifying the "test" script at package.json to:Logs