'How can I test weather I'm being navigated to the correct url or not using jest for react?

The line to test is

 <ButtonCTA text="Facebook" type="submit" onClick={() => {
                window.open('https://www.facebook.com/sharer/sharer.php?u=https://www.legalzoom.com', '', 'status=1,width=575,height=520'); }}
              className="btn btn-action tw-block tw-py-0 tw-px-3 tw-flex tw-items-center
                tw-flex-row-reverse tw-text-16 tw-leading-6 tw-tracking-[-0.2px] tw-w-[192px]
                tw-justify-center tw-mr-3" testid='Facebook'>
            </ButtonCTA>
    const button = getByTestId(containerNode,'Facebook');
    userEvent.click(button);
    const url='https://www.facebook.com/sharer/sharer.php?u=https://www.legalzoom.com';
    expect(window.location.href).toMatch(url);

In jest it navigates to Localhost so this code is not working.



Solution 1:[1]

You don't need to test the browser's behavior in tests. Because this behavior has already been tested by the Mozilla, Google, etc before the release. All you need to do is to test that the behavior is triggered correctly. In your situation it will be something like this:

// before the rendering
jest.spyOn(window, "open")
...
expect(window.open).toHaveBeenCalledWith('https://www.facebook.com/....');

If you really want to test such behavior you should use cypress.io which runs your code in real browser

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Andrey Nelubin