首页 > 解决方案 > Test useEffect hook which has an aync method call within it

问题描述

Presently using useEffect to call customMethod which is an async method that I have written
in another js file.

How could I test this, possibly via jest? And since the calls to useState is in there too,
presumably they would fall under the same test too.

Seen other examples like the following. But most are either using react testing library
or not testing useEffect similar to mine. where it is calling another async method which is not external like fetch
but an internal method within own project.

Using useEffect() hook to test a function in Jest

Trigger useEffect in Jest testing

https://epicreact.dev/how-to-test-react-use-effect/

Could I get some guidance on how to test this pls.

My functional component.

const MyFunc = ({
    myparams
}) => {
    const [data, setData] = React.useState(false);
    React.useEffect(() => {
        const tempMethod = async => {
            return await customMethod();
        }

        tempMethod()
            .then(r => setData(r))
            .catch(() => setData(false));

    }, []);

    // ... other logic

    return (
        <SomeComponent/>
    );
}

标签: javascriptjestjs

解决方案


推荐阅读