net - UK (2020-01)

(Antfer) #1

PROJECTS
React


UNIT AND


INTEGRATION TESTS


IN-DEPTH

There are generally two types of tests we talk about in the
context of code tests:

Unit testing
This is to test the units of code or each module in isolation. They
shouldn’t call other modules in your project, instead you should
mock these modules so that the unit test is able to run.

Integration testing
When two or more modules are used in conjunction, it’s good
practice to write an integration test. These test how modules work
together. Well-written integration tests can identify issues when
you’re using modules as part of a larger piece of work.

These are the two kinds of tests developers usually write – there
are other tests that QA engineers write.

another function works as we assume it will. But
since that function is an external dependency,
we don’t want to test that here. Our tests should
encapsulate only the functionality we want them to.

WRITE YOUR FIRST TEST
Let’s write our first test. Create a new file
called MyComponent.unit.test.js in the same folder
as the component. By adding test.js at the end, it’ll
be automatically picked by the testing library. The
contents of that file are below:

import React from ‘react’
import { render } from ‘@testing-library/react’
import MyComponent from ‘./MyComponent’
describe(‘the <MyComponent />’, () => {
// tests go here
})

The first thing I want to draw your attention to is the
describe() function, which takes two arguments: the
first is a string that you can use to better describe – as
a string of text – what your test is going to be doing.
In our case we’ve simply said that it should render.
This is very useful when someone else looks at your
code or you have to remember what you did at a later
stage. Writing good describe statements is a form of
code documentation and another good reason for
writing tests.
The second argument is your tests. The describe()
function will run all of these tests one after the other.

CLEANUPS
Let’s introduce a helper function called beforeEach().
We need to use this because each time we do
something with the component, we want a fresh
copy without the props we previously had passed to it
still existing in the component. Or we might need to
re-render the component: beforeEach() does that for us
and we can pass it the cleanup function.

import { render, cleanup } from ‘@testing-library/react’
...
describe(‘the component should render’, () => {
beforeEach(cleanup)
}

WRITE A SNAPSHOT TEST
In this step, we’re going to ‘mount’ our component (or
render it).

describe(‘the component should render’, () => {
beforeEach(cleanup)
it(‘renders with basic props’, () => {
render(<MyComponent />)

“The ‘describe()’ function


takes two arguments: the


Ľuvw#lv#d#vwulqj#wkdw#|rx#fdq#


use to better describe – as a


string of text – what your test


is going to be doing”

Free download pdf