Skip to content

[Feature Request]: Mock/support import.meta.url #215

@albinekb

Description

@albinekb

Description

My repo/package is ts with type: module.
In a lot of my tests/code, i use import.meta.url to build paths to my fixtures:

const __dirname = fileURLToPath(new URL('.', import.meta.url))
const cleanDomRoot = path.join(__dirname, './fixtures/getPageMeta/')

It seems that when using "extractWith": "evaluation-cjs", __dirname is defined but import.meta is an empty object {}

There are some discussions in #172 (comment) about different ways to extract tests.

This is happening with evaluation-cjs

Describe the solution you'd like

"mock" import.meta.url so it just works ™️

Add a mocked import.meta.url to the esbuild config

Could it be as easy as updating the contextObj proxy in here?

const contextObj = new Proxy(
{
__dirname: path.dirname(filePath),
__filename: path.basename(filePath),
} as any,
{
get(target, prop) {
if (symbols.value.suite.includes(prop as string)) {
return suiteFunction;
} else if (symbols.value.test.includes(prop as string)) {
return testFunction;
} else if (symbols.value.hooks.includes(prop as string)) {
return placeholder();
} else if (prop in target) {
return target[prop]; // top-level `var` defined get set on the contextObj
} else if (prop in globalThis && !replacedGlobals.has(prop as string)) {
// Bug #153: ESBuild will wrap require() calls into __toESM which breaks quite some things
// we want to keep our Proxy placeholder object in all scenarios
// Due to that we provide a special proxy object which will create again placeholder proxies
// on Object.create
// https://github.com/evanw/esbuild/blob/d34e79e2a998c21bb71d57b92b0017ca11756912/internal/runtime/runtime.go#L231-L242
if (prop === 'Object') {
return objectPlaceholder((globalThis as any)[prop]);
}
return (globalThis as any)[prop];
} else {
return placeholder();
}
},
},
);

Describe alternatives you've considered

Works if I lazily use import.meta.url:

function getHtmlPath() {
  const __dirname = fileURLToPath(new URL('.', import.meta.url))
  const htmlPath = path.join(
    __dirname,
    './fixtures/admin/admin-dropdown.html',
  )
  return htmlPath
}

Another option could be to rewrite all my tests to use some helper fn to get the fixtures path, but would still be nice to mock the url to make it more seamless!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions