标签: react-testing-library

某些包装的 act userEvents 会产生“当前测试环境未配置为支持 act”警告

我无法理解行为和用户事件的需求。我已阅读此问题和链接的博客文章,但这不完全是我的情况https://github.com/testing-library/user-event/issues/497 这不会产生任何警告:

等待行为(async()=>等待用户.键盘(“{Enter}”));

但这会导致生成以下警告:

等待 act(async () => 等待 user.hover(等待 screen.findByLabelText("连接目标")));

console.error
  Warning: The current testing environment is not configured to support act(...)

  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)
  at isConcurrentActEnvironment (node_modules/react-dom/cjs/react-dom.development.js:25260:7)
  at warnIfUpdatesNotWrappedWithActDEV (node_modules/react-dom/cjs/react-dom.development.js:27559:12)
  at scheduleUpdateOnFiber (node_modules/react-dom/cjs/react-dom.development.js:25508:5)
  at Object.enqueueSetState (node_modules/react-dom/cjs/react-dom.development.js:14067:7)
  at List.setState (node_modules/react/cjs/react.development.js:354:16)
  at call (node_modules/react-window/src/createListComponent.js:646:12)
  at tick (node_modules/react-window/src/timer.js:26:16)
  at runAnimationFrameCallbacks (node_modules/jsdom/lib/jsdom/browser/Window.js:599:13)
  at Timeout.<anonymous> (node_modules/jsdom/lib/jsdom/browser/Window.js:577:11)
Run Code Online (Sandbox Code Playgroud)

我可以删除产生警告的行为,并且测试保持绿色,但我不想因为我的更改而遇到误报。

reactjs react-testing-library

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

如何使用 @react-testing-library 测试 @mui/x-date-pickers

我尝试使用 DatePicker 组件为我的表单编写测试。我在最新版本 6.2.0 中使用@mui/x-date-pickers。

当我运行下面的测试时,我收到消息:

“TestingLibraryElementError:无法找到文本为:15 的标签”

问题是,如何在测试表中选择特定日期。

任何帮助表示赞赏。

import React, { Component } from "react";
import {
    render,
    fireEvent,
    screen
} from "@testing-library/react";
import "@testing-library/jest-dom";


