标签: react-testing-library

如何在反应测试库中设置状态

概述:

  • 之前用 Enzyme 测试我重构过脚本测试,现在想用@testing-library/react

问题:

  • 我在@testing-library/react 中找不到 setState 的解决方案

setstate react-testing-library

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

错误:当我在 React 中尝试使用 Jest 进行测试时,无法找到包含文本的元素

我是测试新闻,这是我的问题

我有那个简单的登录组件:

import React, { useState } from "react";

export default function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  function handleLogin(event) {
    event.preventDefault();
    console.log(email, password);
  }

  return (
    <form data-testid="login-form" onSubmit={handleLogin}>
      <input
        data-testid="useremail"
        type="email"
        placeholder="Email"
        value={email}
        onChange={event => setEmail(event.target.value)}
      />

      <input
        data-testid="userpassword"
        type="password"
        placeholder="Password"
        value={password}
        onChange={event => setPassword(event.target.value)}
      />
      <button onClick={handleLogin}>login</button>
    </form>
  );
}

Run Code Online (Sandbox Code Playgroud)

我在这里我的测试尝试:

import React from "react";
import Login from "../pages/Login";

import { render, fireEvent } from "@testing-library/react";

describe("Login component", () => { …
Run Code Online (Sandbox Code Playgroud)

testing tdd reactjs jestjs react-testing-library

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

fireEvent.keyDown 在我的 Jest + React 测试库测试中没有按预期工作

在我当前的 React 项目中,我正在测试一个组件,其中包括Material UI 中的Dialog 组件作为子组件。

假设它必须onClose()在用户按下Esc键时运行该功能。我手动测试了它,它运行得非常好。现在我正在做同样的测试,这次使用Jest + React Testing Library。你可以看到下面的代码:

fireEvent.keyDown(container, {
      key: "Escape",
      code: "Escape",
      keyCode: 27,
      charCode: 27
    });
Run Code Online (Sandbox Code Playgroud)

并且测试没有通过。经过一些调试后,我意识到该事件实际上已被触发,但由于某种原因并未对<Dialog/>组件产生影响。

所以我确实在 Google Chrome 上运行了该组件,并使用以下代码从开发工具控制台触发了相同的事件:

document.dispatchEvent(
    new KeyboardEvent(
        "keydown", {     
            key: "Escape",
            code: "Escape",
            keyCode: 27,
            charCode: 27
        }
    )
);
Run Code Online (Sandbox Code Playgroud)

......它也不起作用。

我该怎么做才能通过此测试?

reactjs jestjs material-ui react-testing-library

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

如何使用 React 测试库测试 Material UI 选择组件

我正在使用反应测试库进行组件测试。材质 UI 选择选项在弹出窗口中呈现。调试不列出选项。在选择选项的情况下如何触发点击事件。

以下是我选择的组件。

import TextField from '@material-ui/core/TextField';
import { MenuItem } from '@material-ui/core';

<TextField
  select
  id="fruit"
  inputProps={{ id: "fruit" }}
  SelectProps={{
    SelectDisplayProps: {
      'data-testid': "fruit"
    }
  }}
  fullWidth
  variant="outlined"
  {...errors}
>
  {options.map(option => (
    <MenuItem key={option[valueFieldName]} value={option[valueFieldName]}>
      {option[labelFieldName]}
    </MenuItem>
  ))}
</TextField>
Run Code Online (Sandbox Code Playgroud)

什么查询选择器应该用于 onclick 事件。

这是 debug() 记录该字段的方式

    <div class="MuiFormControl-root MuiTextField-root MuiFormControl-fullWidth">
  <label
    class="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-formControl MuiInputLabel-animated MuiInputLabel-outlined"
    data-shrink="false"
    for="fruit"
    id="fruit-label"
  >
    Action on failure
  </label>
  <div class="MuiInputBase-root MuiOutlinedInput-root MuiInputBase-fullWidth MuiInputBase-formControl">
    <div
      aria-haspopup="listbox"
      aria-labelledby="fruit-label fruit"
      class="MuiSelect-root MuiSelect-select MuiSelect-selectMenu MuiSelect-outlined MuiInputBase-input …
Run Code Online (Sandbox Code Playgroud)

testing reactjs material-ui react-testing-library

8
推荐指数
1
解决办法
4554
查看次数

React - Jest - 测试 preventDefault Action

我不知道如何测试按键按下事件并防止默认。测试到达代码但从preventDefault未被调用:Received number of calls: 0

反应组件- App.js

  const onKeyDown = e => {
      console.log("==== TEST REACHED HERE ====")
      e.preventDefault(); // NEVER CALLED ???
  };
  useEffect(() => {
    document.addEventListener("keydown", onKeyDown, false);
    return () =>
      document.removeEventListener("keydown", onKeyDown, false);
  }, []);
Run Code Online (Sandbox Code Playgroud)

单元测试

it("should prevent default action on key down", () => {
   const { getByRole } = render(<App {...props} />);
   const grid = getByRole("app");
   const mockEvent = { preventDefault: jest.fn() };
   fireEvent.keyDown(grid, mockEvent);
   expect(mockEvent.preventDefault).toHaveBeenCalledTimes(1);
});
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

unit-testing reactjs jestjs react-testing-library

8
推荐指数
2
解决办法
1445
查看次数

如何使用 react-testing-library 和 framer-motion 测试鼠标移动拖放

我正在尝试使用 react-testing-libary 测试拖放功能。拖放功能来自 framer-motion 并且代码在 reacy 中。据我了解,它使用 mousedown、mousemove 和 mouseup 事件来执行此操作。我想测试以下基本组件的拖放功能:

export const Draggable: FC<DraggableInterface> = ({
  isDragging,
  setIsDragging,
  width,
  height,
  x,
  y,
  radius,
  children,
}) => {
  return (
      <motion.div
        {...{ isDragging }}
        {...{ setIsDragging }}
        drag
        dragConstraints={{
          left: Number(`${0 - x}`),
          right: Number(
            `${width - x}`,
          ),
          top: Number(`${0 - y}`),
          bottom: Number(
            `${height - y}`,
          ),
        }}
        dragElastic={0}
        dragMomentum={false}
        data-test-id='dragabble-element'
      >
        {children}
      </motion.div>
  );
};
Run Code Online (Sandbox Code Playgroud)

我有一个测试片段如下:

it('should drag the node to the new position', async () => …
Run Code Online (Sandbox Code Playgroud)

drag-and-drop mousemove reactjs react-testing-library framer-motion

8
推荐指数
1
解决办法
4794
查看次数

类型错误:预期容器是元素、文档或文档片段,但得到字符串

我正在尝试使用 RTL 运行以下测试用例,并且测试失败并出现错误“TypeError:预期容器为元素、文档或文档片段但得到字符串。”。我尝试寻找解决方案,但找不到。

describe("Feedback Commponent",()=>{
  it('should throw error when feedback textbox is empty', () => {
    const { getByLabelText} = render(<Contact />);

    fireEvent.change(getByLabelText('Feedback'), {
      target: { value: '' },
    });

    fireEvent.blur(getByLabelText('Feedback'));
    debug();

    expect(getByTestId('feedback-error')).toBe(
      'Please Enter Your Feedback'
    );
  });
});
Run Code Online (Sandbox Code Playgroud)

上面的代码片段假设测试反馈表单,具体来说只是反馈文本框,当它是空的并且当用户从文本框中失去焦点时,应该会出现一个错误,指出“请输入您的反馈”。

react-testing-library

8
推荐指数
2
解决办法
4356
查看次数

停止测试库的巨大错误输出

我喜欢testing-library,在 React 项目中使用了很多,我现在正尝试在 Angular 项目中使用它 - 但我一直在努力解决巨大的错误输出,包括渲染的 HTML 文本。这不仅通常没有帮助(我找不到一个元素,这是它不是的 HTML );但如果您在调试模式下运行,它通常会在有趣的行之前被截断。

我只是将它作为一个库添加到标准的 Angular Karma+Jasmine 设置旁边。

如果 HTML 输出导致我的控制台窗口假脱机很长时间,我敢肯定你会说我正在测试的组件太大了,但是我在量角器中有很多集成测试,而且它们太慢了:(。

react-testing-library angular-testing-library

8
推荐指数
2
解决办法
3119
查看次数

如何使用反应测试库模拟 ResizeObserver 以在单元测试中工作

如果有人可以提供帮助,我有一个自定义钩子,它使用 ResizeObserver 来更改组件的宽度。我的问题是,当我去运行我的单元测试时,它破坏了我的所有测试,查看快照时它没有渲染 dom 中的所有元素。在我实现 ResizeObserver 之前,它一直在工作。有谁知道我是否有一种方法可以开玩笑。将 ResizeObserver 模拟为未定义。或者其他建议。

import * as React from 'react';
import ResizeObserver from 'resize-observer-polyfill';

const useResizeObserver = (ref: { current: any }) => {
    const [dimensions, setDimensions] = React.useState<DOMRectReadOnly>();
    React.useEffect(() => {
        const observeTarget = ref.current;
        const resizeObserver = new ResizeObserver((entries) => {
            entries.forEach((entry) => {
                setDimensions(entry.contentRect);
            });
        });
        resizeObserver.observe(observeTarget);
        return () => {
            resizeObserver.unobserve(observeTarget);
        };
    }, [ref]);
    return dimensions;
};

export default useResizeObserver;



import { render, screen, waitFor } from '@testing-library/react';
import userEvent from …
Run Code Online (Sandbox Code Playgroud)

unit-testing window-resize reactjs jestjs react-testing-library

8
推荐指数
5
解决办法
6127
查看次数

使用 userEvent.click 错误的 act() 警告响应测试库

我有几个用 Jest 和 React 测试库编写的测试。它们都模拟获取并使用 userEvent.click 调用来触发发出获取请求的提交按钮。组件中的状态得到更新,我做出断言。我正在使用 useEffect 挂钩来填充数据数组,但它仅在初始加载时运行,因为我向它传递了一个空的依赖项数组。目前我所有的测试都通过了。如果我一起运行它们,我会得到一个错误的 act() 错误,该错误源于 useEffect:

Warning: It looks like you're using the wrong act() around your test interactions.
Be sure to use the matching version of act() corresponding to your renderer:

// for react-dom:
import {act} from 'react-dom/test-utils';
// ...
act(() => ...);

// for react-test-renderer:
import TestRenderer from react-test-renderer';
const {act} = TestRenderer;
// ...
act(() => ...);
Run Code Online (Sandbox Code Playgroud)

但是,当我单独运行其中一个时,我没有收到警告。我可以单独运行其中任何一个,并且不会收到任何警告。仅当我同时运行两个或多个测试时,我才会收到警告。

我的测试是:

Warning: It looks like you're using the wrong act() around your test …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library

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