我用于@testing-library/react测试 UI 组件。无法让笑话模拟工作。
它似乎无法模拟导出函数的实现getDomElement,但会调用实际的实现。
Table.test.js 的实现
describe('Table', () => {
jest.mock('../../../../commonHelpers/getDomElement.js', () => {});
it('it renders columns', () => {
render(
<ThemeProvider>
<Table
columns={columns}
data={data}
/>
</ThemeProvider>,
);
})
})
Run Code Online (Sandbox Code Playgroud)
Table.js 的实现
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import {
useTable,
useSortBy,
useBlockLayout,
useResizeColumns,
usePagination,
} from 'react-table';
import { TableStyled as Table, TableContainer } from './styled';
import Pagination from './Pagination';
import Head from './Head';
import Body from './Body';
import TableContext …Run Code Online (Sandbox Code Playgroud) 我正在尝试在我的 React 应用程序上测试 Info HOC:
const InfoHOC = (HocComponent) => ({ message }) => (
<>
<Tooltip title={message}>
<InfoIcon />
</Tooltip>
{HocComponent}
</>
);
export default InfoHOC;Run Code Online (Sandbox Code Playgroud)
我已经简化了。但由于它使用 Material ui Tooltip 组件,我无法测试鼠标悬停时是否显示消息...
it('should display info message on <div /> mouseover', () => {
const Component = InfoHoc(<div>jest div</div>)({ message: 'jest infoHoc message' });
const { getByTitle, getByDisplayValue } = render(Component);
const icon = getByTitle('jest infoHoc message');
act(() => {
fireEvent(
icon,
new MouseEvent('mouseover', {
bubbles: true,
}),
);
});
expect(getByDisplayValue('jest …Run Code Online (Sandbox Code Playgroud)我正在尝试为我们的富文本组件之一编写测试,该组件是使用 React js 中的 slate js 编辑器实现的。因此,在编写测试时,我正在检索元素 div[contenteditable='true'],但无法模拟更改、模糊、焦点等事件。附加到编辑器组件的处理程序不会被调用。我尝试了多种组合,但没有成功。有人可以帮忙吗?是否可以使用测试库模拟 contenteditable 元素的事件(contenteditable 使用 slatejs 实现)?
contenteditable reactjs slatejs react-testing-library testing-library
我希望从 React 测试库社区获得一些专家建议和指导,以了解确保在拍摄快照之前完成 Material UI 波纹动画的最佳方法。
这个问题一直导致我们进行不稳定的测试,所有内容始终在本地通过,但是当我们在 CI 服务器上运行时,测试是间歇性的并且失败,因为动画完成的速度比本地快,这意味着它与存储的快照不匹配。
这个问题只有在我们换掉后才出现fireEvent,这对于userEventuserEvent 提供的额外操作是有意义的,但我想要的是存储不包含任何 UI 转换的快照。
我在下面创建了一个简单的测试,这将有助于说明问题(也在codesandbox上):
import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Button from "@material-ui/core/Button";
test("clicks material button with fireEvent - no ripple implication", () => {
render(
<Button variant="contained" color="primary">
Ripple
</Button>
);
const btnContainer = screen.getByRole("button", { name: /ripple/i });
expect(btnContainer).toBeInTheDocument();
screen.debug(btnContainer);
fireEvent.click(btnContainer);
screen.debug(btnContainer);
});
test("clicks material button with userEvent", async () …Run Code Online (Sandbox Code Playgroud) 我遇到的问题是,模拟的常量在之后的组件中不会改变jest.doMock。
看一下最小的仓库。
我尝试过用-mock代替doMock- 同样的错误。
应用程序.test.js
import React from "react"
import App from './App'
import '@testing-library/jest-dom'
import { render } from "@testing-library/react";
describe('testing app.js', () => {
// To reset manually mocked values
beforeEach(() => {
jest.resetModules()
});
test("SET CONSTANT TO 1", () => {
jest.doMock('./myConstants.js', () => ({
CONSTANT: {
NUMBER: 1
}
}))
const { getByText, getByLabelText } = render(<App />)
expect(getByText('1')).toBeInTheDocument()
})
test("SET CONSTANT TO 3", () => {
jest.doMock('./myConstants.js', …Run Code Online (Sandbox Code Playgroud) 我有以下问题:我需要测试在我的测试中是否调用了某个函数,但为了正确测试它,我需要按 Enter 或提交表单,但它似乎没有按预期工作。我已经尝试过以下操作:
\nfireEvent.keyDown(input, { key: \'Enter\', code: \'Enter\' });\nfireEvent.submit(input);\nRun Code Online (Sandbox Code Playgroud)\n触发我的组件的 prop 的唯一方法onSubmitEditing是按 Enter 键。
这是我正在尝试测试的代码:
\n<Input placeholder="Cirurgi\xc3\xa3o"\n testID=\'input_buscaCirurgiao_index\'\n value={this.state.text}\n autoCorrect={false}\n keyboardType={(Platform.OS === \'android\') ? \'visible-password\' : \'default\'}\n onChangeText={(item) => this.setState({ text: item })}\n onSubmitEditing={() => { this._searchPressingEnter() }} // i need to test this\n autoCapitalize=\'none\' \n/>\nRun Code Online (Sandbox Code Playgroud)\n这是该_searchPressingEnter函数的代码:
_searchPressingEnter() {\n Keyboard.dismiss()\n\n let item = this.state.text\n\n this._buscarCirurgioes(item)\n}\nRun Code Online (Sandbox Code Playgroud)\n一旦按下 Enter 键,_searchPressingEnter就应该调用该函数,从而触发该onSubmitEditing道具。
unit-testing react-native react-testing-library react-native-testing-library
export default function CommentDialog(props) {
const {
approvalValue,
handleSubmit,
handleDialog,
handleChange,
handleApprovalChange,
value,
characterCount,
maxCharacterValue,
} = props;
const { handleOpen, handleClose, open } = handleDialog;
const classes = useStyles();
return (
<>
<AddCommentButton onClick={handleOpen} />
<Dialog fullWidth onClose={handleClose} aria-labelledby="customized-dialog-title" open={open}>
<DialogTitle id="customized-dialog-title" onClose={handleClose}>
Please select an outcome for this Targeting Request
</DialogTitle>
<RadioGroup
aria-label="quiz"
name="quiz"
value={approvalValue}
onChange={handleApprovalChange}
className={classes.radioButtons}
>
<FormControlLabel value="Approved" control={<Radio color="primary" />} label="APPROVE" />
<FormControlLabel value="Denied" control={<Radio color="secondary" />} label="DENY" />
</RadioGroup>
<DialogContent>
<MarkdownEditor
id="comment-markdown"
error={characterCount >= …Run Code Online (Sandbox Code Playgroud) 我有一个Dashboard包含子组件的组件,例如Child它使用反应查询。
我有一个针对该Dashboard组件的现有单元测试,该测试开始失败,错误是:
TypeError: queryClient.defaultQueryObserverOptions is not a function
38 | const { locale } = React.useContext(LocaleStateContext);
39 | const options = getOptions(locale);
> 40 | return useQuery(
| ^
41 | rqKey,
42 | async () => {
43 | const result = await window.fetch(url, options);
Run Code Online (Sandbox Code Playgroud)
测试片段:
const queryClient = new QueryClient();
const { getByTestId, getByRole } = render(
<IntlProvider locale="en" messages={messages}>
<QueryClientProvider client={queryClient}>
<Dashboard />
</QueryClientProvider>
</IntlProvider>,
);
Run Code Online (Sandbox Code Playgroud)
我阅读了有关测试的文档:
https://react-query.tanstack.com/guides/testing#our-first-test
但我不想一定要使用,renderHook因为我对结果不感兴趣。 …
在使用 React 学习 TDD 的过程中,我注意到有不同的方法可以触发测试中元素的点击。可以通过fireEvent.click(),userEvent.click()和 来 完成HTML_ELEMENT.click()。
他们都工作得很好。经过一些研究后,我了解到userEvent.click()基本上在底层使用 fireEvent,并且它更适合自动化测试(例如 cypress),而fireEvent.click()更适合单元测试。
但我找不到两者userEvent和可以使用的fireEvent常规函数有何不同。HTML_ELEMENT.click()
使用它们而不是使用常规点击功能可以给我带来什么好处?
我有一个元素,其中静态和动态文本的组合都在同一行上。
当通过包含一些静态和动态文本的子字符串测试此行文本时,它失败,显示输出被分割成多行,并且在动态部分之前和之后进行分割。
到底是怎么回事?为什么我不能按照我期望的方式测试它?我该如何正确测试这个?
代码.jsx
const dynamicText = 'all be on one line';
return <div>This should {dynamicText} like I expect.</div>
Run Code Online (Sandbox Code Playgroud)
代码.spec.js
it('Should have dynamic text on one line', () => {
const {getByText} = render(<Code />);
expect(getByText('should all be on one line ')).toBeTruthy();
});
Run Code Online (Sandbox Code Playgroud)
测试输出
Unable to find an element with the text: ... 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 …Run Code Online (Sandbox Code Playgroud) javascript testing unit-testing reactjs react-testing-library
reactjs ×7
jestjs ×5
material-ui ×3
javascript ×2
mocking ×2
unit-testing ×2
react-native ×1
react-native-testing-library ×1
react-query ×1
slatejs ×1
testing ×1
typescript ×1