import {DatePicker} from '@mui/x-date-pickers/DatePicker'; // version 6.2.0
import {  LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';


test("renders DatePicker", async () => {
    const handleChange = jest.fn();
    const { getByLabelText } = render(
        <LocalizationProvider dateAdapter={AdapterDateFns}>
            <DatePicker
                label="Select a date"
                value={null}
                onChange={handleChange}

            />
        </LocalizationProvider>
    );

    const input = getByLabelText('Select a date');
    fireEvent.focus(input); …
Run Code Online (Sandbox Code Playgroud)

datepicker reactjs material-ui react-testing-library

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

如何测试反应测试库中元素是否不可点击

我有一个带有处理程序的元素onClick,可以通过添加pointer-events: none到父级来禁用该元素(父级禁用子级单击)。现在我想测试我的孩子不可点击,我该怎么做?使用userEvent.click抛出错误:

Error: Unable to perform pointer interaction as the element has `pointer-events: none`:
Run Code Online (Sandbox Code Playgroud)

但这正是我想要测试的......

reactjs jestjs react-testing-library

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

使用TypeScript的React Testing Library:设置输入值

我正在使用TypeScript构建一个React应用程序。我使用React Testing Library进行组件测试。

假设您有一个简单的形式,如下所示:

import React from 'react'

function Login({onSubmit}) {
  return (
    <div>
      <form
        onSubmit={e => {
          e.preventDefault()
          const {username, password} = e.target.elements
          onSubmit({
            username: username.value,
            password: password.value,
          })
        }}
      >
        <label htmlFor="username">Username</label>
        <input id="username" />
        <label htmlFor="password">Password</label>
        <input id="password" type="password" />
        <br />
        <button type="submit">Submit</button>
      </form>
    </div>
  )
}

export {Login}
Run Code Online (Sandbox Code Playgroud)

此视频中, Kent(库的创建者)展示了如何测试表单输入。测试看起来像这样:

import React from 'react'
import {renderIntoDocument, cleanup} from 'react-testing-library'
import {Login} from '../login'

afterEach(cleanup)

test('calls onSubmit with username and password', () => {
  const …
Run Code Online (Sandbox Code Playgroud)

unit-testing typescript reactjs htmlelements react-testing-library

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

使用 Material UI 工具提示测试组件时发出警告

这是对https://github.com/mui-org/material-ui/issues/15726#issuecomment-507293766的跟进

我有一个组件Registration,它有一个按钮,默认情况下是禁用的(通过单击复选框控制,接受条款和条件),如果将鼠标悬停在上面,则显示工具提示消息以接受条款和条件。下面是测试结果和测试本身。

? without consent, cannot go further (190ms)

  console.error node_modules/react-dom/cjs/react-dom.development.js:506
    Warning: An update to ForwardRef(Popper) 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 ...
        in ForwardRef(Popper) (created by …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs material-ui react-testing-library

4
推荐指数
2
解决办法
3612
查看次数

React测试库:fireEvent在输入表单上更改时,给定元素没有值设置器

我想在React Testing库中更改Material UI 的值TextField。我已经设置了数据-testid。然后使用getByTestId我拿起输入元素。

// the component
<TextField
  data-testid="input-email"
  variant="outlined"
  margin="normal"
  required
  fullWidth
  id="email"
  label="Email Address"
  name="email"
  value={email}
  onChange={e => setEmail(e.target.value)}
  autoComplete="email"
  autoFocus
/>
// the test 
//...
let userInput = getByTestId('input-email')
fireEvent.change(userInput, { target: { value: 'correct@mail.com' } })
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为它返回错误:The given element does not have a value setter。元素不是e.target.value在其onChange属性上使用吗?我做错了什么?

javascript react-testing-library

4
推荐指数
4
解决办法
1088
查看次数

使用 Jest + react-testing-library 测试异步 `componentDidMount()`

我有一个组件可以异步获取数据 componentDidMount()

componentDidMount() {
  const self = this;

  const url = "/some/path";
  const data = {}
  const config = {
    headers: { "Content-Type": "application/json", "Accept": "application/json" }
  };

  axios.get(url, data, config)
    .then(function(response) {
      // Do success stuff

      self.setState({ .... });
    })
    .catch(function(error) {
      // Do failure stuff

      self.setState({ .... });
    })
  ;
}
Run Code Online (Sandbox Code Playgroud)

我对组件的测试如下所示 -

it("renders the component correctly", async () => {
  // Have API return some random data;
  let data = { some: { random: ["data to be …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs react-testing-library

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

如何使用 Mobx 商店和 Jest 测试组件

我正在尝试使用带有 Jest 和 React-testing-library 的 Mobx 商店来测试我的 React 组件。

问题是我不知道如何为测试注入我的商店。


这是我的简化代码。

StaffInfo.js(组件)

import React, { useState } from "react";
import { observer, inject } from "mobx-react";

const StaffInfo = props => {
   const store = props.instituteStore;
   const [staffs, setStaffs] = useState(store.staffs);

   return (
      <div>
         ....
      </div>
   );
}

export default inject(rootStore => ({
    instituteStore : rootStore.instituteStore
}))(observer(StaffInfo));
Run Code Online (Sandbox Code Playgroud)


index.js(根存储)

import LoginStore from "./LoginStore";
import InstituteStore from "./InstituteStore";

class RootStore {
    constructor(){
        this.loginStore = new LoginStore (this);
        this.instituteStore = new InstituteStore(this);
    } …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs mobx react-testing-library

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

Jest + React-testing-library - 等待模拟的异步函数完成

componentDidMount()触发了对异步函数的调用,但根据该函数的结果,它可能不会导致任何 DOM 更改。有什么办法可以等待该功能在我的测试中完成吗?

这是一个示例 - 单击按钮最初是禁用的。如果 async 函数返回 true,则应启用单击按钮:

    myAsyncFunction.mockImplementation(() => true);
    const {queryByText} = render(<Component />);
    const button = queryByText("Click");
    expect(button).toBeDisabled();
    await waitFor( () => expect(button).not.toBeDisabled() );
    expect(button).not.toBeDisabled();
Run Code Online (Sandbox Code Playgroud)

但如果它返回 false 按钮​​保持禁用状态:

    myAsyncFunction.mockImplementation(() => false);   // async returning different value
    const {queryByText} = render(<Component />);
    const button = queryByText("Click");
    expect(button).toBeDisabled();
    await waitFor( () => {} );                       //        <== **** CODE SMELL ****
    expect(button).toBeDisabled();
Run Code Online (Sandbox Code Playgroud)

第二个测试确实有效,但空的waitFor()被认为是不好的做法。有什么办法可以避免这种情况吗?

jestjs react-testing-library

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

JEST + React 测试库:我应该在测试前使用 beforeAll 渲染我的组件吗?

正如标题所说,我正在使用 RTL + Jest(使用 Create-react-app 设置)。

我的问题是我是否应该在每个测试中使用 beforeAll 预渲染该块内的组件,因此每个测试不必从头开始重新渲染组件,因为我的测试套件总是从相同的基本组件开始。这样做是否有性能改进?

例如,这样做是否有改进

describe("MyComponent", () => {
    beforeAll(() => {
        render(<MyComponent {...props} />);
    });

    it("tests something", () => {
        expect(something).toDoSomething();
    });

    it("tests something else", () => {
        expect(somethingElse).toDoSomethingElse();
    });
});
Run Code Online (Sandbox Code Playgroud)

关于这个(除了不那么冗长和重写组件渲染)?

describe("MyComponent", () => {

    it("tests something", () => {
        render(<MyComponent {...props} />);
        expect(something).toDoSomething();
    });

    it("tests something else", () => {
        render(<MyComponent {...props} />);
        expect(somethingElse).toDoSomethingElse();
    });
});
Run Code Online (Sandbox Code Playgroud)

我应该通过做其他事情来以不同的方式接近我的测试套件吗?这只是个人喜好的问题吗?

我从 Kent C Dodds 的博客中读到了这篇文章,他主要指出它使代码的可读性降低,但没有谈论性能或它是否对测试有任何影响。

testing reactjs jestjs create-react-app react-testing-library

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