我不确定使用 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
我正在使用jest和testing-library/react编写单元测试。在此之前,我从未编写过任何单元测试。编写测试后,我收到类似这样的错误。
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) 我只是想对渲染一个根据登录状态重定向用户的组件进行初步测试,从而使用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) 我正在使用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
我想确保我的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
我有这个组件,它使用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) 以下是我想测试的自定义挂钩:
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) 在react-testing-library对其元素执行一些测试之前,您必须渲染您的反应组件。
对于同一组件的多次测试,是否应该避免多次渲染该组件?或者你必须在每个
test()/it()块中渲染它?
您应该选择每个块中的组件元素(例如按钮)test()/it(),还是应该取消选择并仅选择一次?
它对测试的执行时间有影响吗?
其中一种方法是最佳实践/反模式吗?
为什么最后一个例子失败了?
对于基本组件我有以下测试方法:
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) 有以下单元测试:
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
我想测试一个自定义钩子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
reactjs ×9
jestjs ×7
javascript ×4
typescript ×2
apexcharts ×1
chart.js ×1
function ×1
material-ui ×1
next.js ×1
react-hooks ×1
react-hooks-testing-library ×1
unit-testing ×1