D
D
dc65k2020-04-28 15:21:49
React
dc65k, 2020-04-28 15:21:49

How to test useEffect?

Hello everyone, I have the following situation.
Has a functional component

import React, { useEffect } from 'react'

const Component = ({ data }) => {

  const [c, setC] = useState({ value: 0, date: null })

  useEffect(() => {
    // setC(data)
    setC({
      value: 0, date: new Date('2020-04-28')
    })
  }, [])

  const { date } = c

  if (!date) {
    return null
  }
  
  return <div />
}

The idea is that in componentDidMount() the state changes, and during the current test it gets into:
if (!date) {
  return null
}

Please tell me how to handle this asynchronous moment in jest.
import React from 'react'
import renderer from 'react-test-renderer'

import Component from './component'

const data = [
    {
        date: '2020-04-28',
        value: '2020'
    }
]

describe('Component', () => {

    test('renders component without error', () => {

        const wrapper = renderer.create(
            <Component data={data} />
        ).toJSON()
        
        expect(wrapper).toMatchSnapshot()
    })

})

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question