1

I want to test a function that fetch something from server, it looks like this :

import React, { useEffect } from 'react';

function Component1() {

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

    const fetchSomeData = async () =>{
        console.log('fetchSomeData')
       

    }
    return <div>Component1</div>;
}

export default Component1;

and test file:

import React from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { act } from 'react-dom/test-utils';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Component1 from './Component1.js';

Enzyme.configure({ adapter: new Adapter() });

describe('Name of the group', () => {
    it('should ', () => {
        const wrapper = shallow(<Component1 />);
        expect(wrapper.exists());
        
    });
});

[![picture1][1]][1]

but the test is not covered 'fetchSomeData', any one knows why?

I referred this answer : test restapi inside useeffect in jest try to mock a fn and call it , but I got this:

enter image description here

jjzjx118_2
  • 419
  • 7
  • 23
  • 1
    You should not use async await in useEffect, just call fetchSomeData without await – anttud Oct 30 '20 at 07:22
  • 1
    Does this answer your question? [React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing](https://stackoverflow.com/questions/53332321/react-hook-warnings-for-async-function-in-useeffect-useeffect-function-must-ret) – anttud Oct 30 '20 at 07:24
  • thanks, I have changed the code to avoid use await inside a useEffect, but my problem is about I need to 100% covered my code test with jest. but it seems not covered the red part of my code. – jjzjx118_2 Oct 30 '20 at 08:09
  • You should NOT return data in the callback of `setTimeout`. See https://stackoverflow.com/questions/24928846/get-return-value-from-settimeout – Lin Du Oct 30 '20 at 08:23

0 Answers0