类型错误:未定义不是单元测试自定义 redux 钩子时的函数



我有一个自定义钩子,它调用一个 saga 函数,该函数在测试这个函数时又调用一个 axios api,im get

类型错误:未定义不是函数

我只想测试是否调用了此函数。

postsHook.test.tsx

import { renderHook } from "@testing-library/react-hooks";
import usePostsHook from "./postsHook";
import { initCommentUpdates, getPostsInit } from "../actions/postActions";
import { getPosts } from "../selectors/selectors";
import { useSelector, useDispatch } from "react-redux";
describe("usePostsHook hook", () => {
const [posts] = renderHook(() => usePostsHook());
expect(posts).toHaveBeenCalledWith(1);
});

帖子钩子.tsx

import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { initCommentUpdates, getPostsInit } from "../actions/postActions";
import { getPosts } from "../selectors/selectors";
function usePostsHooks() {
const dispatch = useDispatch();
const posts = useSelector(getPosts());
React.useEffect(() => {
dispatch(getPostsInit());
console.log("post hooks got called");
dispatch(initCommentUpdates());
}, []);
return [posts];
}
export default usePostsHooks;
posts

不是钩子中的函数,而是从商店中选择的东西,我认为是从您的 API 返回的。 所以expect(posts).toHaveBeenCalledWith(1);是很自然的,因为它不是一个函数。

要测试您的调度是否发生,您需要模拟它。这是我在测试中使用的一个示例:

import * as ReactRedux from 'react-redux';
// this mock will be the dispatch function that redux returns on useDispatch()
const mockDispatch = jest.fn();
beforeAll(() => {
// tells useDispatch to return the mocked dispatch
ReactRedux.useDispatch = jest.fn().mockImplementation(() => mockDispatch);
// tells useSelector to return an empty array
ReactRedux.useSelector = jest.fn().mockImplementation(() => []);
});

beforeEach(() => {
// clear the mocks to refresh their calls info
ReactRedux.useDispatch.mockClear();
mockDispatch.mockClear();
});

稍后,在您的测试中

expect(posts).toEqual([])
expect(mockDispatch).toHaveBeenCalledWith(getPostsInit())

这里的问题是,你只是在对钩子进行单元测试,即:它返回useSelector返回的内容,它触发一些调度,而不知道useSelectoruseDispatch的实际实际实现是什么

最新更新