标签: react-testing-library

如何针对不同的屏幕尺寸编写单元测试用例?

我有两个根据屏幕尺寸显示的按钮(对于中屏幕,一个按钮,对于其他屏幕,另一个按钮)。我使用 Material UI 的 MediaQuery 和 theme.breakpoints 来定义屏幕尺寸。

这是我的 UI 代码,我在 React 中使用 Typescript

import React from "react";
import Button from "@material-ui/core/Button";
import useMediaQuery from "@material-ui/core/useMediaQuery";
import { useTheme } from "@material-ui/core/styles";

export default function SimpleCard() {
  const theme = useTheme();
  const isMd = useMediaQuery(theme.breakpoints.only("md"));

  return (
    <div>
      {isMd ? (
        <Button
          data-testid="mediumScreenButton"
          onClick={() => console.log("medium")}
        >
          medium screen
        </Button>
      ) : (
        <Button
          data-testid="otherScreenButton"
          onClick={() => console.log("other")}
        >
          Other screen
        </Button>
      )}
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试代码

import …
Run Code Online (Sandbox Code Playgroud)

unit-testing jestjs material-ui react-testing-library react-hooks

3
推荐指数
1
解决办法
9780
查看次数

模拟react-redux的useSelector和jest,用react测试库进行测试

我正在尝试测试一个使用react-redux 进行状态管理的组件。

为了快速测试,我想模拟 useSelector,如下所示:

const templates = [
  {
    id: ...,
    name: ...,
    ...
  },
  {
    id: ...,
    name: ...,
    ...
  },
]


jest.mock('react-redux', () => ({
  ...jest.requireActual('react-redux'),
  useSelector: jest.fn(),
}));


describe('some awesome description', () => {
  beforeEach(() => {
    useSelector.mockImplementation(callback => callback(templates));
  });
});
Run Code Online (Sandbox Code Playgroud)

但在运行测试时,会失败,如下所示:

TypeError: Cannot read properties of undefined (reading 'ids')

  141 | describe('layouts/TemplatesPanel', () => {
  142 |   beforeEach(() => {
> 143 |     useSelector.mockImplementation(callback => callback(templates));
      |                                                ^
Run Code Online (Sandbox Code Playgroud)

unit-testing reactjs jestjs react-redux react-testing-library

3
推荐指数
1
解决办法
2万
查看次数

简单玩笑测试中返回值无效

我正在测试 React Native 0.68.2/jest 29.0 的组件视图Home。简单的测试用例是从 jest doc 复制的:

\n
import React from 'react';\nimport { NavigationContainer } from '@react-navigation/native';\nimport { render, cleanup, screen, fireEvent } from "@testing-library/react-native";\nimport App from '../App';\n\ndescribe ('App ', () => {\n    //afterEach(cleanup);\n    test ('shall stack screens', async () => {\n        const component = (<NavigationContainer>\n                             <App />\n                            </NavigationContainer>);\n        const {getByText} = render(component);\n\n        await waitFor(() => getByText('AppSplash'));\n        \n\n    })\n})\n
Run Code Online (Sandbox Code Playgroud)\n

这是 App.js:

\n
 import React, {useState, useContext, Component} from 'react';\n import { NavigationContainer } from '@react-navigation/native';\n …
Run Code Online (Sandbox Code Playgroud)

jestjs react-testing-library react-native-testing-library

3
推荐指数
1
解决办法
5731
查看次数

测试 NextJS 和 Jest ReferenceError:TextEncoder 未定义

我在尝试学习如何测试 next.js 应用程序时收到此错误消息我尝试从配置顶部的 utils 导入文本编码器以及测试文件,但没有成功

  ReferenceError: TextEncoder is not defined



  at Object.<anonymous> (node_modules/whatwg-url/lib/encoding.js:2:21)
  at Object.<anonymous> (node_modules/whatwg-url/lib/url-state-machine.js:5:34)
  at Object.<anonymous> (node_modules/whatwg-url/lib/URL-impl.js:2:13)
  at Object.<anonymous> (node_modules/whatwg-url/lib/URL.js:442:14)
  at Object.<anonymous> (node_modules/whatwg-url/webidl2js-wrapper.js:3:13)
  at Object.<anonymous> (node_modules/whatwg-url/index.js:3:34)
  at Object.<anonymous> (node_modules/mongodb-connection-string-url/src/index.ts:1:1)
  at Object.<anonymous> (node_modules/mongodb/src/connection_string.ts:3:1)
  at Object.<anonymous> (node_modules/mongodb/src/mongo_client.ts:11:1)
  at Object.<anonymous> (node_modules/mongodb/src/change_stream.ts:17:1)
  at Object.<anonymous> (node_modules/mongodb/src/index.ts:3:1)
  at Object.<anonymous> (node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js:8:16)
  at Object.<anonymous> (node_modules/mongoose/lib/drivers/node-mongodb-native/index.js:7:18)
  at Object.<anonymous> (node_modules/mongoose/lib/index.js:7:25)
  at Object.<anonymous> (node_modules/mongoose/index.js:8:18)
  at Object.<anonymous> (library/mongoDB.js:15:56)
  at Object.<anonymous> (library/players.js:15:18)
  at Object.<anonymous> (pages/index.js:18:18)
  at Object.<anonymous> (tests/index.test.js:6:53)
Run Code Online (Sandbox Code Playgroud)

玩笑配置文件

const nextJest = require('next/jest')
    const createJestConfig = nextJest({
  dir: './',
})
const …
Run Code Online (Sandbox Code Playgroud)

jestjs next.js react-testing-library

3
推荐指数
1
解决办法
3738
查看次数

如何查找不同元素的 getByRole 可用的属性?

当使用 React 测试库编写单元测试时,我们可以通过元素的角色来访问元素getByRole

例如,如果元素是heading,则它有level选项:

const headingNode = screen.getByRole('heading', { level: 3 });
Run Code Online (Sandbox Code Playgroud)

或者如果是的话radio它有name

 const radioNode = screen.getByRole('radio', { name: 'high'});
Run Code Online (Sandbox Code Playgroud)

我的问题是,在哪里可以找到每种类型的所有可能选项?有这方面的文档吗?没找到。

unit-testing accessibility reactjs jestjs react-testing-library

3
推荐指数
1
解决办法
5113
查看次数

异步 thunk 会在测试中导致警告(包含在 act 中)

当尝试测试调度异步 thunk 的组件时,我收到以下警告。它们是由于测试完成后执行的更新而显示的。

  console.error
    Warning: An update to App inside a test was not wrapped in act(...).
    
    When testing, code that causes React state updates should be wrapped into act(...):
    
    act(() => {
      /* fire events that update state */
    });
    /* assert on the output */
    
    This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
        at App (/home/karlosos/Dev/nokia/playground/testing-redux/src/App.tsx:6:34)
        at Provider (/home/karlosos/Dev/nokia/playground/testing-redux/node_modules/react-redux/lib/components/Provider.js:19:3)
        at Wrapper (/home/karlosos/Dev/nokia/playground/testing-redux/src/testUtils.tsx:11:22)

      at printWarning (node_modules/react-dom/cjs/react-dom.development.js:86:30)
      at error (node_modules/react-dom/cjs/react-dom.development.js:60:7) …
Run Code Online (Sandbox Code Playgroud)

redux react-redux react-testing-library redux-toolkit

3
推荐指数
1
解决办法
978
查看次数

解决 React 测试库中的 act() 警告

我正在尝试测试我的组件并且测试正在通过,但是我不断收到有关在我的终端中更新的状态片段的行为警告:“警告:测试中对 Bird 的更新未包含在 act(...) .”

该警告指的是 const handleRemoveBird = () => { setShowModal(true); };状态更新。

这是否与链接到模态组件的状态有关并且它在测试之外更新?如果是这种情况(或不是),我需要等待/等待什么来修复行为警告?

我的测试:

import { screen, waitFor } from "@testing-library/react";
import user from "@testing-library/user-event";
import { renderWithProviders } from "../utils/utils-for-tests";
import Bird from "../components/Bird";

const modalContainerMock = document.createElement("div");
modalContainerMock.setAttribute("class", "modal-container");
document.body.appendChild(modalContainerMock);

const birdImgMock = jest.mock("../../components/BirdImg", () => {
  return () => {
    return "Bird Img Component";
  };
});

const renderComponent = (bird) => {
  renderWithProviders(<Bird bird={bird} />);
};

const bird = {
  id: "1",
  name: "blue …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs react-testing-library

3
推荐指数
1
解决办法
933
查看次数

由于未知的意外令牌“导出”,玩笑测试失败

我将 tRPC 与 Typescript 和 Next.js 结合使用。直到最近我的测试才失败(我认为我没有碰过它们)。我得到了错误Unexpected token 'export'。我尝试过更改我的jest.config.mjs添加transformIgnorePatterns: ["!node_modules/"]以及babel-jest

\n
   transform: {\n      "^.+\\\\.tsx?$": "ts-jest",\n      "^.+\\\\.(js|jsx)$": "babel-jest",\n      "node_modules/variables/.+\\\\.(j|t)sx?$": "babel-jest"\n    },\n
Run Code Online (Sandbox Code Playgroud)\n

但无济于事:(有人可以帮助我吗?这是我的错误日志。

\n
Test suite failed to run\n\n    Jest encountered an unexpected token\n\n    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.\n\n    Out of the box Jest supports Babel, which will be used …
Run Code Online (Sandbox Code Playgroud)

testing commonjs jestjs es6-modules react-testing-library

3
推荐指数
1
解决办法
1610
查看次数

如何测试根据 prop 更改 CSS 属性的 useEffect 钩子?

p我有一个 TextField 组件,右侧包含一个单元 ( )。我动态地更改了该单元和文本值之间的填充useEffect,但是当我想确保它使用 Cypress 组件测试正确工作时,我阻止了。


import classNames from "classnames";
import { IProps } from "./type";
import styles from "./style.module.css";
import { useEffect, useRef } from "react";

const TextField = ({
  ID,
  value,
  placeholder,
  type,
  rounded,
  outline,
  disabled,
  icon,
  unit,
  onChange,
  onFocus,
  onBlur,
}: IProps) => {
  const unitRef = useRef<HTMLParagraphElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // How to test this hook
  useEffect(() => {
    if (unitRef.current && inputRef.current) {
      const unitWidth = unitRef.current.getBoundingClientRect().width;
      inputRef.current.style.paddingRight = `${unitWidth …
Run Code Online (Sandbox Code Playgroud)

reactjs cypress react-testing-library

3
推荐指数
1
解决办法
144
查看次数

在使用Jest和react-testing-library进行测试时如何设置组件的本地状态?

使用AirBnB的酶,我们可以设置组件的状态:

const loginComponent = shallow(<Login />);
loginComponent.setState({ error: true });
Run Code Online (Sandbox Code Playgroud)

我想使用react-testing-library做同样的事情。

谢谢!

javascript unit-testing reactjs jestjs react-testing-library

2
推荐指数
1
解决办法
607
查看次数