标签: react-testing-library

使用 React Router V6 测试 React 组件

我知道 React 测试库有一个使用 React 路由器进行测试的示例,但我无法让它工作(我想是因为我使用的是 React 路由器 V6)。

基本上,我需要路由器测试,因为我有使用 useParams() 来获取部分 url 的详细信息组件。没有它我无法渲染组件。

这是我让它工作的尝试(是的,该页面也需要 apollo,尽管它并不真正需要 redux)。

const AllTheProviders = ({children, initialRoutes}) => {
    return (
        <ApolloProvider client={client}>
            <Provider store={store}>
                <MemoryRouter>
                    {children}
                </MemoryRouter>
            </Provider>
        </ApolloProvider>
    );
}
const customRender = (ui, options) => render(ui, {wrapper: AllTheProviders, ...options})


beforeEach(() => {
    window.history.pushState({}, 'Test page',"/details/url-param-the-component-needs")
    customRender(<App/>);
});
Run Code Online (Sandbox Code Playgroud)

毫不奇怪,但这不起作用。我假设 window.history.pushState() 不适用于 React Router V6。我尝试使用 useNavigate(),但这在组件之外不起作用。

如果有人对我如何使这项工作有任何想法。我将不胜感激。

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

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

@testing-library/react 中用于异步钩子的函数 waitForNextUpdate (@testing-library/react-hooks) 的替代方案是什么?

我想测试我的自定义钩子,但在 React 18 中 @testing-library/react-hooks 库不起作用,而是我使用 @testing-library/react 它具有 renderHook 函数并且工作正常,但该库没有 waitForNextUpdate异步钩子函数。因此,我无法测试我的自定义异步挂钩。

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

16
推荐指数
1
解决办法
7318
查看次数

如何使用react-testing-library在容器内的元素上触发fireEvent.scroll?

我正在尝试模拟div中包含的元素的滚动,这是传递给render函数的元素。

我正在尝试这样的事情,但是随着下一个expect下降,div似乎没有滚动。

const content = (
      <div style={{display: 'flex'}}>
        <LazyList itemRenderer={itemRenderer} items={items} minItemHeight={MIN_ITEM_HEIGHT} />
      </div>
    );
mockOffsetSize(WIDTH, HEIGHT);

const {debug, container, queryByText} = render(content);
const scrollContainer = container.querySelector('.ReactVirtualized__Grid');
debug(scrollContainer);
fireEvent.scroll(scrollContainer, {y: 100});
debug(scrollContainer);
Run Code Online (Sandbox Code Playgroud)

这是触发滚动事件的正确方法吗?还有其他选择吗?

reactjs jestjs react-testing-library

15
推荐指数
1
解决办法
1736
查看次数

如何使用Jest和React测试库测试className

我是JavaScript测试的新手,并且在新的代码库中工作。我想编写一个在元素上检查className的测试。我正在与Jest和React-Testing-Library合作。下面我有一个测试,将根据variant道具。它还包含一个className和。我想测试一下。

it('Renders with a className equal to the variant', () => {
    const { container } = render(<Button variant="default" />)
    expect(container.firstChild) // Check for className here
})
Run Code Online (Sandbox Code Playgroud)

我试图在Google上搜索像Enzyme一样具有的属性,hasClass但找不到任何东西。有谁知道如何使用当前库(react-testing-library,Jest)解决此问题?

javascript reactjs jestjs react-testing-library

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

通过React Testing Library获得HTML元素?

我正在使用getByTestIdReact Testing库中的函数:

const button = wrapper.getByTestId("button");
expect(heading.textContent).toBe("something");
Run Code Online (Sandbox Code Playgroud)

是否可以/建议搜索HTML元素?所以像这样:

const button = wrapper.getByHTML("button");
const heading = wrapper.getByHTML("h1");
Run Code Online (Sandbox Code Playgroud)

react-testing-library

15
推荐指数
3
解决办法
9098
查看次数

无法找到带有文本的元素:使用 react-testing-library 时出现“myText”错误

我正在尝试react-testing-library与 React 和 Jest一起使用,但我的一个测试失败了,我认为这与className prop测试文件上的正则表达式有关。

下面我附上了各自的测试和组件文件。

另外,有没有办法snapshot用这个库进行测试?我觉得我的测试由于某种原因没有完成。

// Image.js Component


// @flow
import * as React from "react";
import styled from "styled-components";

const StyledImage = styled.img`
  max-width: ${props => props.imageWidth || 100}%;
`;

type Props = {
  imageAlt: string,
  imageSrc: string | boolean | Function,
  className?: string,
  StyledImage: React.Element<typeof StyledImage>
};

