'How to test logic based on search params?

I have a simple React component that expects a search param like: ?some_param=1.

If some_param is present, the component renders slightly differently. Due to odd circumstances, I cannot use a prop and must use a search param.

I'm struggling to write a basic unit test that confirms the render logic is working when the param is passed. The general structure of my test is like so:

  test('example test', async () => {
    const location = {
      ...window.location,
      search: '?some_param=1',
    };
    Object.defineProperty(window, 'location', {
      writable: true,
      value: location,
    });

  
    render(<SomeComponent />);

    const textThatOnlyRendersIfParam = await screen.findAllByText('someText');
    expect(textThatOnlyRendersIfParam).toHaveLength(3);
  });

Unfortunately <SomeComponent /> is not pulling in ?some_param=1 and does not render the textThatOnlyRendersIfParam text.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source