如何使用react-hooks-testing-library测试自定义异步/等待挂钩

Dan*_*zki 13 testing reactjs react-hooks react-hooks-testing-library

我创建了一个自定义的React钩子,该钩子应该可以处理所有不太重要的api请求,但我不想将其存储在redux状态。挂钩工作正常,但我无法对其进行测试。我的测试设置是开玩笑和酶,但是我决定在这里也尝试一下react-hooks-testing-library

到目前为止,我尝试过的工作是先使用fetch-mock库模拟fetch请求,但效果很好。接下来,我用renderHook方法渲染钩子,该方法来自react-hooks-testing-library。不幸的是,我似乎不太了解该waitForNextUpdate方法。

这就是我的钩子的样子。

useApi钩

export function useApi<R, B = undefined>(
    path: string,
    body: B | undefined = undefined,
    method: HttpMethod = HttpMethod.GET
): ResponseStatus<R> {
    const [response, setResponse] = useState();
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [error, setError] = useState<string | boolean>(false);

    useEffect(() => {
        const fetchData = async (): Promise<void> => {
            setError(false);
            setIsLoading(true);
            try {
                const result = await callApi(method, path, body);
                setResponse(result);
            } catch (errorResponse) {
                setError(errorResponse);
            }

            setIsLoading(false);
        };

        fetchData();
    }, [path, body, method]);

    return { response, isLoading, error };
}
Run Code Online (Sandbox Code Playgroud)

挂钩可以采用3种不同的状态组合,我想测试一下。不幸的是,我不知道如何。

加载数据中:

{ response: undefined, isLoading: true, error: false }
Run Code Online (Sandbox Code Playgroud)

加载的数据:

{ response: R, isLoading: false, error: false }
Run Code Online (Sandbox Code Playgroud)

错误:

{ response: undefined, isLoading: false, error: true }
Run Code Online (Sandbox Code Playgroud)

这是我目前的测试结果:

import fetchMock from 'fetch-mock';
import { useApi } from './hooks';
import { renderHook } from '@testing-library/react-hooks';

test('', async () => {
    fetchMock.mock('*', {
        returnedData: 'foo'
    });

    const { result, waitForNextUpdate } = renderHook(() => useApi('/data-owners'));

    console.log(result.current);

    await waitForNextUpdate();

    console.log(result.current);
});
Run Code Online (Sandbox Code Playgroud)

callApi功能

/**
 * Method to call api.
 *
 * @param {HttpMethod} method - Request type.
 * @param {string} path - Restful endpoint route.
 * @param {any} body - Request body data.
 */
export const callApi = async (method: HttpMethod, path: string, body: any = null) => {
    // Sends api request
    const response = await sendRequest(method, path, body);
    // Checks response and parse to the object
    const resJson = response ? await response.json() : '';

    if (resJson.error) {
        // If message contains error, it will throw new Error with code passed in status property (e.g. 401)
        throw new Error(resJson.status);
    } else {
        // Else returns response
        return resJson;
    }
};
Run Code Online (Sandbox Code Playgroud)

小智 1

你所做的一切都很好。现在,您需要使用expect进行测试。

const value = {...}
expect(result.current).toEqual(value)
Run Code Online (Sandbox Code Playgroud)