标签: react-testing-library

React-Query - 使用react-testing-library进行单元测试

我有一个Dashboard包含子组件的组件,例如Child它使用反应查询。

我有一个针对该Dashboard组件的现有单元测试,该测试开始失败,错误是:

TypeError: queryClient.defaultQueryObserverOptions is not a function

  38 |     const { locale } = React.useContext(LocaleStateContext);
  39 |     const options = getOptions(locale);
> 40 |     return useQuery(
     |            ^
  41 |         rqKey,
  42 |         async () => {
  43 |             const result = await window.fetch(url, options);
Run Code Online (Sandbox Code Playgroud)

测试片段:

const queryClient = new QueryClient();
const { getByTestId, getByRole } = render(
    <IntlProvider locale="en" messages={messages}>
        <QueryClientProvider client={queryClient}>
            <Dashboard />
        </QueryClientProvider>
    </IntlProvider>,
);
Run Code Online (Sandbox Code Playgroud)

我阅读了有关测试的文档:

https://react-query.tanstack.com/guides/testing#our-first-test

但我不想一定要使用,renderHook因为我对结果不感兴趣。 …

typescript reactjs react-testing-library react-query

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

React 测试库使用 userEvent、fireEvent 和常规点击之间的差异

在使用 React 学习 TDD 的过程中,我注意到有不同的方法可以触发测试中元素的点击。可以通过fireEvent.click(),userEvent.click()和 来 完成HTML_ELEMENT.click()。

他们都工作得很好。经过一些研究后,我了解到userEvent.click()基本上在底层使用 fireEvent,并且它更适合自动化测试(例如 cypress),而fireEvent.click()更适合单元测试。

但我找不到两者userEvent和可以使用的fireEvent常规函数​​有何不同。HTML_ELEMENT.click()

使用它们而不是使用常规点击功能可以给我带来什么好处?

reactjs jestjs react-testing-library

6
推荐指数
1
解决办法
6884
查看次数

React 构建 - 未找到:错误:无法解析“缓冲区”

当我在 React 中构建应用程序时遇到错误。仅当我尝试构建应用程序时,我才注意到此错误。

当我停止开发服务器并再次运行它时,它显示了相同的错误。看来我做了一些更改,仅在我再次启动服务器或进行构建时才显示:

找不到模块:错误:无法解析“\node_modules\htmlparser2\lib”中的“缓冲区”重大更改:webpack < 5 默认情况下用于包含 node.js 核心模块的 polyfill。现在不再是这种情况。验证您是否需要这些模块并为其配置一个polyfill。

如果你想包含一个polyfill,你需要安装“buffer”。如果你不想包含一个polyfill,你可以使用一个空模块,如下所示:resolve.alias: { "buffer": false }

错误 命令失败,退出代码为 1。

我的申请是用 CRA 和 Typescript 制作的。这是我的package.json:

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "start": "react-scripts start",
    "build": "cross-env NODE_OPTIONS='--max-old-space-size=4096' react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "dependencies": {
    "@apollo/react-hooks": "^4.0.0",
    "@date-io/moment": "^1.3.13",
    "@material-ui/core": "^4.11.0",
    "@material-ui/icons": "^4.9.1",
    "@material-ui/lab": "^4.0.0-alpha.56",
    "@material-ui/pickers": "^3.2.10",
    "@optimizely/react-sdk": "^2.4.0",
    "apollo-boost": "^0.4.9",
    "classnames": "^2.2.6",
    "formik": "^2.2.5",
    "graphql": "^15.4.0",
    "lodash": "^4.17.20",
    "moment": "^2.29.1",
    "react": "^16.13.1", …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs enzyme react-scripts react-testing-library

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

如何等待测试库中按钮的禁用状态发生更改?

我有一个 React 组件,其中一个输入字段和一个按钮在一开始就被禁用。如果用户向输入字段提供的输入经过 API 验证(在输入字段中输入任何内容后调用该 API),则此按钮的状态(已禁用)会发生变化。

我正在通过提供有效输入进行测试,但它需要等到 API 调用完成,所以基本上我想测试,如果提供有效输入,按钮在我的测试中是否重新启用。

我通过以下代码执行此操作:

userEvent.type(getByRole("textbox"), "HELLO");
await waitFor(() => expect(getByTestId("my-btn")).not.toBeDisabled());

Run Code Online (Sandbox Code Playgroud)

但即使输入有效,它也不起作用

testing reactjs react-testing-library

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

如何在反应测试库中测试单选按钮(用户可以选择其他单选按钮)

我是反应新手,并在反应中编写测试用例。我有两个单选按钮(IPV4 和 IPV6)。我想测试用户是否可以选择另一个单选按钮。我不知道要在单选按钮上应用哪个事件侦听器,是更改事件还是单击事件?

\n

我将问题分为两部分:1)我正在检查是否可以选择或取消选择一个单选按钮2)我是否可以选择另一个单选按钮。我只在第一部分失败了,所以请帮助我。这是我的代码和测试用例。

\n
import React from \'react\'    \nimport constants from \'LookingGlass/constants\'    \nimport { Label, RadioButton } from \'LookingGlass/common/components\'\n    \nexport const componentTestId = \'SelectorIPVersion\'\n    \nexport default function SelectorIPVersion(props = {}) {\n    const { checkedVersion, onChange, disabled } = props\n    \n    const { choices, groupName, label } = constants.SelectorIPVersion\n    \n    const _onChange = (e) => {\n        onChange && onChange(e.target.value)\n    }\n    \n    let selectorChoices = choices.map((c) => {\n        return (\n            <RadioButton\n                key={c.value}\n                id={c.value}\n                name={groupName}\n                value={c.value}\n                label={c.label}\n                checked={c.value === checkedVersion}\n                onChange={_onChange}\n …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library

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

