mercredi 14 octobre 2020

How to test custom react hook with renderHook

I created a custom react hook that uses axios to get a list of tags and handles any errors. The hook works fine, and I can test the success handling, but I am having a hard time figuring out how to test the error handling.

component.js

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

const useGetTags = () => {
  const [tags, setTags] = useState([])

  const getTags = async () => {
    await axios
      .get('/api/tags')
      .then(response => {
        if (response.data.errors) {
          response.data.errors.map(error => console.log(error.message))
        } else {
          setTags(response.data.data)
        }
      })
      .catch(error => console.log(error.message))
  }

  useEffect(() => {
    getTags()
  }, [])

  return tags
}

export default useGetTags

This is how I tested a successful response, which works.

test.js

import axios from 'axios'
import { renderHook } from '@testing-library/react-hooks'
import useGetTags from './useGetTags'

jest.mock('axios', () => ({
  get: jest.fn(() => Promise.resolve({ data: { data: [], errors: [{ message: 'mock' }] } })),
}))

describe('useGetTags hook', () => {
  it('should make an axios call to display a list of tag options', async () => {
    axios.get.mockImplementationOnce(() =>
      Promise.resolve({ data: { data: [{ label: 'mock-A', value: 'mock-a' }] } }),
    )

    const { waitForNextUpdate, result } = renderHook(() => useGetTags())

    await waitForNextUpdate()

    expect(result.current).toStrictEqual([{ label: 'mock-A', value: 'mock-a' }])
  })
})

I've tried to do something similar for the errors, but with no such luck.

it('should display an error if an errors array exists', async () => {
    axios.get.mockImplementationOnce(() =>
      Promise.resolve({ data: { data: [], errors: [{ message: 'mock' }] } }),
    )

    const { waitForNextUpdate, result } = renderHook(() => useGetTags())
    
    await waitForNextUpdate()

    expect(result.current).toStrictEqual({ data: [], errors: [{ message: 'mock' }] })
  })

Any ideas would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire