vitest hooks for JSDOM location mock
npm install vitest-location-mock![]()
(Fork of jest-location-mock, but for vitest)
Vitest hooks for JSDOM location mock



Ever gotten the following error when using window.location.assign, reload, or replace?
``txt`
Error: Not implemented: navigation (except hash changes)
This Vitest plugin fixes this error and mocks out window.location so it behaves similar to how does in the browser.
- Mock and control window.location
- Relative URL support
- TypeScript extend expect support
`bash`
npm install --save-dev vitest-location-mock
To start using Vitest Location Mock, extend expect and add hooks by importing the default export in your Vite setup file.
vite.config.js
`js`
export default defineConfig({
setupFiles: [
"./config/vitest-setup.js"
]
});
config/vitest-setup.js
`jswindow.location
// Mock with Vitest spies and extend expect`
import "vitest-location-mock";
#### expect(location).toBeAt(url, [base])
Throws: When the URLs have a different absolute href.
| Parameter | Type | Description |
| --------- | ------------------- | ----------------------------------------------------------------------- |
| location | Location \| URL | Instance of URL to check its href |string
| url | \| URL | Relative or absolute URL |string
| base | \| URL | If the url parameter is relative, an base URL for the URL constructor |
`ts``
it("should call assign with a relative url", () => {
window.location.assign("/relative-url");
expect(window.location).not.toBeAt("/");
expect(window.location).toBeAt("/relative-url");
});
Copyright Evelyn Hathaway, MIT License