react enzyme hooks test code example

Example: react enzyme hooks test

//app.js
import React from 'react'
import FetchData from './FetchData'

const fetchUsers = () =>
fetch('https://jsonplaceholder.typicode.com/users').then((res) => res.json())

function App() {
  return (
    <>
      
    
  )
}

export default App

//fetchdata.js
import React, { useState } from 'react'

function fetchData({ fetchUsers }) {
  const [state, setState] = useState([])

  React.useEffect(() => {
    fetchUsers().then(setState)
  }, [])

  return (
    <>
      {state &&
        state.map((val, id) => (
          
  • {val.name}
))} ) } export default fetchData // fetchdata.test.js import React from 'react' import { shallow } from 'enzyme' import FetchData from '../FetchData' describe('Fetch All Data Hooks', () => { let props let wrapper let useEffect const users = [ { id: 1, name: 'jamal' }, { id: 2, name: 'karyo' }, { id: 3, name: 'mirdad' } ] beforeEach(() => { useEffect = jest.spyOn(React, 'useEffect').mockImplementationOnce((f) => f()) props = { fetchUsers: jest.fn().mockResolvedValue(users) } wrapper = shallow() }) afterAll(() => { jest.clearAllMocks() }) it('result all users', () => { expect(useEffect).toHaveBeenCalled() expect(props.fetchUsers).toHaveBeenCalled() expect(props.fetchUsers).toHaveBeenCalledTimes(1) expect(jest.isMockFunction(props.fetchUsers)).toBeTruthy() }) it('find render all users exits count', () => { expect(wrapper.find('ul > li')).toHaveLength(3) expect( wrapper.containsAllMatchingElements([
  • jamal
,
  • karyo
,
  • mirdad
]) ).toBeTruthy() }) })

Tags:

Misc Example