标签: react-testing-library

在react-testing-library中按id查找元素

我正在使用react-testing-libarary来测试我的反应应用程序.出于某种原因,我需要能够找到元素,id而不是data-testid.在文档中无法实现此目的.

有没有办法实现这个目标?

我的渲染输出为:

const dom = render(<App />);
Run Code Online (Sandbox Code Playgroud)

我正在寻找符合以下内容的东西:

const input = dom.getElemenById('firstinput');
//or 
const input = dom.getById('firstinput');
Run Code Online (Sandbox Code Playgroud)

reactjs react-testing-library

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

React testing-library - 测试在第一个 useEffect 挂钩中设置状态的承诺

我有一个 useEffect 钩子,它在安装组件时加载,如下所示:

useEffect(() => {
   listFiles().then(keys => {
      setKeys(keys)
      console.log(keys)
   }).catch(err => {
        showFail(err.message)
   })
}, [])
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用反应测试库来测试该函数,只需使用渲染函数:

beforeEach(() => {
  render(<Dashboard />)
})
Run Code Online (Sandbox Code Playgroud)

但是,当我运行任何解决承诺并设置状态的测试时:

jest.mock('../utils/storage', () => ({
    listFiles: jest.fn(() => Promise.resolve([])),
}))
Run Code Online (Sandbox Code Playgroud)

我最终收到一条关于使用actto 包装事件的奇怪警告消息:

  Warning: An update to Dashboard 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 …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing reactjs react-testing-library react-hooks

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

React 测试库:无法更改 Material UI DatePicker 输入值

我正在尝试使用 React 测试库更改 Material UI Datepicker 输入的值。但它似乎不适用于fireEvent.change().

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

import MomentUtils from "@date-io/moment";
import { DatePicker, MuiPickersUtilsProvider } from "@material-ui/pickers";

