How to test React component with axios and useEffect?

Viewed 23

I have a component that calls an API. In this case I am using Axios and the API call is inside a useEffect and a setInterval.

Also, the component sets different values with a useState, and finally returns those values in an object.

I am new using Jest and react-testing-library and my doubt is how to test components that use Axios with useEffect.

function Currencies() {
  const [btcprice, setBtcprice] = useState(0);

  // Getting BTC price in USD

  useEffect(() => {
    const API_key = "7c138b65";
    const endPoint_usd = "https://api.blockchain.com/v3/exchange/tickers";

    const interval_usd = setInterval(() => {
      axios
        .get(endPoint_usd, {
          headers: { "x-api-key": { API_key } },
        })
        .then((resp) => {
          const BTCData = resp.data[33].last_trade_price;
          setBtcprice(BTCData);
        })
        .catch((err) => console.log("Error: " + err));
    }, 5000);
    return () => clearInterval(interval_usd);
  }, []);

  // Another function to get usdprice value...

  return {
    valBTC: btcprice,
    valUSD: usdprice,
  };
}

This is my Currencies.test.js

import axios from 'axios';
import Currencies from './Currencies'

jest.mock('axios');

test('good responde', () => {
    const btcprice = 22900.00
    const resp = {data: btcprice};
    axios.get.mockImplementation(() => Promise.resolve(resp))
  
    return Currencies.all().then(data => expect(data).toEqual(btcprice));
})

The error in the console is this, but I have followed this documentation, so I don't know what's wrong:

TypeError: _Currencies.default.all is not a function
0 Answers
Related