Skip to content

window.location.pathname contains test metadata when Browser mode is enabled #7424

@bteng22

Description

@bteng22

Describe the bug

My team is trying to migrate our tests from Web Test Runner to Vitest and we have a few tests that are failing due to window.location.pathname. We have Vitest's Browser Mode enabled and noticed it places test metadata onto our path, which I'm assuming is from:

iframe.setAttribute(
'src',
`${url.pathname}__vitest_test__/__test__/${
getBrowserState().sessionId
}/${encodeURIComponent(file)}`,
)
.

Unfortunately, there's cases in our application code that expect window.location.pathname to be specific routes e.g.

    const path = window.location.pathname
    const isHomePagePath = path === '/' || path === '/home'

But our pathname when running our tests results is something similar to: "/__vitest_test__/__test__/2650bfc6-b49a-4c09-868f-44fa8a52c2ae/%2Fpath%2Fto%2Ftest%2Ffile.ts",

Any workarounds or suggestions here since we're not able to mock/redefine window.location? Hoping not to modify our application code and keep this isolated to our tests. Or is Vitest able to implement something similar to what Web Test Runner does? It saves the metadata onto a namespaced variable on the global window.

e.g.
window.__WTR_CONFIG__ = {"testFile":"/name/of/test/file.ts?wtr-session-id=HzIg-c9rnYcBvBOdTLkT4","watch":false,"debug":false,"testFrameworkConfig":{"timeout":10000,"retries":1}}

Reproduction

https://stackblitz.com/edit/vitest-dev-vitest-r7td449n?file=test%2Fone.browser.test.ts

System Info

System:
    OS: Linux 5.0 undefined
    CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 18.20.3 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 10.2.3 - /usr/local/bin/npm
    pnpm: 8.15.6 - /usr/local/bin/pnpm
  npmPackages:
    @vitest/browser: 3.0.4 => 3.0.4 
    playwright: 1.35.0 => 1.35.0 
    vite: 6.0.9 => 6.0.9 
    vitest: 3.0.4 => 3.0.4

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions