Skip to content

Instantly share code, notes, and snippets.

@Alexisvt
Last active September 1, 2022 10:30
Show Gist options
  • Save Alexisvt/8fab18d303543e83130101746246f51c to your computer and use it in GitHub Desktop.
Save Alexisvt/8fab18d303543e83130101746246f51c to your computer and use it in GitHub Desktop.
Jest and testing-library recipes

Jest Recipes

How to mock some windows functions

In this example, Im mocking the open function of the window object, then in the actual test block, Im returning an object with a focus property that also Im mocking.

Describe('some test', () => {

  let spyWindowOpen;

  beforeEach(() => {
    spyWindowOpen = jest.spyOn(window, 'open');
  });

  afterEach(() => {
    spyWindowOpen.mockRestore();
  });


  it('some other test', () => {
    const open = jest.fn((...args) => ({ focus: jest.fn() }));
    spyWindowOpen.mockImplementation(open);


    render(<YourComponent />);
    
    // ... the rest of your code

    expect(open).toBeCalled();
    expect(open).toBeCalledWith('http://www.google.com', '_blank');
  });

})

Some references:

How to write a text programatically on an input or textarea

const input = screen.getByRole('textbox', { name: /some field/i });
// always remember to await this kind of actions
await userEvent.type(input, 'abc');
expect(input).toHaveValue('');

Also, there are sometimes where we want to clear whatever we typed, for that we use userEvent.clear

const input = screen.getByRole('textbox', { name: /some field/i });
// always remember to await this kind of actions
await userEvent.type(input, 'abc');
expect(input).toHaveValue('');

await userEvent.clear(input)
...

References

How to mock window alert

const alertMock = jest.spyOn(window, "alert").mockImplementation();
render(<App />);

userEvent.click(screen.getByRole("button", { name: LOGIN_BUTTON_TEXT }));

expect(alertMock).toHaveBeenCalled();

How to react React ENV variables in Jest

Just create a file called .env.test.local Jest will read it automatically

Reference:

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