标签: react-testing-library

考虑使用“jsdom”测试环境

我有这个简单的测试:

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

import Button from '.'

describe('Button', () => {
  it('renders button without crashing', () => {
    const label = 'test'

    render(<Button label={label} />)
  })
})

Run Code Online (Sandbox Code Playgroud)

我有一个jest.config.json包含此内容的

{
  "setupFilesAfterEnv": [
    "<rootDir>/lib/settings/setupTests.ts"
  ]
}
Run Code Online (Sandbox Code Playgroud)

我的setupTests.ts我有

import '@testing-library/jest-dom'
Run Code Online (Sandbox Code Playgroud)

当我运行npm run test(刚刚运行jest)时,出现以下错误:

下面的错误可能是由于使用了错误的测试环境导致的,参见 https://jestjs.io/docs/configuration#testenvironment-string

考虑使用“jsdom”测试环境。

我做错了什么?这在升级之前曾经有效。

javascript typescript reactjs react-testing-library

84
推荐指数
2
解决办法
9万
查看次数

React 测试库在 React 18 中给出 ReactDOM.render 的控制台错误

更新到 React 18 或从 创建新的 React 18 应用程序后create-react-app,当我运行该yarn test命令时,它会为任何测试中使用的console.error每个方法发出警告,如下所示:render

console.error
警告:ReactDOM.render 在 React 18 中不再支持。请改用 createRoot。在您切换到新 API 之前,您的应用程序的行为就像运行 React 17 一样。了解更多信息:https ://reactjs.org/link/switch-to-createroot

如屏幕截图所示: 反应测试库警告

由于 React 测试库目前似乎不支持 React 18 方法。

unit-testing reactjs jestjs react-dom react-testing-library

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

如何使用 react-testing-library 测试锚点的 href

我正在尝试测试我的锚标签。一旦我点击它,我想看看它是否window.location.href是我所期望的。

我尝试渲染锚点,单击它,然后进行测试window.location.href

test('should navigate to ... when link is clicked', () => {
  const { getByText } = render(<a href="https://test.com">Click Me</a>);

  const link = getByText('Click Me');

  fireEvent.click(link);

  expect(window.location.href).toBe("https://www.test.com/");
});
Run Code Online (Sandbox Code Playgroud)

我期待测试通过,但 window.location.href 只是"http://localhost/"意味着它没有因任何原因得到更新。我什至尝试用 包装我的期望await wait,但这也不起作用。我找不到关于使用react-testing-library. 也许有比我正在做的更好的方法来测试它们。???

anchor href reactjs jestjs react-testing-library

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

react-testing-library:调试输出的某些部分不可见

我正在使用 react jest 和 react 测试库来测试我的组件。我正面临一个奇怪的问题。我正在使用来自测试库的渲染进行调试返回。

test('component should work', async () => {
  const { findByText, debug } = render(<MyComponent />);
  const myElement = await findByText(/someText/i);
  debug();

});
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

正如您在屏幕截图中看到的那样,缺少父项的不完整开发和结束标签。

javascript reactjs jestjs react-testing-library

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

如何解决testing-library-react中的“update was not returned in act()”警告?

我正在使用一个有副作用的简单组件。我的测试通过了,但我收到警告Warning: An update to Hello inside a test was not wrapped in act(...).

我也不知道这是否waitForElement是编写此测试的最佳方法。

我的组件

export default function Hello() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
      setPosts(response.data);
    }

    fetchData();
  }, []);

  return (
    <div>
      <ul>
        {
          posts.map(
            post => <li key={post.id}>{post.title}</li>
          )
        }
      </ul>
    </div>
  )
}

Run Code Online (Sandbox Code Playgroud)

我的组件测试

import React from 'react';
import {render, cleanup, act } from '@testing-library/react';
import mockAxios from …
Run Code Online (Sandbox Code Playgroud)

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

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

如何使用jest和react-testing-library测试元素的不存在?

我有一个组件库,我正在为使用Jest和react-testing-library编写单元测试.基于某些道具或事件,我想验证某些元素没有被渲染.

getByText,getByTestId等扔在错误react-testing-library如果未找到该元素,导致测试的前失效expect功能火灾.

你如何使用react-testing-library测试不存在于jest中的东西?

reactjs jestjs react-testing-library

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

在 React 测试库中发现多个元素错误

我在查询时遇到问题,我正在尝试获取两个无线电输入,其中之一没有任何问题,但另一个反应测试库引发了错误:It Found multiple elements with the role "radio" and name /to/i:

查询

test('Render form with default items', () => {
  const handleUpdateValue = jest.fn();
  const handleNextStep = jest.fn();
  render(
    <Form
      handleNextStep={handleNextStep}
      updateValue={handleUpdateValue}
      transferFundsValues={{}}
    />
  );

  const amountInput = screen.getByLabelText(/amount/i);
  const fromRadio = screen.getByLabelText(/from/i);
  const toRadio = screen.getByLabelText(/to/i);
  const messageInput = screen.getByLabelText(/message/i);

  const continueButton = screen.getByRole('button', { name: /continue/i });
  const cancelButton = screen.getByRole('button', { name: /cancel/i });

  // If no value has been entered to the inputs, the continue …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs react-testing-library

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

如何使用 React 测试库通过包含 html 标签的文本字符串进行查询?

当前工作解决方案

使用这个 html:

<p data-testid="foo">Name: <strong>Bob</strong> <em>(special guest)</em></p>
Run Code Online (Sandbox Code Playgroud)

我可以使用React 测试库 getByTestId方法来查找textContent

expect(getByTestId('foo').textContent).toEqual('Name: Bob (special guest)')

Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

我想简单地使用这个 html:

expect(getByTestId('foo').textContent).toEqual('Name: Bob (special guest)')

Run Code Online (Sandbox Code Playgroud)

并像这样使用React Testing LibrarygetByText方法:

expect(getByText('Name: Bob (special guest)')).toBeTruthy()
Run Code Online (Sandbox Code Playgroud)

但这不起作用。

所以,这个问题……

有没有一种更简单的方法来使用 React 测试库来查找带标签的文本内容字符串?

unit-testing reactjs jestjs react-testing-library

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

如何使用 Jest 使用新的 React Router Hooks 模拟 history.push

我正在尝试history.push在新useHistory钩子上模拟react-router并使用@testing-library/react. 我只是像这里的第一个答案一样嘲笑模块:How to test components using new react router hooks?

所以我在做:

//NotFound.js
import * as React from 'react';
import { useHistory } from 'react-router-dom';


const RouteNotFound = () => {
  const history = useHistory();
  return (
    <div>
      <button onClick={() => history.push('/help')} />
    </div>
  );
};

export default RouteNotFound;
Run Code Online (Sandbox Code Playgroud)
//NotFound.js
import * as React from 'react';
import { useHistory } from 'react-router-dom';


const RouteNotFound = () => {
  const history = useHistory(); …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-router react-router-dom react-testing-library

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

如何在react-testing-library中获取具有“name”属性的元素

我正在使用反应测试库和笑话来测试我的反应应用程序。

我想知道如何在react-testing-library中获取具有“name”属性的元素。

例如,在下面的页面中,是否可以通过“userName”获取此元素?

<input type="text" name="userName" />
Run Code Online (Sandbox Code Playgroud)

或者我应该设置data-testId到元素并使用getByTestId方法?

return (
  <div>
    <input type="text" name="userName" />
  </div>
)
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library

34
推荐指数
3
解决办法
6万
查看次数