首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用测试自定义异步/等待钩子-测试库

如何使用测试自定义异步/等待钩子-测试库
EN

Stack Overflow用户
提问于 2019-08-14 13:33:40
回答 1查看 2.6K关注 0票数 20

我创建了一个定制的react钩子,它应该用来处理所有不太重要的api请求,我不想存储在redux状态中。钩子很好,但我在测试它时遇到了麻烦。我的测试设置是开玩笑和酶的,但我决定在这里尝试一下react-hooks-testing-library

到目前为止,我尝试的是第一次使用 fetch -模拟库来模拟提取请求,这很好。接下来,我使用renderHook方法呈现钩子,该方法来自react hooks- Next库.不幸的是,看起来我不太理解waitForNextUpdate方法。

我的钩子就是这样的。

useApi hook

代码语言:javascript
复制
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 };
}

钩子可以采取3种不同的状态组合,我想测试。不幸的是我不知道怎么做。

加载数据:

代码语言:javascript
复制
{ response: undefined, isLoading: true, error: false }

加载的数据:

代码语言:javascript
复制
{ response: R, isLoading: false, error: false }

错误:

代码语言:javascript
复制
{ response: undefined, isLoading: false, error: true }

现在我的测试是这样的:

代码语言:javascript
复制
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);
});

callApi func

代码语言:javascript
复制
/**
 * 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;
    }
};
EN

回答 1

Stack Overflow用户

发布于 2020-06-01 15:56:00

你这么做没什么关系。现在,您需要使用expect进行测试。

代码语言:javascript
复制
const value = {...}
expect(result.current).toEqual(value)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57495823

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档