net - UK (2020-04)

(Antfer) #1

PROJECTS
React Testing Library


REACT TESTING LIBRARY


View source


files here!
All the files you need for
this tutorial can be found at
https://netm.ag/2UpMOsg

import axios from “axios”;
const { get } = require(‘axios’)
const GetApiData = async (domain = “https://swapi.co”,
parameters = {}) => {
try {
const { data } = await get(`${domain}/api/`, {
parameters
})
if (!Array.isArray(data) || !data.length) {
return []
}
return data
} catch (error) {
console.log(error)
}
}
export default GetApiData;

Looking at this code, I can immediately see the
following possible outcomes:

WRITE TESTS FOR


JAVASCRIPT API CALLS


Ben Read show us more advanced React testing methods by testing an


API call, its fallbacks and possible failures using the React Testing Library


In net 327, we walked through how to use the
React Testing Library to write basic unit tests
for React components (https://netm.ag/issue327). In
this article we’re going to dive deeper and
demonstrate how to write tests for some code that
fetches data from an API.
I hope you’ll learn some more things to help you
ensure that all of your code is production-ready,
which will give you and your stakeholders more
confidence when publishing new code.

DECIDE WHAT TO TEST
Before we even begin writing tests, it’s good to
take some time to decide what needs to be tested.
We need to set clear boundaries right from the
start, otherwise we could waste time writing tests
unnecessarily. Read through your code and see what
different outcomes it might generate.
Let’s look at an imaginary API call to see what
outcomes exist. Here’s the code we’re going to test:

ABOUT THE AUTHOR
BEN READ
t: @muzzlehatch_
job: Developer
areas of expertise:
JavaScript, React and UX

FOR MORE
REACT
TESTING
TIPS, CHECK
OUT NET 327
https://netm.ag/
issue327
Free download pdf