-1

I want to test useEffect with two api calls as shown below. How can I mock api call or in this case how can I spy on fetchCountry & fetchStates functions and then how to test setCountry and setStates functions

using Jest & Enzyme

import React, { useEffect, useState } from "react";
import fetchCountry from "../fetchCountry";
import fetchState from '../fetchState';
const App = () => {

  const [country, setCountry] = useState();
  const [state, setStates] = useState();

  useEffect(() => {
    loadData()
  }, []);

 const loadData = async()=>{
  const country = await fetchCountry('Japan');
  const states = await fetchState(country.code)
 
  setCountry(country);
  setStates(states)
 } 

fetchCountry.js (dummy implementation)

const fetchCountry = (countryName) => {
    const requestOptions = {
      method: "GET",
      headers: { "Content-Type": "application/json" }
    };

    return fetch(`https://restcountries.com/v2/name/${countryName}`, requestOptions).then(res=>res.ok && res.json());
  };

export default fetchCountry;

fetchState.js

const fetchState = (countryCode) => {
  const requestOptions = {
    method: "GET",
    headers: { "Content-Type": "application/json" }
  };

  return fetch(`https://restcountries.com/v2/name/${countryCode}`, requestOptions).then(res=>res.ok && res.json());
};

export default fetchState;
micronyks
  • 54,797
  • 15
  • 112
  • 146

1 Answers1

0

You actually don't need to test useState hook. It is a part of React and it is already tested by its maintainers.

Let's come back to fetchCountry and fetchState.

In your test:

const fetchCountryMock = jest.spyOn(fetchCountry, 'default').mockImplementation();

const wrapper = mount(Component);

await flushPromises(); /* You can write your own implementation or use the library
function flushPromises() {
    return new Promise(resolve => setImmediate(resolve));
}
*/
expect(fetchCountryMock).toHaveBeenCalledWith('Japan');