net - UK (2020-01)

(Antfer) #1

React


To p The React Testing
Library resource is a great
place to learn more about
testing your components

This is great: we don’t have to manually go to the
site and look around, then click the button and look
around a second time – during which, you might
admit, you’ll likely forget or miss something! Now we
can have confidence that, given the same input, we
can expect the same output in our component.
When it comes to test IDs, I personally dislike
using data-testid to find something in the DOM.
After all, the object of tests is to mimic what the
user is doing and to test what happens when they
do. data-testid feels like a bit of a cheat – although
data-testids will likely come in handy for your
QA engineer (see the boxout The Role of Quality
Assurance Engineers).
Instead, we could use getByText() and pass in the
text of our button. That method would be a lot more
behaviour specific.


MOCKING AND SPYING
Sometimes we might need to test a call to a function
but that function is outside the scope of the test. For
example, I have a separate module that contains a
function that calculates the value of pi to a certain
number of decimals.
I don’t need to test what the result of that module
is. I need to test that my function does as expected.
For more information about why this is, please see the
box Unit and Integration Tests. In this case, we could
‘mock’ that function:


const getPiValue = jest.fn()
it(‘calls the function on click’, () => {
const { container, getByTestId } = render(<ToggleButton
/>)
fireEvent.click(getByTestId(‘mode-toggle’))
expect(getPiValue).toHaveBeenCalledTimes(1)
)
})


The function toHaveBeenCalledTimes() is one of the many
helper functions in the testing library that enable us


to test the output of functions. This lets us not only
scope our tests only to the module we want to test but
also means we can ‘spy’ on or see what our function
does when it calls that function.

START TESTING REACT APPLICATIONS
Writing tests can seem a little daunting to start
with. I hope this tutorial has given you a little more
confidence to try it. Since I started writing tests for
my applications, I really can’t go back: I can rest
easier, knowing I’m leaving behind a much better
legacy for those who will use my work in the future.
For more ideas about how to test your components,
visit: https://react-testing-examples.com or https://testing-
library.com/docs/react-testing-library/intro. If you’re
looking for some courses to help you get started, the
one by Kent C Dodds (who wrote and maintains React
Testing Library) is popular: https://testingjavascript.com/.
I also enjoyed this one on Level Up Tutorials it’s the
one that got me started writing tests for my
code: https://www.leveluptutorials.com/tutorials/react-
testing-for-beginners.

“We don’t have to


manually look around


the site. Now we can have


frqĽghqfh#wkdw/#jlyhq#


the same input, we can


expect the same output”

Free download pdf