const Image = (props: Props) => {
  const { imageAlt, imageSrc, className } = props;
  return (
    <StyledImage
      {...props}
      className={className}
      src={imageSrc}
      alt={imageAlt}
    /> …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library

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

测试时,导致 React 状态更新的代码应该被包装成行为

我有这个测试:

import {
  render,
  cleanup,
  waitForElement
} from '@testing-library/react'

const TestApp = () => {
  const { loading, data, error } = useFetch<Person>('https://example.com', { onMount: true });

  return (
    <>
      {loading && <div data-testid="loading">loading...</div>}
      {error && <div data-testid="error">{error.message}</div>}
      {data && 
        <div>
          <div data-testid="person-name">{data.name}</div>
          <div data-testid="person-age">{data.age}</div>
        </div>
      }
    </>
  );
};

  describe("useFetch", () => {
    const renderComponent = () => render(<TestApp/>);

    it('should be initially loading', () => {
      const { getByTestId } = renderComponent();

      expect(getByTestId('loading')).toBeDefined();
    })
  });
Run Code Online (Sandbox Code Playgroud)

测试通过,但我收到以下警告:

警告:测试中 TestApp 的更新未包含在 …

reactjs react-testing-library

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

如何使用 react-testing-library 测试由其他组件组成的组件?

我对反应测试库完全陌生。在使用 Enzyme 测试组件没有成功之后,我才开始阅读我能找到的所有各种“入门”文档和博客文章。我能找到的大多数示例都非常简单,例如“Introducing the react-testing-library”博客文章中的示例。我想看看如何测试一个本身由其他组件组成的组件的示例,因为组件组合是关于 React 的最伟大的事情之一(在这篇 SO 文章中,ComposedComponent由于缺乏更好的名称,我将称之为此类示例) .

当我为ComposedComponentedEnzyme中的 a 编写测试时,我可以断言正确的 props 被传递给了一些ChildComponent并且信任ChildComponent有自己的测试,我不必关心ChildComponent在我的测试中实际呈现给 DOM 的内容ComposedComponent。但是对于 react-testing-library,我担心由于“您的测试将使用实际的 DOM 节点而不是处理呈现的 React 组件的实例”,因此我还必须ChildComponent通过对 DOM 节点进行断言来测试 的行为它呈现以响应其与 的关系ComposedComponent。这意味着我在 React 应用程序的组件层次结构中越往上走,我的测试就会变得越长、越详尽。我的问题的要点是:如何在不测试这些子组件的行为的情况下测试具有其他组件作为子组件的组件的行为?

我真的希望我只是缺乏想象力,有人可以帮助我弄清楚如何正确使用这个已经获得了如此多的追随者作为 Enzyme 的替代品的库。

reactjs react-testing-library

15
推荐指数
1
解决办法
5246
查看次数

在 dom-testing-library 或 react-testing-library 中测试输入值的最佳方法

测试/ 中<input>元素值的最佳方法是什么?dom-testing-libraryreact-testing-library

我采用的方法是通过closest()方法获取原始输入元素本身,然后我可以直接访问value属性:

const input = getByLabelText("Some Label")
expect(input.closest("input").value).toEqual("Some Value")
Run Code Online (Sandbox Code Playgroud)

我希望有一种方法可以做到这一点,而无需直接访问 HTML 属性。这似乎不符合测试库的精神。也许类似于jest-dom toHaveTextContent 匹配匹配器:

const input = getByLabelText("Some Label")
expect(input).toHaveTextContent("Some Value")
Run Code Online (Sandbox Code Playgroud)

更新

根据评论中的请求,这里是一个代码示例,显示了我觉得需要测试输入框中的值的情况。

这是我在我的应用程序中构建的模态组件的简化版本。喜欢,极其简化。这里的整个想法是,基于字符串道具,模态打开时输入预先填充了一些文本。用户可以自由编辑此输入并通过按按钮提交。但是,如果用户关闭模态然后重新打开它,我希望将文本重置为该原始字符串道具。我为它写了一个测试,因为以前版本的模态没有重置输入值。

我是用 TypeScript 写的,所以每个道具的类型都非常清楚。

interface Props {
  onClose: () => void
  isOpen: boolean
  initialValue: string
}

export default function MyModal({ onClose, isOpen, initialValue }) {
  const [inputValue, setInputValue] = useState(initialValue)

  // useEffect does the reset!
  useEffect(() => {
    if (!isOpen) …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs react-testing-library

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

如何等待断言元素永远不会出现在文档中?

我想断言某个元素永远不会出现在我的文档中。我知道我可以做到这一点

import '@testing-library/jest-dom/extend-expect'

it('does not contain element', async () => {
    const { queryByText } = await render(<MyComponent />);
    expect(queryByText('submit')).not.toBeInTheDocument();
});
Run Code Online (Sandbox Code Playgroud)

但就我而言,我需要等待以确保延迟后不会添加该元素。我怎样才能实现这个目标?

reactjs jestjs react-testing-library

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