标签: react-testing-library

fireEvent 正在调用 Found multiple elements by:react-testing-library 中的 data-testid 错误

data-testid我通过查找带有with的按钮来调用函数"show_more_button"

<OurSecondaryButton test={"show_more_button"} onClick={(e) => showComments(e)} component="span" color="secondary">
    View {min !== -1 && min !== -2 ? min : 0} More Comments
</OurSecondaryButton>
Run Code Online (Sandbox Code Playgroud)

显示评论

const showComments = (e) => {
  e.preventDefault();
  if (inc + 2 && inc <= the_comments) {
     setShowMore(inc + 2);
     setShowLessFlag(true);
  } else {
     setShowMore(the_comments);
  }
};
Run Code Online (Sandbox Code Playgroud)

这使得这个

const showMoreComments = () => {
    return filterComments.map((comment, i) => (
        <div data-testid="comment-show-more" key={i}>
            <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
        </div>
    ));
};
Run Code Online (Sandbox Code Playgroud)

在执行 …

reactjs react-testing-library

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

如何用 fireEvent.scroll 检测scrollPosition?- 反应测试库

[出于问题目的,我制作了虚拟示例以使其更容易理解]

假设我有一个主页组件,它将在达到页面高度的 1/3 时切换颜色。

// Homepage.js
const Home = (props) => {
  const [toggle, setToggle] = useState(false)

  useEffect(() => {
    window.addEventListener('scroll', handleScroll)

    return () => window.removeEventListener('scroll', handleScroll)
  }, [toggle])

  const handleScroll = () => {
    const scrollPosition = document.documentElement.scrollTop;
    const oneThirdPageHeight = (1 / 3) * document.documentElement.offsetHeight;

    if (scrollPosition > onethirdPageHeight) {
      return setToggle(true)
    }
    return setToggle(false)
  }

  return <div style={{ height: '1500px', color: toggle ? 'blue' : 'red'}}>hello</div>
}
Run Code Online (Sandbox Code Playgroud)

和测试文件

