使用thunk测试对测试库Redux进行React,未分派操作

j0pj023g  于 2023-01-13  发布在  React
关注(0)|答案(1)|浏览(170)

我正在尝试测试用户单击按钮后是否增加了类似计数器。我正在使用react测试库,其中我找到了一个按钮并执行userEvent.click,这应该在后台调度一个操作并增加计数器,然后我可以Assert新值。
当我手动通过用户界面但无法使测试工作时,这是有效的。
按钮:

<Button
      size="small"
      color="primary"
      onClick={() => dispatch(likePosts(post._id))}
    >
      <ThumbUpIcon fontSize="small" />
      Like {`${post.likeCount}`}
      {}
    </Button>

Thunk操作:

export const likePosts = (id) => async (dispatch) => {
  try {
    const { data } = await api.likePost(id);
    dispatch({ type: LIKE, payload: data });
  } catch (error) {
    console.log(error);
  }

我还设置了一个test-util来帮助我测试连接组件TEST UTIL LINK我还添加了applyMiddleware(thunk)来支持连接组件时的thunk
测试效用:

import React from "react";
import { render as rtlRender } from "@testing-library/react";
import { legacy_createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import thunk from "redux-thunk";
// Replace this with the appropriate imports for your project
import reducers from "../redux/reducers";

const render = (
  ui,
  {
    store = legacy_createStore(reducers, applyMiddleware(thunk)),
    ...renderOptions
  } = {}
) => {
  const Wrapper = ({ children }) => (
    <Provider store={store}>{children}</Provider>
  );
  return rtlRender(ui, { wrapper: Wrapper, ...renderOptions });
};

export * from "@testing-library/react";

export * from "@testing-library/jest-dom";
// override render method
export { render };

我的测试:

import Post from "./Post";
import { render, screen } from "../../../utils/test-utils";
import userEvent from "@testing-library/user-event";

describe("Post", () => {
  let initialState;
  beforeEach(() => {
    initialState = {
      _id: "1234",
      title: "post title",
      message: "post message",
      creator: "post creator",
      tags: ["postTag", "postTag"],
      selectedFile: "path/to/file",
      likeCount: 0,
      createdAt: "2022-07-20T23:54:25.251Z",
    };
  });

  test("should increment post likes when like button clicked", () => {
    render(<Post post={initialState} />, { initialState });

    const postLikeButton = screen.getByRole("button", { name: /Like/i });
    userEvent.click(postLikeButton);
    const clickedPostLikeButton = screen.getByRole("button", {
      name: /Like 1/i,
    }).textContent;

    // expect().toHaveBeenCalled();
    expect(clickedPostLikeButton).toBe(100);
  });
});

测试错误:

TestingLibraryElementError: Unable to find an accessible element with the role "button" and name `/Like 1/i`

这意味着在测试中单击then按钮时没有调度该操作。
更新:
该按钮来自MUI库:

import { Button } from "@material-ui/core";

post prop从其父组件Posts传递:

import React from "react";
import { useSelector } from "react-redux";

import { Grid, CircularProgress } from "@material-ui/core";
import Post from "./Post/Post";
import useStyles from "./styles";

const Posts = ({ setCurrentId }) => {
  const posts = useSelector((state) => state.posts);
  const classes = useStyles();

  return !posts.length ? (
    <CircularProgress />
  ) : (
    <Grid
      className={classes.container}
      container
      alignItems="stretch"
      spacing={3}
    >
      {posts.map((post, index) => (
        <Grid key={index} item xs={12} sm={6}>
          <Post key={post.id} post={post} setCurrentId={setCurrentId} />
        </Grid>
      ))}
    </Grid>
  );
};

export default Posts;

此外,当使用UI时,所有这些工作都很好,它只是在React测试库中测试按钮onClick似乎不发送likePosts

mwg9r5ms

mwg9r5ms1#

你试过redux-mock-store吗?

import configureStore from 'redux-mock-store'
const mockStore = configureStore()
const store = mockStore(reducers) // add your reducers here

// ...
render(
    <Provider store={store}>
        {children}
    </Provider>
)

相关问题