mock `window.location.pathname` and window.location.search` in vitest unit test in typescript

In order to mock window.location.pathname and window.location.search in a unit test for TypeScript using @testing-library/react, you can use the Object.defineProperty method to define a mock value for these properties.

Here's an example of how you can mock these properties in a unit test:

index.ts
// Import the necessary modules and functions
import { render } from '@testing-library/react';

// Define a mock value for window.location.pathname
const mockPathname = '/mock/pathname';
Object.defineProperty(window, 'location', {
  value: {
    ...window.location,
    pathname: mockPathname,
  },
});

// Define a mock value for window.location.search
const mockSearch = '?mock=query&param=value';
Object.defineProperty(window, 'location', {
  value: {
    ...window.location,
    search: mockSearch,
  },
});

// Now you can write your unit tests
test('Your test case', () => {
  // Your test logic goes here

  // You can access the mocked values of window.location.pathname and window.location.search in your test code
  expect(window.location.pathname).toBe(mockPathname);
  expect(window.location.search).toBe(mockSearch);
});
834 chars
30 lines

In the above example, we use Object.defineProperty to define a mock value for window.location.pathname and window.location.search. We create an object with the same properties as window.location and set the mock values for pathname and search. Then, we assign this object as the value of window.location.

By mocking these properties, you can simulate different values for window.location.pathname and window.location.search in your unit tests and test different scenarios effectively.

It's worth noting that this approach works with TypeScript and can be used with any testing framework that supports the @testing-library/react library.

related categories

gistlibby LogSnag