标签: react-testing-library

使用react-testing-library时用mocha和chai进行断言?

我想将 React 测试库添加到使用 mocha 和 chai 进行单元测试的项目中。在编写断言时我有点困惑,大多数例子都使用 jest 和 jest-dom。我真的很热衷于使用像toBeInTheDocumentor 这样的断言toHaveTextContent

我想知道是否有一个 chai 插件可以替代 jest-dom?或者您找到了哪些使用 React 测试库与 mocha 和 chai 的替代解决方案?

mocha.js chai reactjs react-testing-library jest-dom

5
推荐指数
1
解决办法
1581
查看次数

Jest 单元测试 onClick 事件

我有一个组件,想用反应玩笑对其进行单元测试...我想测试 onClick 事件..我已经尝试了很多情况,但它们没有涵盖 onClick 语句

这是我的组件

export default class HeaderCreate extends Component {

  render() {
    const { name, description, closeRightSection } = this.props;
    return (
      <div className="header">
        <h1 className="header-text" title={name} data-testid="header">{name}</h1>
        <p data-testid= "description-para">{description}</p>

        <Tooltip title="Close Section">
          <div className="icon-close">
            <i className="material-icons" onClick={() => closeRightSection()} data-testid="id">close</i>
          </div>
        </Tooltip>
      </div>
    )
  }
}; 
Run Code Online (Sandbox Code Playgroud)

这是我的 test.js

import React from 'react'
import { render } from "@testing-library/react";

import HeaderCreate from '../components/createHeader';

