Testing React Context APIs with React Testing Library

Sajal Dulal
Geek Culture
Published in
4 min readMar 31, 2022

--

This article aims at providing a clear concept for writing test cases for Context Providers in a React Application with react-testing-library. This article does not however cover how to use or when to use Context API in React.

Also, some familiarity with Writing Tests is expected through this tutorial. Not necessarily with React Testing Library.

Context provides a way to pass data through the component tree without having to pass props down manually at every level.
- ReactJS Docs

React Contexts are vital to every React Application. They could be used as a single source of truth that could be used across the required component tree. So it is important that they are well tested as well. But a ton of the time, ContextAPIs are left untested, cause….well…there’s no straightforward way to test contexts. But we can test it quite well with another dummy component, that uses all of its features just for the sake of testing them.

Provider

Let’s take an example AuthContext provider which stores and provides the user Authentication info to the React application wherever needed.

//AuthContext.jsimport React, { createContext, useState, useEffect } from 'react';import {…

--

--

No responses yet