React & Jest for UseEffect + Async

Viewed 139
export const XYZ: FC<props> = () => {
    const [isLoaded, setIsLoaded] = useState<any>(false);

    React.useEffect(() => {
        async function Status() {
            await getStatus()
            .then((res: any) => {
                if (res.totalCount === 0){
                    setIsLoaded(true);
                }
....
....
    return (
              isLoaded && <Loaded />
              !isLoaded && <Loading />
    );

Question, How could I write unit tests to test if <Loaded> is visible/active component on the screen?

Using useEffect with Async method to call the Status api service has become a pain.

What I have right now and which obviously doesn't work.

jest.spyOn(APIService, "getStatus")
    .mockResolvedValue({ totalCount: 0 });


describe('XYZ_Tests', ()=> {
        let wrapper: any;
        let useEffect: any;

        const mockUseEffect = () => {
            useEffect.mockImplementationOnce(f => f());
        };

    beforeEach(() => {
            useEffect = jest.spyOn(React, "useEffect").mockImplementation(f => f());

            mockUseEffect();
        
            wrapper = shallow(<XYZ />);
    
            console.log(wrapper.debug()); 
          });

console.log(wrapper.debug());

This line always says <Loading /> is active indicating that useEffect mocks doesnt work.

0 Answers
Related