test("render header correctly", () => {
    const { getByTestId } = render(<HeaderCreate name="My …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing onclicklistener reactjs react-testing-library

5
推荐指数
1
解决办法
4万
查看次数

在react-testing-library中基于动态导入的svg测试图标

这是我的第一个问题,我编码才一年,所以请耐心等待。我在网站上寻找类似的问题,但找不到任何对我有用的东西。

我创建了一个 Icon 组件,在其中动态导入请求的 SVG。我第一次使用这个运行良好的解决方案,但是当我尝试使用反应测试库和快照测试这个组件时,我意识到快照始终是在未导入任何内容时返回的跨度。我首先认为它与 useRef() 的使用有关,因为我看到人们说 refs 不适用于 Jest,所以我将 Icon 组件更改为:

const Icon: FC<IconProps> = ({ type, onClick, tooltip, className }: IconProps) => {

  const [IconProps, setIconProps] = useState({
    className: className || 'icon'
  });
  const tooltipDelay: [number, number] = [800, 0];
  useEffect(() => {
    setIconProps({ ...IconProps, className: className || 'icon' });
  }, [className]);

  const SVG = require(`../../svg/${type}.svg`).default;
  const spanClassName = "svg-icon-wrapper";
  if (typeof SVG !== 'undefined') {
    if (tooltip) {
      return (
        (<Tooltip title={tooltip.title} delay={tooltip.delay ? tooltipDelay …
Run Code Online (Sandbox Code Playgroud)

svg dynamic-import typescript reactjs react-testing-library

5
推荐指数
0
解决办法
1381
查看次数

测试单选按钮组的箭头键键盘导航

我正在用来testing-library测试单选按钮组的实现。我可以测试将tab焦点设置到第一个单选选项,但我无法正确测试箭头键导航。

这是我的测试:

import {
  getByLabelText,
  render,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
...

test('arrow key navigation', () => {
  const {container} = render(
    <div>
      <label htmlFor="apple">
        Apple
        <input type="radio" value="apple" id="apple" name="fruit"/>
      </label>
      <label htmlFor="banana">
        Banana
        <input type="radio" value="banana" id="banana" name="fruit"/>
      </label>
    </div>
  )

  const apple = getByLabelText(container, 'Apple')
  const banana = getByLabelText(container, 'Banana')

  userEvent.tab()
  expect(apple).toHaveFocus() // This assertion passes
  userEvent.keyboard('{arrowright}')
  expect(banana).toHaveFocus() // This assertion fails
})

Run Code Online (Sandbox Code Playgroud)

reactjs react-testing-library

5
推荐指数
1
解决办法
3365
查看次数

当发现多个元素时如何过滤 getByLabelText 查询?

如何过滤getByLabelText查询,如果它抛出类型错误:TestingLibraryElementError: Found multiple elements with the text of: /to/i,我有以下 HTML 结构,其中有一些嵌套标签:

当前的 HTML 结构

<div class="ant-row ant-form-item ant-radio-group-cards" style="row-gap: 0px;">
    <div class="ant-col ant-form-item-label">
        <!-- <label> with "To" text -->
        <label for="transferFunds_to" class="ant-form-item-required" title="To">To</label> 
    </div>
    <div class="ant-col ant-form-item-control">
        <div class="ant-form-item-control-input">
            <div class="ant-form-item-control-input-content">
                <!-- Other <label> with "To" text here -->
                <label class="ant-radio-button-wrapper">
                    <span class="ant-radio-button"><input id="transferFunds_to" type="radio" class="ant-radio-button-input" value="" /><span class="ant-radio-button-inner"></span></span>
                    <span>
                        <li class="ant-list-item">
                            <div class="ant-list-item-meta">
                                <div class="ant-list-item-meta-avatar">
                                    <svg width="1em" height="1em" viewBox="0 0 16 16" fill="none" style="font-size: 48px;"></svg> …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing reactjs jestjs react-testing-library

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

具有 openApi 后端的模拟服务人员

我正在使用MSWOpenAPI 后端包。我想模拟展位浏览器服务器和测试服务器。我有 OpenAPI 定义可用的形式,我为 RTK 查询生成 generated.ts (超出了这个问题的范围)。我想使用 OpenAPI 规范将其与 OpenAPI 后端一起使用,并为浏览器和测试生成 MSW 休息工作人员。

接下来是设置:

索引.tsx

import worker from './mocks/browser';

if (process.env.NODE_ENV === 'development') {
    worker.start();
}
Run Code Online (Sandbox Code Playgroud)

模拟/浏览器.ts

import { setupWorker, rest } from 'msw';

import { OpenAPIBackend } from 'openapi-backend';
import type { Document } from 'openapi-backend';
import definition from './api.json';


// create our mock backend with openapi-backend
const api = new OpenAPIBackend({ definition: definition as Document });
api.register('notFound', (c, res, ctx) => res(ctx.status(404)));
api.registerHandler('notImplemented', …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs openapi react-testing-library msw

5
推荐指数
1
解决办法
2719
查看次数

无法模拟 useEffect 中的函数

我有一个自定义挂钩,如下所示

export const useUserSearch = () => {
  const [options, setOptions] = useState([]);
  const [searchString, setSearchString] = useState("");
  const [userSearch] = useUserSearchMutation();
  useEffect(() => {
    if (searchString.trim().length > 3) {
      const searchParams = {
        orgId: "1",
        userId: "1",
        searchQuery: searchString.trim(),
      };
      userSearch(searchParams)
        .then((data) => {
          setOptions(data);
        })
        .catch((err) => {
          setOptions([]);
          console.log("error", err);
        });
    }
  }, [searchString, userSearch]);
  return {
    options,
    setSearchString,
  };
};
Run Code Online (Sandbox Code Playgroud)

我想测试这个钩子,但无法模拟userSearch在 useEffect 内部调用的函数。有人可以帮忙吗?这是我的测试

it('should set state and test function', async () => {
    const …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs react-testing-library

5
推荐指数
1
解决办法
2209
查看次数

如何使用 Redux-RTK 设置 React-Testing-Library(在打字稿中)

我正在使用 Redux 来管理组件的状态。虽然它适用于我的应用程序,但我无法让它在我的反应测试库测试套件中工作。

好消息是,这里Redux-RTK有设置他们的库的文档(示例如下)。坏消息是,我很难将其转换为也很难做任何其他需要做的事情来使其在测试中实际工作。react-testing-library jsxtsx

还原文档

这是他们提供的包装器,用于让组件(在测试中)访问... redux 存储/行为?

// testing-utils.ts

import React from 'react'
import { render as rtlRender } from '@testing-library/react'
import { configureStore } from '@reduxjs/toolkit'
import { Provider } from 'react-redux'
// Import your own reducer
import alertReducer from '../alertSlice'

function render(
 ui,
  {
    preloadedState,
    store = configureStore({
      reducer: { alert: alertReducer },
      preloadedState,
    }),
    ...renderOptions
  } = {}
) {
  function Wrapper({ children …
Run Code Online (Sandbox Code Playgroud)

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

5
推荐指数
0
解决办法
1249
查看次数

玩笑测试返回一个空主体

当我进行debug()此测试时,它返回一个空主体。有谁知道我哪里出错了?它应该呈现一个带有网格的组件以供用户输入。以下是propTypes该组件的信息:

CompanyInfoInputs.propTypes = {
  onChange: PropTypes.func.isRequired,
  loading: PropTypes.bool.isRequired,
  fieldValues: PropTypes.object.isRequired,
  dropdownError: PropTypes.bool
};

CompanyInfoInputs.defaultProps = {
  dropdownError: false
};

NewCompanyModal.propTypes = {
  open: PropTypes.bool.isRequired,
  handleClose: PropTypes.func.isRequired
};

export default NewCompanyModal;
Run Code Online (Sandbox Code Playgroud)

这是目前的测试。

import React from 'react';
import { render } from '@testing-library/react';
import { ApolloProvider } from '@apollo/react-hooks';
import { client } from '../../../../../client';
import NewCompanyModal from '../../../../../components/reusable_components/company/NewCompanyModal';

const RComponent = props => {
  const companyModalOpen = true;
  const loading = false;
  return (
    <ApolloProvider client={client}>
      <NewCompanyModal …
Run Code Online (Sandbox Code Playgroud)

testing reactjs jestjs react-testing-library

5
推荐指数
0
解决办法
1599
查看次数

React、Jest 和测试库:TypeError:使用 findBy(例如 findByAltText)时无法读取 null 的属性“createEvent”

问题

当我尝试使用 Jest、React 和测试库运行测试时,npm test出现以下错误:

错误

/node_modules/react-dom/cjs/react-dom.development.js:3905
      var evt = document.createEvent('Event');
                         ^

TypeError: Cannot read property 'createEvent' of null
    at Object.invokeGuardedCallbackDev (/node_modules/react-dom/cjs/react-dom.development.js:3905:26)
    at invokeGuardedCallback (/node_modules/react-dom/cjs/react-dom.development.js:4056:31)
    at flushPassiveEffectsImpl (/node_modules/react-dom/cjs/react-dom.development.js:23543:11)
    at unstable_runWithPriority (/node_modules/scheduler/cjs/scheduler.development.js:468:12)
    at runWithPriority$1 (/node_modules/react-dom/cjs/react-dom.development.js:11276:10)
    at flushPassiveEffects (/node_modules/react-dom/cjs/react-dom.development.js:23447:14)
    at Object.<anonymous>.flushWork (/node_modules/react-dom/cjs/react-dom-test-utils.development.js:992:10)
    at Immediate.<anonymous> (/node_modules/react-dom/cjs/react-dom-test-utils.development.js:1003:11)
    at processImmediate (node:internal/timers:464:21)
/node_modules/react-dom/cjs/react-dom.development.js:3905
      var evt = document.createEvent('Event');
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-dom react-testing-library

5
推荐指数
1
解决办法
7956
查看次数