Skip to content

Instantly share code, notes, and snippets.

@jericbas
Created June 21, 2019 05:05
Show Gist options
  • Save jericbas/11cbce3a1481b00492a42e416d92752a to your computer and use it in GitHub Desktop.
Save jericbas/11cbce3a1481b00492a42e416d92752a to your computer and use it in GitHub Desktop.
Mock `window.location.search`
it('mocks search', () => {
delete window.location;
window.location = { search: '?query=phone' };
expect(window.location.search).toEqual('?query=phone');
});
@tatethurston
Copy link

👍

@justinfarrelldev
Copy link

Absolute lifesaver

@moshfeu
Copy link

moshfeu commented Jun 29, 2023

Thanks.
Not that easy to make it work with typescript 😅

@zacharytyhacz
Copy link

Not working with React Testing Library

        window.location.search = '?slug=test&token=resetToken'
        const { findByText } = render(<Component />)

Then in my <Component, I console.log(window.location.search) and it shows up undefined


  console.log
    search query:

@zacharytyhacz
Copy link

Mock window.location.search in a TypeScript React project using React Testing Library and Jest, you can follow these steps:

  1. Install the necessary packages if you haven't already:

    npm install @testing-library/react @testing-library/jest-dom jest @types/jest --save-dev
  2. Create a setup file for Jest to configure the global window.location.search mock. In the root of your project, create a jest.setup.js file (or jest.setup.ts if you are using TypeScript).

  3. In the jest.setup.js (or jest.setup.ts) file, define the mock for window.location.search:

    // jest.setup.js (or jest.setup.ts)
    Object.defineProperty(window, 'location', {
      writable: true,
      value: { search: '' },
    });

    This code snippet sets up a mock for window.location with an initial value for the search property as an empty string. This allows you to override this value during your tests.

  4. Update your Jest configuration in the package.json (or jest.config.js for a separate configuration file) to include the setup file:

    // package.json
    {
      "jest": {
        "setupFilesAfterEnv": ["<rootDir>/jest.setup.js"]
      }
    }

    This tells Jest to execute the setup file before running the tests.

  5. Now, in your test files, you can use React Testing Library and Jest as usual. To mock the window.location.search for a specific test, you can set the desired value before rendering your component:

    // YourComponent.test.tsx (or .test.ts, .spec.ts, etc.)
    import React from 'react';
    import { render } from '@testing-library/react';
    import YourComponent from './YourComponent';
    
    describe('YourComponent', () => {
      it('should render with a custom search query', () => {
        // Set the desired value for window.location.search
        Object.defineProperty(window, 'location', {
          writable: true,
          value: { search: '?query=test' },
        });
    
        // Now, render your component
        const { getByText } = render(<YourComponent />);
    
        // Add your assertions
        const element = getByText('Your Component Content');
        expect(element).toBeInTheDocument();
      });
    });

    In this example, the window.location.search is mocked with a custom query string (?query=test) before rendering the YourComponent.

By following these steps, you should be able to mock window.location.search in your TypeScript React project using React Testing Library and Jest. Remember to customize the value of window.location.search according to your test scenarios.

@jericbas
Copy link
Author

jericbas commented Nov 3, 2023

Mock window.location.search in a TypeScript React project using React Testing Library and Jest, you can follow these steps:

  1. Install the necessary packages if you haven't already:

    npm install @testing-library/react @testing-library/jest-dom jest @types/jest --save-dev
  2. Create a setup file for Jest to configure the global window.location.search mock. In the root of your project, create a jest.setup.js file (or jest.setup.ts if you are using TypeScript).

  3. In the jest.setup.js (or jest.setup.ts) file, define the mock for window.location.search:

    // jest.setup.js (or jest.setup.ts)
    Object.defineProperty(window, 'location', {
      writable: true,
      value: { search: '' },
    });

    This code snippet sets up a mock for window.location with an initial value for the search property as an empty string. This allows you to override this value during your tests.

  4. Update your Jest configuration in the package.json (or jest.config.js for a separate configuration file) to include the setup file:

    // package.json
    {
      "jest": {
        "setupFilesAfterEnv": ["<rootDir>/jest.setup.js"]
      }
    }

    This tells Jest to execute the setup file before running the tests.

  5. Now, in your test files, you can use React Testing Library and Jest as usual. To mock the window.location.search for a specific test, you can set the desired value before rendering your component:

    // YourComponent.test.tsx (or .test.ts, .spec.ts, etc.)
    import React from 'react';
    import { render } from '@testing-library/react';
    import YourComponent from './YourComponent';
    
    describe('YourComponent', () => {
      it('should render with a custom search query', () => {
        // Set the desired value for window.location.search
        Object.defineProperty(window, 'location', {
          writable: true,
          value: { search: '?query=test' },
        });
    
        // Now, render your component
        const { getByText } = render(<YourComponent />);
    
        // Add your assertions
        const element = getByText('Your Component Content');
        expect(element).toBeInTheDocument();
      });
    });

    In this example, the window.location.search is mocked with a custom query string (?query=test) before rendering the YourComponent.

By following these steps, you should be able to mock window.location.search in your TypeScript React project using React Testing Library and Jest. Remember to customize the value of window.location.search according to your test scenarios.

thanks chatGPT? 😂🤣

@MikolajBryksa
Copy link

Thanks. Not that easy to make it work with typescript 😅

Mock window.location.search in TypeScript:

global.window = Object.create(window);
Object.defineProperty(window, 'location', {
  value: {
    search: '?query=phone',
  },
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment