有一个使用react-hook-form的基本组件:
const { 处理提交、重置、控制 } = useForm({ 解析器: yupResolver(schema) });
...
<MyComponent
title='title'
open={isOpened}
control={control}
/>
Run Code Online (Sandbox Code Playgroud)
这个组件有 3 个 props,title - 一个字符串,open - 一个函数,control - 不知道它是什么,所有这些都是强制性的。
因此,在为其编写测试时,我陷入了困境:
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import MyComponent from './my-component';
describe('MyComponent', () => {
const title = 'title';
it('should render successfully', () => {
const { baseElement, getByText } = render(
<TaskModal
title={title}
open={jest.fn()}
control={} // what should be written here?
/>
);
expect(baseElement).toBeTruthy();
expect(getByText(title)).toBeTruthy();
});
Run Code Online (Sandbox Code Playgroud)
control这个测试怎么能被嘲笑呢?
javascript typescript reactjs react-testing-library react-hook-form
我正在尝试使用 jest 和 React 测试库编写单元测试。我想测试 useEffect 挂钩内的函数调用,但我的测试不起作用。我需要做什么才能成功通过测试?
useEffect(() => {
getActiveFilters(filterValue);
// eslint-disable-next-line
}, [filterValue, dictionaries]);
Run Code Online (Sandbox Code Playgroud)
这是我的测试
it('should call the [getActiveFilters] function', async () => {
const getActiveFilters = jest.fn();
await waitFor(() => expect(getActiveFilters).toHaveBeenCalled());
});
Run Code Online (Sandbox Code Playgroud)
在react-testing-library中测试div或ap标签中的文本的最佳方法是什么?
让我们假设我们有一个这样的 React 组件:
const Greeting = ({name}) => {
return <div>Welcome {name}!</div>
}
Run Code Online (Sandbox Code Playgroud)
测试组件呈现预期值的最佳方法是什么,是使用toBeInTheDocument():
import {render, screen} from '@testing-library/react'
import Greeting from './greeting'
test('it renders the given name in the greeting', () => {
render(<Greeting name="John Doe"/>)
expect(screen.getByText(`Welcome John Doe!`)).toBeInTheDocument()
})
Run Code Online (Sandbox Code Playgroud)
或使用toBeVisible()
import {render, screen} from '@testing-library/react'
import Greeting from './greeting'
test('it renders the given name in the greeting', () => {
render(<Greeting name="John Doe"/>)
expect(screen.getByText(`Welcome John Doe!`)).toBeVisible()
})
Run Code Online (Sandbox Code Playgroud)
或两者都不是:
import {render, screen} from …Run Code Online (Sandbox Code Playgroud) 正在努力学习测试。使用测试库、Jest、React-Router v6 和 Typescript。我正在尝试找出如何测试链接。我一直在到处寻找解决方案,但找不到。使用 React-Router v6。代码如下所示(链接只是带有 href 的常规元素),只是想确保用户到达新页面(在本例中是来自忘记密码页面的登录页面)。
//omitted imports but imported all appropriate items from below
describe('ForgotPassword', () => {
test('User can navigate to login screen', async () => {
render(
<MemoryRouter initialEntries={['/forgot-password' ]}>
<ForgotPassword />
</MemoryRouter>)
userEvent.click(screen.getByRole('link', { name: 'Back to Login' }))
await waitFor(() => {
expect(screen.getByRole('heading', { name: 'Login' })).toBeInTheDocument()
})
})
//also tried:
describe('ForgotPassword', () => {
test('User can navigate to login screen', async () => {
render(
<MemoryRouter initialEntries={['/forgot-password' ]}>
<Routes>
<Route path='/forgot-password' component={<ForgotPassword …Run Code Online (Sandbox Code Playgroud) 我有一个beforeEach()渲染我的应用程序的:
describe('...', () => {
beforeEach(() => {
render(<App />);
});
...
});
Run Code Online (Sandbox Code Playgroud)
我目前正在我的应用程序中进行配置更改。config以前是 localStorage 中的布尔值,现在它有一个更合适的值,例如prod和dev。我的应用程序在首次加载时检查旧的布尔值,并将它们更改为各自的非布尔值 - 这是映射:
true -> prod
false -> dev
Run Code Online (Sandbox Code Playgroud)
我正在尝试在 Jest 中为这种转换编写测试。第一个测试背后的想法是设置 localStorage 项,重新渲染应用程序,并检查 localStorage 项是否已正确更新:
it('should show dev config when using old boolean value', () => {
const toggle = screen.getByTestId('toggle');
expect(toggle).toBeChecked();
localStorage.setItem('config', false);
// re-render app and check localStorage
render(<App />);
const toggle2 = screen.getByTestId('toggle');
expect(toggle2).not.toBeChecked();
expect(localStorage.getItem('config')).toEqual('dev');
});
Run Code Online (Sandbox Code Playgroud)
但是,此测试可能会引发错误,因为应用程序现在呈现两次而不是一次:
TestingLibraryElementError: Found multiple elements by: [data-id="toggle"] …Run Code Online (Sandbox Code Playgroud) 我正在尝试遵循 TDD,并且span5 秒后应该会出现在屏幕上。我根本没有实现跨度,所以测试应该失败,但目前它通过了测试expect(messageSpan).toBeInTheDocument。
这是我的两个测试:
it("doesn't show cta message at first", () => {
render(<FAB />);
const messageSpan = screen.queryByText(
"Considering a career in nursing? Join our team!"
);
expect(messageSpan).toBeNull(); // passes, as it should
});
it("should show the cta message after 5 secs", () => {
render(<FAB />);
setTimeout(() => {
const messageSpan = screen.getByText( // also tried queryByText instead of get
"Considering a career in nursing? Join our team!"
);
expect(messageSpan).toBeInTheDocument(); // also passes, even …Run Code Online (Sandbox Code Playgroud) 我需要一种方法来测试一个组件,其中另外两个组件是延迟加载的。
我们正在使用webpack 模块联合。因此,这里ComponentOne和ComponentTwo是在组件内部延迟加载的微前端App。因此,App这里的组件是包含两个应用程序并提供它们之间的路由的容器应用程序。
我的App.tsx看起来像这样:
import { Suspense, lazy } from 'react';
import { Route, Routes } from 'react-router-dom';
const ComponentOne = lazy(() => import('components/ComponentOne));
const ComponentTwo = lazy(() => import('components/ComponeentTwo'));
export const App = () => {
return (
<Suspense fallback={<div>FallbackDummy</div>}>
<Routes>
<Route path="/" element={<ComponentOne />} />
<Route path="/two" element={<ComponentTwo />} />
</Routes>
</Suspense>
);
};
Run Code Online (Sandbox Code Playgroud)
这个应用程序组件在我的文件中使用bootstrap.tsx如下:
import { render } from 'react-dom';
import { BrowserRouter …Run Code Online (Sandbox Code Playgroud) reactjs webpack jestjs react-testing-library webpack-module-federation
我正在尝试测试使用反应测试库构建的表
我正在使用 debug 输出
<body>
<div>
<div
class="table-wrapper"
>
<div
class="table-component__header"
/>
<table
class="test-table"
>
<tbody>
<tr>
<td
class="text-grid-item"
data-testid="text-grid-item"
>
test table data
</td>
</tr>
</tbody>
<tfoot
class="table_footer"
>
<tr>
<td />
</tr>
</tfoot>
</table>
</div>
</div>
</body>
Run Code Online (Sandbox Code Playgroud)
我试图断言test table data那里有
expect(findByTestId('text-grid-item')).toHaveTextContent('test table dat')
Run Code Online (Sandbox Code Playgroud)
但它失败了
received value must be a Node.
Received has type: object
Received has value: {}
Run Code Online (Sandbox Code Playgroud)
我怎样才能断言文本test table data在那里
import React from 'react'
import { render } from '@testing-library/react'
import { Table …Run Code Online (Sandbox Code Playgroud) 如何使用react-testing-library在MUI日期选择器的TextField输入中输入user-event内容?我可以看到正在应用面具
我已经尝试userEvent.type(inputEl, '1')过并且userEvent.keyboard('1'). 在这两种情况下,输入都保持为空。
我当前的假设是,重新渲染将我的更新替换为高阶组件的空状态(这是有道理的,基于应用程序的输入日期格式掩码)。
文档示例按预期工作,因此我的问题特定于MUI datepicker。
可以在此沙箱中找到该组件(和测试)的淡化版本。
下面是渲染的 HTML 的副本,以证明我正在使用 a 定位输入元素data-testid,但这不起作用:
screen.getByTestId('date-selector-text-field').outerHTML:
<input
aria-invalid="false"
placeholder="dd / mm / yyyy"
readonly=""
type="text"
aria-readonly="true"
aria-label="Choose date"
data-testid="date-selector-text-field"
class="MuiOutlinedInput-input MuiInputBase-input css-1t8l2tu-MuiInputBase-input-MuiOutlinedInput-input"
value=""
aria-describedby="mui-1-helper-text"
id="mui-1"
>
Run Code Online (Sandbox Code Playgroud) javascript datepicker material-ui react-testing-library user-event
我正在学习React测试库(多年其他语言的TDD经验)
\nReact 测试库的文档说,当getByText失败时,它“但是会打印正在测试的 DOM 的状态”:
https://testing-library.com/docs/dom-testing-library/api-debugging/
\n\n然而,在当前的 RTL 中,这种情况不会发生在我身上。
\n相反,我得到这个:
\n \xe2\x97\x8f loads and displays greeting\n\n TestingLibraryElementError: Unable to find an element with the text: the current weather is: overcast clouds. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.\n\n Ignored nodes: comments, <script />, <style />\n <h1\n data-testid="currentWeatherOutput"\n />\n\n 27 | …Run Code Online (Sandbox Code Playgroud) reactjs ×9
jestjs ×5
javascript ×4
datepicker ×1
material-ui ×1
testing ×1
typescript ×1
unit-testing ×1
user-event ×1
webpack ×1