question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Testing components with @testing-library/react example

See original GitHub issue

I implemented the basic tutorial (https://recoiljs.org/docs/basic-tutorial/atoms) and wanted to add tests for components. I’m especially wondering how to mock out/simplify setting up global state that’s accessed via recoil hooks. For example useRecoilState as below.

Here’s my test for the TodoItem class (it is in typescript, but that’s not relevant). It works but I find it very convoluted to wrap my Component to test twice in order to get this to work correctly. I must be doing this in a very convoluted way.

import React, { useEffect } from "react";
import { render, fireEvent } from "@testing-library/react";

import { RecoilRoot, useRecoilState } from "recoil";

import { TodoItem } from "./TodoItem";
import { todoListState } from "../../state/atoms/todoListState";
import { Todo } from "../../state/atoms/todoState";

const RecoiledTodoItem = ({ todo }: { todo: Todo }) => {
  const [todoList, setTodoList] = useRecoilState<any>(todoListState);
  useEffect(() => {
    setTodoList((todoList: Todo[]) => {
      return [...todoList, todo];
    });
  }, []);
  if (todoList.length == 0) {
    return null;
  }
  return (
    <>
      {todoList.map((todo: Todo) => (
        <TodoItem key={todo.id} todo={todo} />
      ))}
    </>
  );
};

const WrappedTodoItem = ({ todo }: { todo: Todo }) => {
  return (
    <RecoilRoot>
      <RecoiledTodoItem todo={todo} />
    </RecoilRoot>
  );
};

test("updates todo item", async () => {
  const todo: Todo = {
    id: "testId",
    isComplete: false,
    title: "old title",
  };

  // Act
  const { getByTestId, getByDisplayValue } = render(
    <WrappedTodoItem todo={todo} />
  );

  fireEvent.change(getByTestId(/todo-text/i), {
    target: { value: "new title" },
  });

  // Assert
  expect(getByDisplayValue(/new title/i)).toBeInTheDocument();
});


Adding some example tests into an example/tests folder or similar using @testing-library/react (which is included in CRA) would be great!

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:1
  • Comments:6

github_iconTop GitHub Comments

31reactions
schnerdcommented, Jul 18, 2020

This simple solution seems to work well if you just need to initialize some atom states before testing a component:

  render(
    <RecoilRoot initializeState={(snap) => snap.set(myAtom, {foo: 'bar'})}>
      <MyComponent />
    </RecoilRoot>,
  );
4reactions
orrybaramcommented, Jun 22, 2020

@jonolo6 not sure if you’ve figured out your own pattern yet, but we ran into the same issue with testing out recoil states. We ended up creating a small library that extends @testing-library/react-hooks. It works by injecting RecoilRoot into the wrapper and creating dummy components with state updaters for each piece of state you want to update. Check it out here https://github.com/inturn/react-recoil-hooks-testing-library would love some feedback!

Read more comments on GitHub >

github_iconTop Results From Across the Web

React Components Testing with React Testing Library and Jest
React Testing Library (RTL) is built on top of the DOM testing library, as the tests will work with the actual DOM. This...
Read more >
React Testing Library
The React Testing Library is a very light-weight solution for testing React components. It provides light utility functions on top of react-dom ...
Read more >
How To Test a React App with Jest and React Testing Library
In this tutorial, you will test asynchronous code and interactions in a sample project containing various UI elements. You will use Jest to ......
Read more >
React Testing Library Tutorial - Robin Wieruch
React Testing Library is used to interact with your React components like a human being. What a human being sees is just rendered...
Read more >
React Testing Library – Tutorial with JavaScript Code Examples
React Testing Library is a testing utility tool that's built to test the actual DOM tree rendered by React on the browser. The...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found