【问题标题】:react testing library Redux with thunk testing, action not being dispatched反应测试库 Redux 与 thunk 测试,动作不被分派
【发布时间】:2023-01-09 15:43:59
【问题描述】:

我正在尝试测试用户单击按钮后是否增加了类似计数器。我正在使用 React 测试库,我在其中找到一个按钮并预制 userEvent.click,这应该在幕后分派一个动作并增加计数器,然后我可以在其中断言新值。

当我手动通过 ui 但无法使测试工作时,这会起作用。

按钮:

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

咚咚动作:

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 LINK 我还添加了 applyMiddleware(thunk) 以支持 thunk when a for a for a connected component

测试工具:

    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 时都工作得很好,它只是在反应测试库中测试按钮 onClick 似乎不发送 likePosts

【问题讨论】:

  • 你能提供Button的代码吗?或者,它是否来自 UI 库? post 来自哪里?请提供mvce
  • @slideshowp2 我更新了这篇文章,希望能有所帮助,谢谢你看看

标签: reactjs redux react-testing-library


【解决方案1】:

你试过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>
)

【讨论】:

    猜你喜欢
    • 2018-06-18
    • 2017-10-15
    • 1970-01-01
    • 2021-08-18
    • 2017-03-03
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多