`getByRole` 找不到相应文本框的名称

这是针对 的测试:

  it("changes the state when body input is changed", () => {
    render(<CommentForm />)
    // let input = screen.getByLabelText("Your Name");

    let input = screen.getByRole("textbox", { name: "Your Comment" });
    fireEvent.change(input, { target: { value: "MyComment" } });
    expect(input.value).toEqual("MyComment");
  });

Run Code Online (Sandbox Code Playgroud)

使用注释行它可以工作(当我使用 搜索时getByLabelText)。这是当我尝试使用以下命令找到它时得到的结果getByRole:

 Unable to find an accessible element with the role "textbox" and name "Your Comment"

    Here are the accessible roles:

      document:

      Name "":
      <body />

      --------------------------------------------------
      generic:

      Name "":
      <div />

      Name "":
      <div
        class="input-group" …
Run Code Online (Sandbox Code Playgroud)

reactjs react-testing-library

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

类型错误:符号不是函数

页脚视图.tsx

\n
import styles from './Footer.module.scss';\n\nimport logo from 'assets/images/logo_header.svg';\nimport { ReactSVG } from 'react-svg';\nimport iconTwitter from 'assets/images/logo_twitter.svg';\nimport iconFacebook from 'assets/images/logo_facebook.svg';\nimport iconYoutube from 'assets/images/logo_youtube.svg';\nimport { proxyConfSelector } from 'core';\nimport { useSelector } from 'react-redux';\nimport { useTranslation } from 'hooks/useTranslation';\n\nconst Footer = () => {\n  const proxyConf = useSelector(proxyConfSelector);\n  const year = new Date().getFullYear();\n  const [t, lang] = useTranslation();\n\n  // eslint-disable-next-line no-console\n  console.log('Language', [t, lang]);\n\n  return (\n    <div className={styles.footerContainer}>\n      <a href={`https://fodjan.com/${lang === 'de' ? 'de/' : 'en/'}`}>\n        <ReactSVG className={styles.footerLogo} src={logo} />\n      </a>\n …
Run Code Online (Sandbox Code Playgroud)

svg reactjs react-testing-library

6
推荐指数
1
解决办法
6498
查看次数

React 测试库 - “messageParent”只能在工作人员内部使用

我正在使用 RTL 测试 React 组件,每次运行测试时,我都会得到,

"messageParent" can only be used inside a worker
Run Code Online (Sandbox Code Playgroud)

**这是代码

describe('Header', () => {
  it('validates header component is rendered', () => {
    const { getByTestId } = render(<Header patientName="Jake Bland" />);
    expect(getByTestId('patient-name')).toHaveTextContent(/^Jake Bland$/);
    expect(getByTestId('dateRange')).toBe(dateRange);
  });
});
Run Code Online (Sandbox Code Playgroud)

对此的任何帮助将不胜感激。

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

6
推荐指数
2
解决办法
2584
查看次数

来自 Jest 和 React-testing-library 单元测试的 useRef 的 ref 为 null

我有以下组件,我在导航上创建 ref 以在导航外部单击时关闭菜单:

import { useState, useEffect, useRef, } from 'react';

const Header = () => {
  const [menuOpen, setMenuOpen] = useState(false);
  const navRef = useRef(null);

  const hideMenu = () => setMenuOpen(false);

  const handleClick = event => {
    if (menuOpen && !navRef.current.contains(event.target)) {
      hideMenu();
    }
  };

  useEffect(() => {
    document.addEventListener('click', handleClick);
    return () => {
      document.removeEventListener('click', handleClick);
    };
  });

  return (
    <header className="header">
      <nav className="header-nav" ref={navRef}>
        ...
      </nav>
    </header>
  );
};

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

这是单元测试:

import React from 'react';

import …
Run Code Online (Sandbox Code Playgroud)

unit-testing reactjs jestjs react-testing-library

6
推荐指数
0
解决办法
4215
查看次数

模拟 window.performance.getEntriesByType

在我的组件中,我检查页面是否重新加载并重定向到另一个页面。我通过以下代码来做到这一点。

useEffect(() => {
    //this will prevent users from accidently refreshing / closing tab
    window.onbeforeunload = () => {
      return "";
    };
   //check whether user reloaded
    if (
      window.performance.getEntriesByType("navigation")[0].type === "reload"
    ) {
      openExternalURL(process.env.GATSBY_MARKETING_URL);
    }
  }, []);
Run Code Online (Sandbox Code Playgroud)

问题是我在 Jest/react-test-library 测试用例中不断收到错误,如下所示

TypeError: window.performance.getEntriesByType is not a function
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

即使我尝试像下面那样嘲笑它,但没有成功。

window.performance = {
  getEntriesByType: jest.fn().mockReturnValue([{ type: "reload" }]),
  measure: jest.fn()
};
Run Code Online (Sandbox Code Playgroud)

有人能指出我正确的方向吗?提前致谢。

javascript unit-testing mocking reactjs react-testing-library

6
推荐指数
1
解决办法
3900
查看次数