// Homepage.test.js
test('should toggle color when scrolled', () => …
Run Code Online (Sandbox Code Playgroud)

javascript dom scroll reactjs react-testing-library

11
推荐指数
1
解决办法
5300
查看次数

反应测试库中未实现窗口错误

我正在测试一个使用 Redux 构建的非常基本的反例元素。这是我的测试:

import userEvent from "@testing-library/user-event";
import { render, screen } from "src/testUtils";
import { Counter } from "../Counter";

describe("Counter screen", () => {
  it("buttons should change displayed value", () => {
    render(<Counter />);
    const counter = screen.getByText(/counter*/i);
    const plus = screen.getByRole("button", { name: /\+/i });
    const minus = screen.getByText(/\-/i);

    expect(counter).toHaveTextContent("0");
    userEvent.click(plus);
    userEvent.click(plus);
    expect(counter).toHaveTextContent("10");
    userEvent.click(minus);
    expect(counter).toHaveTextContent("9");
  });
});
Run Code Online (Sandbox Code Playgroud)

测试全部通过,但我收到了大量错误jsdom测试全部通过,但我在记录到控制台

Error: Not implemented: window.computedStyle(elt, pseudoElt)
          at module.exports (/home/abhijeet/Documents/github/react-template/node_modules/jsdom/lib/jsdom/browser/not-implemented.js:9:17)
          at Window.getComputedStyle (/home/abhijeet/Documents/github/react-template/node_modules/jsdom/lib/jsdom/browser/Window.js:657:7)
          at computeMiscTextAlternative (/home/abhijeet/Documents/github/react-template/node_modules/@testing-library/react/node_modules/dom-accessibility-api/sources/accessible-name.ts:306:62)
          at computeTextAlternative (/home/abhijeet/Documents/github/react-template/node_modules/@testing-library/react/node_modules/dom-accessibility-api/sources/accessible-name.ts:521:11)
          at …
Run Code Online (Sandbox Code Playgroud)

jsdom reactjs jestjs react-redux react-testing-library

11
推荐指数
2
解决办法
6060
查看次数

React 测试库覆盖延迟加载

如何覆盖react测试库中的延迟加载组件。

import React, {lazy} from 'react';
const ownerInfo = lazy(() => import('../abc'))

const compone = () => {
  return <Suspense><abc /></Suspense>
}
export default compone
Run Code Online (Sandbox Code Playgroud)

测试规范.js

 import React from 'react'
 import {render, fireEvent} from '@testing-library/react'
 import configureStore from 'redux-mock-store'

 ...
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs redux-mock-store react-testing-library react-hooks

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

使用 jest 和 React-testing-library 测试正确的 SVG 组件渲染

我在 React 组件中有一个有条件渲染的 svg。

<div className='avatar'>
      {gender === true ? <MaleAvatar /> : <FemaleAvatar />}
    </div>
Run Code Online (Sandbox Code Playgroud)

MaleAvatar 和 FemaleAvatar 是包含 svgs 的组件。最初,我希望渲染 MaleAvatar svg,然后如果性别值更改为 false,FemaleAvatar svg 就会渲染 - 但男性头像应该首先渲染,这就是我想要测试的。

条件所在的组件是子组件的子组件,但我正在通过文本测试该组件中的元素,并且测试工作正常,例如:

const personDetailsText = screen.getByText('Personal details')
Run Code Online (Sandbox Code Playgroud)

我正在使用 jest 和 react-testing-library 进行测试,但是在父 div 上使用测试 id 然后抓取第一个子项不起作用,因为它无法识别测试 id。所以如果我有:

<div data-testid='avatar' className='avatar'>
          {gender === true ? <MaleAvatar /> : <FemaleAvatar />}
        </div>
Run Code Online (Sandbox Code Playgroud)

...然后下面的测试在 'const avatarSVG = screen.getByTestId('avatar')' 处失败:

test('gender avatar is male on initialisation', () => {
    const avatarSVG = screen.getByTestId('avatar')
    expect(avatarSVG).toBeInTheDocument()
    expect(() => …
Run Code Online (Sandbox Code Playgroud)

svg reactjs jestjs react-testing-library

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

如何获取H1标签的值并使用Jest和RTL进行测试

我正在尝试测试我的组件是否在 h1 中显示正确的值。

\n

下面是我将要测试的组件。

\n
  const Title = () => {\n  return (\n    <>\n      <h1 aria-label='Title of the project'>MY RTL PROJECT</h1>\n    </>\n  );\n};\n\nexport default Title;\n
Run Code Online (Sandbox Code Playgroud)\n

这是我的测试文件,尝试检查我的组件是否显示“MY RTL PROJECT”。

\n
import { render, } from '@testing-library/react';\nimport Title from '../Title';\n\n\n    describe('Checks the title component', () => {\n    \n        it('checks the value of the Title component', () => {\n            const { getByText } = render(<Title />);\n            const titleValue = getByText('MY RTL PROJECT')\n            expect(titleValue).toBe('MY RTL PROJECT')\n        })\n    })\n
Run Code Online (Sandbox Code Playgroud)\n

这是错误: “messageParent”只能在工作人员内部使用

\n …

javascript reactjs jestjs react-testing-library

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

React 测试库中的 userEvent 不会导致 onClick 被调用

我正在尝试使用react-testing-library运行一个非常简单的测试,其中为按钮提供了模拟函数,单击该按钮,然后测试检查该函数是否被调用。但是,测试当前失败,因为未调用该函数。这是代码:

import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

describe('Button', () => {
  test('eventHandler called on click', () => {
    const handleClick = jest.fn();
    render(
      <button onClick={handleClick} type="button">
        Click Me
      </button>
    );

    userEvent.click(screen.getByRole('button'));

    expect(handleClick).toHaveBeenCalledTimes(1);
  });
});
Run Code Online (Sandbox Code Playgroud)

没有抛出任何错误,成功找到按钮,但由于某种原因,该函数没有注册它已被调用。

任何帮助,将不胜感激!

reactjs jestjs react-testing-library

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

如何使用 Jest 测试 React Router

我是玩笑测试的新手,我想测试以下代码。

\n
import React from "react";\nimport "./ButtonLogin.css";\nimport { Link } from 'react-router-dom';\n\nfunction ButtonLogin() {\n    return (\n        <Link to="/login"> <button className="button-login">Iniciar sesi\xc3\xb3n</button></Link>\n    )\n}\n\nexport default ButtonLogin;\n
Run Code Online (Sandbox Code Playgroud)\n
import { MemoryRouter } from 'react-router-dom';\nimport { render, fireEvent, Link } from '@testing-library/react';\nimport { ButtonLogin } from './ButtonLogin';\n\nit('routes to a new route', async () => {\n\n  ButtonLogin = jest.fn();\n\n  const { getByText } = render(\n    <MemoryRouter ButtonLogin={ButtonLogin}>\n      <Link to="/login">Iniciar sesi\xc3\xb3n</Link>\n    </MemoryRouter>\n  );\n\n  fireEvent.click(getByText('Iniciar sesi\xc3\xb3n'));\n\n  expect(ButtonLogin).toHaveBeenCalledWith('/login');\n});\n
Run Code Online (Sandbox Code Playgroud)\n

我已经执行了以下测试,但失败了,并且在第 9 行中收到以下错误。\n路由到新路由

\n
"ButtonLogin" is read-only.\n
Run Code Online (Sandbox Code Playgroud)\n

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

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

React + Jest 测试错误 - ReferenceError:expect 未定义

我已经到处寻找这个问题的答案,并且可能尝试了 99% 的方法,所以我决定开始一个自己的线程,这样其他人就可以仔细查看我目前拥有的内容,看看他们是否能发现问题。

\n

我对 Jest 测试非常陌生,决定尝试将其实现到我们的代码库中。我使用本指南来确保我所做的一切都是完美的,但仍然发生此错误\n使用 Jest 测试 React 应用程序的实用指南

\n

我正在测试一个简单的功能组件,该组件使用react-hook-form在页面上生成表单,然后通过redux调用将完成的表单发送到我们的后端

\n

我已将 setupTests.js 文件设置为:

\n
import \'@testing-library/jest-dom\'\nimport { configure } from "enzyme"\nimport Adapter from "enzyme-adapter-react-16";\nimport \'@testing-library/jest-dom/extend-expect\';\n\nconfigure({ adapter: new Adapter() });\n
Run Code Online (Sandbox Code Playgroud)\n

将我的 package.json 测试命令更新为

\n
"test": "react-scripts test --env=jsdom --setupFiles ./src/setupTests.js"\n
Run Code Online (Sandbox Code Playgroud)\n

这是我尝试通过简单测试运行的测试规范:

\n
import React from \'react\';\nimport { render as rtlRender, screen } from \'@testing-library/react\';\nimport { Provider } from \'react-redux\';\nimport store from \'../../../store\';\nimport AddNewProperty from \'./AddNewProperty\';\n\nconfigure({ adapter: new Adapter() });\n\nconst render = component => rtlRender(\n …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library react-hooks react-testing

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

如何模拟带有 ref 属性的 React 函数组件?

问题:

我正在尝试使用 jest 和 React 测试库来模拟包含在 React.ForwardRef() 中的功能组件,但我不断收到此警告(这使我的测试失败):

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Run Code Online (Sandbox Code Playgroud)

这是我要测试的组件:

const ParentComponent = () => {
  const childRef = useRef(null);

  return (
    <div data-testid="parent">
      Parent
      {/* want to mock this ChildComponent */}
      <ChildComponent ref={childRef} />
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

这是我要模拟的组件:

const ChildComponent = forwardRef((props, ref) => (
  <div ref={ref} {...props}>
    Child
  </div>
));
Run Code Online (Sandbox Code Playgroud)

我尝试过的:


jest.mock("../ChildComponent", () => ({
  __esModule: true,
  default: () …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library

11
推荐指数
1
解决办法
9158
查看次数