Skip to content

Instantly share code, notes, and snippets.

@sibelius
Last active February 1, 2024 17:36
Show Gist options
  • Star 52 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sibelius/632b525ff006b48b10859e98bad4757b to your computer and use it in GitHub Desktop.
Save sibelius/632b525ff006b48b10859e98bad4757b to your computer and use it in GitHub Desktop.
testing library concept and basic test

You first need to undestand the concept of frontend tests.

You should not test the implementation but the behavior

You test like the end user

For instance, imagine a login screen with email and password inputs and a submit button

The test should input the email and the password, then click in the submit button.

You should assert the API was called with the inputted data.

When using testing library you test against DOM

code:

const emailInput = getByTestId(emailTestId);
fireEvent.onChange(emailInput, { target: { value: 'email@email.com.br' }})

const passwordInput = getByTestId(passwordTestId);
fireEvent.onChange(passwordInput, { target: { value: 'pwd' }})

const submitButton = getByText('Login').closest('button');
fireEvent.click(submitButton);

// assert api was called properly
@biantris
Copy link

biantris commented Jun 9, 2021

Use blur to simulate when the element loses focus:

const emailInput = getByTestId(emailTestId);
fireEvent.onChange(emailInput, { target: { value: 'email@email.com.br' }})
fireEvent.blur(emailInput)

const passwordInput = getByTestId(passwordTestId);
fireEvent.onChange(passwordInput, { target: { value: 'pwd' }})
fireEvent.blur(passwordInput)

const submitButton = getByText('Login').closest('button');
fireEvent.click(submitButton);

// assert api was called properly

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