describe("DatePicker", () => {
    test("Change datepicker value", async () => {
        render(
            <MuiPickersUtilsProvider utils={MomentUtils}>
                <DatePicker
                    label="Start Date"
                    id="startDate"
                    onChange={(date) => {
                        return undefined;
                    }}
                    value={new Date()}
                    format={"yyyy/MM/DD"}
                />
            </MuiPickersUtilsProvider>
        );

        const startDateInput = (await screen.findByLabelText("Start Date")) as HTMLInputElement;
        screen.debug(startDateInput);
        fireEvent.change(startDateInput, { target: { value: "2021/01/01" } }); …
Run Code Online (Sandbox Code Playgroud)

javascript datepicker reactjs material-ui react-testing-library

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

让单元测试等待异步获取填充的数据

useSWR我有一个单元测试,其中包括渲染用于获取数据的组件。但在调用之前数据尚未准备好,expect()因此测试失败。

test("StyleOptionDetails contains correct style option number", () => {
    renderWithMockSwr(
        <StyleOptionDetails
            {...mockIStyleOptionDetailsProps}
        />
    )
    expect(screen.getByText(123)).toBeInTheDocument();
});
Run Code Online (Sandbox Code Playgroud)

但如果我延迟setTimeout(),它就会通过测试。

setTimeout(() => {
    console.log('This will run after 2 second')
    expect(screen.getByText(123)).toBeInTheDocument();
}, 2000);
Run Code Online (Sandbox Code Playgroud)

创建延迟或等待数据的正确方法是什么?

unit-testing reactjs jestjs react-testing-library swr

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

测试按钮单击 ReactJS 时是否呈现另一个组件

我在两个不同的文件中有两个独立的组件

组件A和组件B

我在ComponentB中有一个按钮

现在我想测试一下,当单击ComponentB中的特定按钮时, ComponentA应呈现如下:

import { render, screen, fireEvent } from '@testing-library/react';
import ComponentA from './ComponentA';
import ComponentB from './ComponentB'

test('Component A Comes up on Click of Component B button', () => {
  render(<ComponentB />);

  const componentBButton = screen.getByRole('button');
  
  fireEvent.click(componentBButton);
  
  expect(<ComponentA />).toBeInTheDocument(); //This throwing an error that receiver must be HTMLElement or SVGElement

});
Run Code Online (Sandbox Code Playgroud)

不幸的是,我收到了Receiver must be HTMLElement or SVGElement这个expect(<ComponentA />).toBeInTheDocument();错误

请问,我是测试新手,请问如何解决这个问题?谢谢您的意见

ui-testing reactjs react-testing-library

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

我如何使用 React 测试库编写测试来检查悬停是否更改了组件样式?

我正在测试我的应用程序并遇到问题。当尝试测试Dropdown组件中的行是否对悬停施加效果时,我注意到我无法检查元素的背景颜色,我觉得这很奇怪。

尝试使用 jest-dom matcher "toHaveStyle()",下面是一个示例,我一生都无法让它工作。

下拉菜单.test.tsx

test('Should contain clickable elements that change style when hovered', () => {
    const dropElement1 = screen.getByLabelText('testLabel1');
    expect(dropElement1).toHaveStyle('background: white');
});
Run Code Online (Sandbox Code Playgroud)

错误

错误

我还尝试过使用background-color、使用十六进制值(另一个有趣的错误是 PrettyDom 将十六进制转换为 RGB),或者添加到toHaveStyle().

我确信该元素确实是白色的,但我不明白出了什么问题。如果我的方法是不好的做法,并且您对如何检查这一点有更好的了解,或者您对我的问题有解决方案,请告诉我!

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

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

Jest 中函数覆盖率的含义

jest以下是在我的一个组件上运行的输出:

----------------------------|---------|----------|---------|---------|-------------------
File                        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------------------------|---------|----------|---------|---------|-------------------
All files                   |     100 |      100 |      50 |     100 |                   
 search-suggestion-base.tsx |     100 |      100 |      50 |     100 |                   
----------------------------|---------|----------|---------|---------|-------------------
...
Jest: "global" coverage threshold for functions (100%) not met: 50%
Run Code Online (Sandbox Code Playgroud)

请注意,这% Funcs不是 100,测试失败。(覆盖率阈值不是我设定的。我不会设定这么高的阈值。)

问题是,Jest 没有告诉我哪些是未覆盖的线。此外,我也很难弄清楚 的含义是什么% Funcs。我什至找不到这方面的官方文档% Funcs。

任何帮助表示赞赏!

reactjs jestjs react-testing-library

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

如何修复错误:useHref() 只能在 &lt;Router&gt; 组件的上下文中使用

我该如何解决这个问题。我只是想创建一个测试来确保该组件呈现,但由于某种原因,即使该组件已经在内部,仍然会出现此问题<Router>。

我在这里读过其他类似的问题,答案都说将组件放入<Router/>,但这对我来说似乎不是问题。请告诉我我错过了什么?

** 我的应用程序.tsx**

import './App.scss';
import { AuthContexProvider } from './Utils/Contexs/AuthContext';
import { Routes, Route } from 'react-router-dom';
import { LogoLarge } from './Components/Logo/Logo';
import { SignInView } from './Views/SignInView';
import { ErrorPage } from './Views/ErrorView';
import { SignUpView } from './Views/SignUpView';
import { SwipeView } from './Views/SwipeView';
import { ResetPasswordView } from './Views/ResetPasswordView';
import { CreateProfileView } from './Views/CreateProfileView';
import { PrivateRoute } from './Utils/PrivateRoute';
import { ProfileView } from './Views/ProfileView';
import { SwipeContexProvider …
Run Code Online (Sandbox Code Playgroud)

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

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

使用react-testing-library测试导航

我想测试我为导航创建的侧边栏是否有效,这是我所做的一个简单示例

<ul>
  <li><Link to="/location1">location 1</Link></li>
  <li><Link to="/location2">location 2</Link></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

这是我的测试

const routerWrapper = ({children}) => <BrowserRouter>{children}</BrowserRouter>

// The first one runs fine
it('navigation to location 1' , () => {
render(<SideBar/> , {wrapper:routerWrapper})
// get the element and click on it
// check if title of page is correct
})

it('navigation to location 2' , () => {
render(<SideBar/> , {wrapper:routerWrapper})
// can't run because location is at /location1
})
Run Code Online (Sandbox Code Playgroud)

当我使用 RTL 测试导航时,第一个测试运行良好,但之后位置仍保留在该目录中以进行下一个测试,如何在每次测试后清除位置?或者有什么建议我应该如何测试导航?

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

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

React 测试库 - fireEvent 不会更改输入值

\n我正在学习 React 测试,但 fireEvent 不会改变我输入的值。无奈,不知道为什么?

\n

我正在渲染 BuyPlace 组件。在这个组件中,我有一个包含输入组件的表单(这些组件只是带有输入的标签,我将道具传递给表单上的这个组件)。

\n

在 screen.debug() 上,我可以看到我的组件是使用此表单和所有这些输入正确呈现的。

\n

另外,我的输入在我的测试中被正确捕获,我检查了这一点。

\n

这是我的测试:

\n
test("should change input value", async () => {\nrender(\n<HashRouter>\n<UserContext.Provider value={{ user: true }}>\n<BuyPlace />\n</UserContext.Provider>\n</HashRouter>\n);\nconst nameInputEl = screen.getByPlaceholderText("Podaj w\xc5\x82asn\xc4\x85 nazw\xc4\x99");\nfireEvent.change(nameInputEl, {\ntarget: { value: "Micha\xc5\x82" },\n});\nawait waitFor(() => {\nexpect(nameInputEl.value).toBe("Micha\xc5\x82");\n});\n});\n
Run Code Online (Sandbox Code Playgroud)\n

测试未通过。当然,我的应用程序运行正常,但在测试中它不起作用。

\n

这是我的组件上的handleInputChange:

\n
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) => {\nsetInputValues((prevValues) => {\nreturn {\n...prevValues,\n[e.target.name]: e.target.value,\n}\n});\n};\n
Run Code Online (Sandbox Code Playgroud)\n

我发现的每个解决方案都不起作用...我的输入值始终是空字符串。有人可以帮我弄这个吗?我想学习编写好的测试,但我不知道问题出在哪里。

\n

编辑\n我在 screen.debug() 上看到了一些有趣的东西。

\n

我在测试中的输入在没有 onchange 属性的情况下呈现,这在测试中正常吗?看一下这个:

\n
                   <input\n                    id="name"\n                    name="name"\n                    placeholder="Podaj w\xc5\x82asn\xc4\x85 nazw\xc4\x99"\n                    type="text"\n …
Run Code Online (Sandbox Code Playgroud)

javascript testing reactjs jestjs react-testing-library

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