标签: react-testing-library

React 测试库 - 检查 ag-grid onGridready 回调是否执行或等待 onGridReady 回调执行

我一直在为我的应用程序编写测试用例。在我的测试用例中,在 ag-grid 准备好之前,如果触发与 ag-grid onGridready 事件 API 相关的任何操作,它会抛出错误,如 api 未定义。因为 onGridready 回调,我们收到网格 API 对象并将其存储在变量中并在组件内部使用。所以我必须等到 ag-grid onGridReady 回调执行然后触发操作。

有没有办法使用测试库检查测试用例中是否执行了 ag-grid onGridready 回调?

或者

如何使用测试库等待测试用例中的 onGridReady 回调执行?

我在 ag-grid 文档中看到了一个使用“酶”的示例。这里我不应该使用酶。这就是为什么尝试使用测试库来实现

请帮我。

reactjs ag-grid react-testing-library

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

测试异常-unstable_flushDiscreteUpdates

我有一个使用 Jest 和 React-testing-library 以及 .tsx 测试文件(TypeScript)的测试:

import React from "react";
import { Provider } from 'react-redux';
import { render, screen } from "@testing-library/react";
import Home from "./Home";
describe('Home', () => {
    test("renders Programs without crashing", async () => {
        const storeFake = (state: any) => ({
            default: () => { },
            subscribe: () => { },
            dispatch: () => { },
            getState: () => ({ ...state })
        });
        const store = storeFake({}) as any;
        const { getByAltText } = …
Run Code Online (Sandbox Code Playgroud)

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

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

如何在 React 测试库中的多个测试中使用单个渲染?

使用 Jest 和 React 测试库是否可以在多个测试中维护相同的 render() ?我正在构建一个 Trivia 应用程序,并且有一个组件可以在用户完成测验时显示不同的问题。为了测试选择按钮、提交按钮的功能,并检查是否在正确的时间显示正确的屏幕,我需要在测验的不同阶段对同一渲染组件执行测试。例如:

describe("Question Screen", () => {

    it("should render the first question when difficulty button is clicked", async () => {
        render(<TriviaBox/>);
        const btn = screen.getByRole("button", {name: /easy/i});
        fireEvent.click(btn);

        const heading = await screen.findByText("Question 1");
        expect(heading).toBeInTheDocument();
    });

    it("should display the next question when the current question is answered", async () => {
        render(<TriviaBox/>);
        const btn = screen.getByRole("button", {name: /easy/i});
        fireEvent.click(btn);

        const correctAnswer = await screen.findByRole("button", {name: /Nevada/i});
        const submit = await screen.findByRole("button", {name: …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library

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

当表单中所需的输入字段为空时,如何模拟提交处理程序未被调用?

我最近开始使用 Jest 和 React-testing-library 进行测试。但我遇到了一个小问题。我正在测试我的组件,如下所示:

\n
import React, { useState } from 'react';\n\nconst Login = () => {\n  const [username, setUsername] = useState<string>('');\n  const [password, setPassword] = useState<string>('');\n\n  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {\n    event.preventDefault();\n  };\n\n  return (\n    <div>\n      <form onSubmit={handleSubmit} data-testid="loginForm">\n        <label>\n          Username:\n          <input\n            required\n            type="text"\n            data-testid="usernameText"\n            placeholder="e.g. JohnLukeThe3rd"\n            value={username}\n            onChange={(event) => setUsername(event.target.value)}\n            autoFocus\n          />\n        </label>\n        <label>\n          Password:\n          <input\n            required\n            type="password"\n            data-testid="passwordText"\n            placeholder="e.g. \xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2"\n            value={password}\n            onChange={(event) => setPassword(event.target.value)}\n          />\n        </label>\n        <input type="submit" data-testid="loginButton" value="Login" />\n      </form>\n    </div>\n  );\n};\n\nexport …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing reactjs jestjs react-testing-library

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

React 测试库查询需要额外的 waitFor 才能成功

我正在使用React 测试库来测试一个组件,该组件通过 redux thunk 获取 componentDidMount 中的数据,并使用 MSW JS 模拟后端。

我的测试本质上是:

  1. 渲染应用程序
  2. 等待组件的“加载状态/旋转器”清除(在所有 redux thunk 内容成功之后),这通过出现带有文本“Create Card”的按钮来表示
  3. 单击“创建卡片”按钮
  4. 等待 redux thunk stuff 成功创建卡片,类似于 #2
  5. 查询组件以获取已创建卡片的证据
const history = createMemoryHistory()
history.push(`/${DECK_ID}`)

const { getByText } = render(
  <Provider store={store}>
    <Router basename="/games" history={history}>
      <App />
    </Router>
  </Provider>
)

await waitFor(() => getByText('Create Card'))
fireEvent.click(getByText('Create Card'))
await waitFor(() => getByText(`Id: ${NEW_CARD_TYPE_ID}`))
Run Code Online (Sandbox Code Playgroud)

奇怪的是,没有找到“创建卡片”:

TestingLibraryElementError: Unable to find an element with the text: Create Card...
...
      124 |     await waitFor(() => getByText('Create Card')) …
Run Code Online (Sandbox Code Playgroud)

async-await reactjs react-router react-redux react-testing-library

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

如何将react-intl与jest一起使用

我正在使用React测试库,我需要获得文本的翻译,我们在setupTest文件中模拟了react-intl库:

jest.mock('react-intl', () => {
  const reactIntl = require.requireActual('react-intl');
  const intl = reactIntl.createIntl({
    locale: 'en'
  });

  return {
    ...reactIntl,
    useIntl: () => intl
  };
});
Run Code Online (Sandbox Code Playgroud)

但我不知道如何在测试中使用它,有人可以为我提供使用该库进行翻译的完整测试示例吗?我尝试这样做:

let intl = useIntl();
      let i18n = {
        header: intl.formatMessage({
          id: 'header.myHeader',
          defaultMessage: 'header.myHeader'
        })
      };
Run Code Online (Sandbox Code Playgroud)

但有来自语言环境的 intl 消息。

问候。

jestjs react-testing-library

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

为什么 Jest 会抛出“无效的挂钩调用”?

我有一个 Gatsby 网站和一个组件库。运行 Gatsby 站点时,我收到“无效的挂钩调用”错误,并像此处建议的那样添加 Webpack 别名解决了该问题。

\n

现在,在使用 Jest 和 运行测试时,我遇到了类似的“无效挂钩调用”错误react-testing-library:

\n
Error: Uncaught [Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n      1. You might have mismatching versions of React and the renderer (such as React DOM)\n      2. You might be breaking the Rules of Hooks\n      3. You might have more than one copy of React in …
Run Code Online (Sandbox Code Playgroud)

reactjs webpack jestjs react-testing-library react-hooks

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

userEvent.type 包装在 act 中时仅输入最后一个字符

我在用户事件 github 中发现了一个问题,它说它在版本 12.0.1 中已解决,但我使用的是版本 12.1.5,并且不断收到错误。

\n
import React, { Fragment } from "react";\nimport { render, act } from "@testing-library/react";\nimport userEvent from "@testing-library/user-event";\nimport App from "./App";\n\ntest("Gets a code and renders it in a new route", () => {\n  const { getByLabelText } = render(<App />);\n  act(() => {\n    userEvent.type(getByLabelText("Code:"), "12345");\n  });\n  expect(getByLabelText("Code:")).toHaveValue("12345");\n});\n
Run Code Online (Sandbox Code Playgroud)\n
  \xe2\x97\x8f Gets a code and renders it in a new route\n\n    expect(element).toHaveValue(12345)\n\n    Expected the element to have value:\n      12345\n    Received:\n      5\n
Run Code Online (Sandbox Code Playgroud)\n

javascript reactjs jestjs react-testing-library

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

与 Cypress 或 React 测试库集成测试?

我是测试新手,据我了解,集成测试的目的是测试一堆组件以及它们如何相互交互。

但是如果在一个项目中我们同时使用 Cypress 进行端到端测试,同时使用 React 测试库进行单元测试,那么使用哪一个进行集成测试,各有什么优缺点呢?

testing frontend reactjs cypress react-testing-library

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

如何使用react-test-library测试复选框

我正在使用最新版本的 create-react-app (在 package.json 中,“react”:“^17.0.1”)

我正在尝试使用react-test-library来测试一个应用程序,其中检查复选框会增加计数器。我已将问题归结为我能处理的最简单的形式。我试过 keyDown,点击...

文本需要 '2' 并收到 '0' :

组件文件:

import React, { useEffect, useState  } from "react";

function App3() {
  const [counter, setCounter]= useState(0);
  const handleClickInCheckbox = (ev) => {
  setCounter(2)
  };

  return (
    <div className="App">
      <input type="checkbox" onChange={handleClickInCheckbox} id="chkbx" data-testid="ch1" ></input>
      <h1 data-testid="h1" >{counter}</h1>
    </div>
  );
}

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

测试文件:

import React from 'react';
import { render, act,  screen, fireEvent,  getByRole} from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import App from '../App3'

describe ('app', () => { …
Run Code Online (Sandbox Code Playgroud)

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

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