reactjsjestjsreact-testing-library

How to test async function in react using react-testing-library


I am trying to use react testing library and writing common example, just to find out how it works.

And here is a problem, I have a component NewForm, there is a useEffect, and the purpose is to change state after 1 sec delay and show div with text. I need to write test to understand how to test async logic, but my solution is wrong, do you have any ideas how to fix it ?

My component:

import React, { useEffect, useState } from 'react'

const NewForm = () => {
  const [value, setValue] = useState(null)
  useEffect(() => {
   const timer =  setTimeout(() => {
      setValue({name: "Nik"})
    }, 1000)
    return () => {
      clearTimeout(timer)
    }
  }, [])
  return (
    <form>
        <input type="text" />
        <input type="email" />
        <button type={'button'}>Click</button>
        {value && <div>Div</div>}
    </form>
  )
}

My test file:

import { render, screen } from "@testing-library/react"
import NewForm from "./NewForm"


describe('', () => {
    it('', async () => {
        render(<NewForm/>)
        screen.debug()
        const divText =  await screen.findByText(/div/i)
        expect(divText).toBeInTheDocument()
        screen.debug()
    })
})

Error:

enter image description here

file setupTests:

import '@testing-library/jest-dom'

I have no idea what to do.


Solution

  • Try:

    import { render, screen, act } from '@testing-library/react';
    import '@testing-library/jest-dom';
    import React from 'react';
    import NewForm from './NewForm';
    
    describe('75915189', () => {
      it('should pass', async () => {
        jest.useFakeTimers();
        render(<NewForm />);
        act(() => {
          jest.advanceTimersByTime(1000);
        })
        const divText = await screen.findByText(/div/i);
        expect(divText).toBeInTheDocument();
      });
    });
    

    Test result:

     PASS  stackoverflow/75915189/NewForm.test.jsx (9.734 s)
      75915189
        ✓ should pass (41 ms)
    
    -------------|---------|----------|---------|---------|-------------------
    File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    -------------|---------|----------|---------|---------|-------------------
    All files    |     100 |      100 |     100 |     100 |                   
     NewForm.jsx |     100 |      100 |     100 |     100 |                   
    -------------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        10.247 s