Katharina Schreiber
Katharina Schreiber

Reputation: 1371

Mocking window object with Jest

I have a function which mocks a hostname. It is defined before the actual test, so before describe.

const mockHost = (hostname: string) => {
  global.window = Object.create(window);
    Object.defineProperty(window, 'location', {
      value: {
        hostname
      }
    });
}

I run two tests with a different hostname

it('should show local hostname', async() => {
    fetchMock.getOnce('/test', {
      data: {
        green: true,
      },
    });
    mockHost('local')
    const instance = render(<Component />);
    expect(instance.getByText('local')).toBeVisible();
  });

 it('should show different hostname', async() => {
    fetchMock.getOnce('/test', {
      data: {
        green: true,
      },
    });
    mockHost('different')
    const instance = render(<Component />);
    expect(instance.getByText('different')).toBeVisible();
  });

It's a fake example and when run separately both tests work. But if both are run in a bunch a hostname won't reset and stays as local, causing second test with a different hostname to fail. I am new to testing. What am I doing wrong?

Upvotes: 1

Views: 3485

Answers (1)

Katharina Schreiber
Katharina Schreiber

Reputation: 1371

I found this article on Medium 'Mocking window object with Jest' from Marek Rozmus on Oct 14, 2021, which describes, that I was doing the static mocking, which is only suitable if we need to test only one value. Im my case value changes, so I need dynamic hostname mocking.

So instead mockHost(), I'd need the following:

const mockPathname = jest.fn();
Object.defineProperty(window, 'location', {
  value: {
    get hostname() {
      return mockPathname();
    },
  },
});

In tests itself I'd call:

mockPathname.mockReturnValue('some hostname');

And I'd need to clear all Mocks after each test

afterEach(() => {
    jest.resetAllMocks();
});

Upvotes: 3

Related Questions