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:
- https://jestjs.io/docs/mock-function-api#mockfnmockimplementationfn
- https://jestjs.io/docs/upgrading-to-jest28#jestfn
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
const alertMock = jest.spyOn(window, "alert").mockImplementation();
render(<App />);
userEvent.click(screen.getByRole("button", { name: LOGIN_BUTTON_TEXT }));
expect(alertMock).toHaveBeenCalled();
Just create a file called .env.test.local
Jest will read it automatically
Reference: