标签: react-testing-library

使用 React/Typescript 在 test-utils 中扩展 React 测试库的自定义渲染的返回类型是什么?

我不确定使用 React 测试库的 Render 的自定义渲染函数的返回类型,我假设它是 element 或 JSX,但这似乎不起作用。

代码:

import React, { ReactElement } from 'react'
import { render, RenderOptions } from '@testing-library/react'
import { theme } from './theme'
import { ThemeProvider } from 'styled-components'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import { searchReducer, initialState } from './store/reducer/searchReducer'

const store = createStore(searchReducer, initialState)

interface ProviderProps { 
  children?: NonNullable<React.ReactNode>
}

const TheProvider: React.FC<ProviderProps> = ({
  children,
}) => {
  return (
    <Provider store={store}>
      <ThemeProvider theme={theme}> …
Run Code Online (Sandbox Code Playgroud)

function typescript reactjs react-testing-library react-typescript

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

TypeError: r.node.getBBox 不是函数”。] { code: 'ERR_UNHANDLED_REJECTION' }

我正在使用jesttesting-library/react编写单元测试。在此之前,我从未编写过任何单元测试。编写测试后,我收到类似这样的错误。

\n
 FAIL  src/__test__/components/Barchart.test.tsx\n  \xe2\x97\x8f Test suite failed to run\n\n    Call retries were exceeded\n\n      at ChildProcessWorker.initialize (node_modules/jest-worker/build/workers/ChildProcessWorker.js:193:21)\n\nnode:internal/process/promises:245\n          triggerUncaughtException(err, true /* fromPromise */);\n          ^\n\n[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "TypeError: r.node.getBBox is not a function".] {\n  code: 'ERR_UNHANDLED_REJECTION'\n}\nnode:internal/process/promises:245\n          triggerUncaughtException(err, true /* fromPromise */);\n          ^\n\n[UnhandledPromiseRejection: This error originated either by throwing …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs react-testing-library apexcharts

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

使用 React-testing-library 测试时出现 Next.js 路由器错误

我只是想对渲染一个根据登录状态重定向用户的组件进行初步测试,从而使用routerfrom next/routerincomponentDidMount但出现以下错误:

未找到路由器实例。您应该只在应用程序的客户端内使用“next/router”。

在我看来,从客户端来看,这意味着必须在渲染方法内部使用路由器链接,因为这使得 DOM 和其他方法(如生命周期、钩子和服务器端)在这些情况下并非如此它会抛出一个错误。

我知道测试整个组件超出了单元测试的目的,但无论如何我想这样做。因此,我遵循了这个讨论,看来必须模拟路由器才能被React-Testing-Library使用,但没有一个解决方案对我有用。

这是我尝试过的代码:

describe('Home Page', () => {
  it('renders without crashing', async () => {
    render(<Home />)
  })
})
Run Code Online (Sandbox Code Playgroud)

jestjs next.js react-testing-library

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

为什么使用 React Hook 表单时表单测试失败?

我正在使用react-hook-form来构建一个表单。该表格运行良好,但测试未通过。

react-hook-form当我不使用并通过 onSubmit时测试通过<form onSubmit={onSubmit}>。当我通过 handleSubmit 传递 onSubmit 时<form onSubmit={handleSubmit(onSubmit)}>,它没有通过。

这是我的表格 App.js

import { useForm } from "react-hook-form";

export default function App({ onSubmit = (data) => console.log(data) }) {
  const { handleSubmit, register } = useForm();
  return (
    // <form onSubmit={onSubmit}>                  <--- This works
    // <form onSubmit={handleSubmit(onSubmit)}>    <--- This doesn't work
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        placeholder="Email"
        defaultValue=""
        key="email"
        {...register("email")}
      />
      <input
        placeholder="Password"
        defaultValue=""
        key="password"
        {...register("password")}
      />
      <input type="submit" value="submit" />
    </form>
  );
}
Run Code Online (Sandbox Code Playgroud)

这是我为其编写的测试 App.test.js

import { …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-testing-library react-hooks react-hook-form

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

如何测试 Material-UI Popover 关闭实现

我想确保我的Popover元素与触发按钮相结合的实现按预期工作。我无法进行工作测试来断言用户按 esc 后 Popover 会关闭。我能够使用 Modal 进行此测试,但我必须在当前项目中使用 Popover。

组件代码:

import {
    Button, Popover,
} from '@mui/material';
import React from 'react';

export default function SimpleModal() {
    const [anchorEl, setAnchorEl] = React.useState<HTMLButtonElement | null>(null);

    const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const open = Boolean(anchorEl);
  const id = open ? 'user-menu' : undefined;

    return (
        <>
            <Button
                aria-controls={id}
                aria-haspopup="true"
                onClick={handleClick}
            >
                Open Modal
            </Button>

            <Popover open={open} onClose={handleClose}>
                    <h1>Text in Modal</h1> …
Run Code Online (Sandbox Code Playgroud)

integration-testing reactjs jestjs material-ui react-testing-library

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

反应测试库:无法从给定项目获取上下文

我有这个组件,它使用react-chartjs-2来渲染Doughnut图表:

const CompliancyChart = ({data}): JSX.Element => {
...
   return (
     <ChartStyled>
          {chartPlugins && chartData && (
            <Doughnut
              aria-label="Compliancy Chart"
              data={chartData}
              options={chartOptions}
              plugins={chartPlugins}
            />
          )}
        </ChartStyled>
    );
};
Run Code Online (Sandbox Code Playgroud)

我有一个该组件的测试文件,其中包含以下断言:

describe('Chart component', () => {
  afterEach(() => {
    cleanup();
  });

  test('should render without errors', async () => {
    render(<CompliancyChart data={mockCompliancyChartData} />, {});
    const compliancyChart = await screen.findByRole('img', {
      name: 'Compliancy Chart',
    });
    expect(compliancyChart).toBeDefined();
  });
});
Run Code Online (Sandbox Code Playgroud)

该测试工作正常,但我不断在测试控制台中收到此错误:

Failed to create chart: can't acquire context from the given item …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs chart.js react-testing-library

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

假计时器不适用于最新版本的用户事件?

以下是我想测试的自定义挂钩:

import { useEffect, useState } from "react";

export const useAlert = () => {
  const [alert, setAlert] = useState(null);

  useEffect(() => {
    let timerId = setTimeout(() => {
      console.log("Timeout, removing alert from DOM");
      setAlert(null);
    }, 200);

    return () => clearTimeout(timerId);
  }, [alert]);

  return {
    renderAlert: alert ? alert : null,
    setAlert,
  };
};
Run Code Online (Sandbox Code Playgroud)

它只是允许组件设置警报并在 300 毫秒后自动清除警报。

这是对上述钩子的工作测试

import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useAlert } from "../components/useAlert";

// jest.useFakeTimers();

function FakeComponent() …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs react-testing-library

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

您应该在每个“test()/it()”块中还是在全局中渲染组件/选择元素?

react-testing-library对其元素执行一些测试之前,您必须渲染您的反应组件。

  1. 对于同一组件的多次测试,是否应该避免多次渲染该组件?或者你必须在每个 test()/it()块中渲染它?

  2. 您应该选择每个块中的组件元素(例如按钮)test()/it(),还是应该取消选择并仅选择一次?

  3. 它对测试的执行时间有影响吗?

  4. 其中一种方法是最佳实践/反模式吗?

  5. 为什么最后一个例子失败了?

对于基本组件我有以下测试方法:

function MyComponent() {
  return (
    <>
      <button disabled>test</button>
      <button disabled>another button</button>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

例如

describe("MyComponent", () => {
  it("renders", async () => {
    const { getByRole } = render(<MyComponent />);
    const button = getByRole("button", { name: /test/i });
    expect(button).toBeInTheDocument();
  });

  it("is disabled", async () => {
    // repetetive render and select, should be avoided or adopted?
    const { getByRole } = render(<MyComponent />);
    const button = …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library

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

检查对象是否包含 React 测试库中的链接

有以下单元测试:

  const MY_URL = 'example.com'
  it('should render MyComponent with url', () => {
    const { getByTestId } = render(<MyComponent />);
    const myLink = getByTestId(TestIds.LINK);
    expect(loggingLink).toContain(MY_URL);
  });
Run Code Online (Sandbox Code Playgroud)

测试失败并显示以下消息:

 Expected value:  "example.com"
 Received object: <div class="m-3" data-testid="test-link"><a href="example.com">my-link</a></div>
Run Code Online (Sandbox Code Playgroud)

所以看起来并toContain没有检查该对象内部的内容。有没有一种方法可以检查 URL 是否在对象内部?

javascript unit-testing reactjs jestjs react-testing-library

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

在react-testing-library和TypeScript中renderHook的合适类型是什么?

我想测试一个自定义钩子react-testing-library,因此我将以下代码添加到 beforeEach 中:

let renderedHook ;

beforeEach(() => {
  renderedHook = renderHook(() => useFetch());
});

test('.....', () => {
  expect(renderedHook.current.data).toBe(1);
});
Run Code Online (Sandbox Code Playgroud)

上面的代码运行良好!但我使用的是 TypeScript,在这种情况下合适的类型是什么let renderedHook

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

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