标签: react-testing-library

React Native 测试库即使在调试中也找不到文本

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

我有一个简单的组件,它呈现两个可点击的图标和一个文本。这是一个可以递增和递减数字的计数器。

import React, { PureComponent } from "react";
import { Text, TouchableOpacity, View } from "react-native";
import { Button, Icon } from "react-native-elements";
import { getIconName } from "../../services/core";
import styles from "./styles";

export interface AmountButtonProps {
  amount: number;
  onDecrement: () => void;
  onIncrement: () => void;
  size: "small" | "large";
}

export class AmountButtons extends PureComponent<AmountButtonProps> {
  render() {
    const { amount, onDecrement, onIncrement, size } = this.props;
    const …
Run Code Online (Sandbox Code Playgroud)

unit-testing typescript reactjs react-native react-testing-library

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

在 React-Testing-Library 中使用自定义 /pages/_app.js 测试 Next.js 应用程序

我正在尝试按照Reat-Testing-Library 文档中的本指南来包装我想要测试的所有组件。我这样做是因为我需要访问在我正在测试的组件中的 _app.js 中定义的各种上下文提供程序。

这是我的 /pages/_app.js 文件:

export class MyApp extends App {
  public componentDidMount() {
    const jssStyles = document.querySelector("#jss-server-side");
    if (jssStyles && jssStyles.parentNode) {
      jssStyles.parentNode.removeChild(jssStyles);
    }
  }
  public render() {
    const { Component, pageProps, apolloClient } = this.props;
    return (
      <Container>
        <StateProvider>
          <ThemeProvider theme={theme}>
            <ApolloProvider client={apolloClient}>
              <CssBaseline />
              <Component {...pageProps} />
              <SignUp />
              <Snackbar />
            </ApolloProvider>
          </ThemeProvider>
        </StateProvider>
      </Container>
    );
  }
}

export default withApollo(MyApp);
Run Code Online (Sandbox Code Playgroud)

这是我的 /utils/testProviders.js 文件:

class AllTheProvidersWrapped extends App {
  public componentDidMount() {
    const …
Run Code Online (Sandbox Code Playgroud)

jestjs next.js react-testing-library

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

检查组件是否未呈现的最佳实践

让我们假设一个组件在 render 方法中返回 null,基于一些 prop。

使用 expect 来确保不呈现组件的最佳方法是什么?

例子:

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import Pagination from '../Pagination';

it('should not render if totaPages is 0', () => {
  const { container } = render(<Pagination activePage={1} totalPages={0} />);
  expect(container.firstChild).toBeNull();
});
Run Code Online (Sandbox Code Playgroud)

上面的代码够吗?

javascript testing unit-testing reactjs react-testing-library

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

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

概述:

  • 之前用 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
查看次数

如何修复错误: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万
查看次数