我被困在这里进行一个测试,我想验证在滚动浏览由react-window导入的列表组件后,正在渲染不同的项目。该列表位于一个表格组件内,该组件保存了 React 上下文中的滚动位置,这就是我需要测试整个表格组件的原因。
不幸的是,滚动事件似乎没有效果,列表仍然显示相同的项目。
测试看起来像这样:
render(
<SomeProvider>
<Table />
</SomeProvider>
)
describe('Table', () => {
it('scrolls and renders different items', () => {
const table = screen.getByTestId('table')
expect(table.textContent?.includes('item_A')).toBeTruthy() // --> true
expect(table.textContent?.includes('item_Z')).toBeFalsy() // --> true
// getting the list which is a child component of table
const list = table.children[0]
fireEvent.scroll(list, {target: {scrollY: 100}})
expect(table.textContent?.includes('item_A')).toBeFalsy() // --> false
expect(table.textContent?.includes('item_Z')).toBeTruthy() // --> false
})
})
Run Code Online (Sandbox Code Playgroud)
任何帮助将非常感激。
我已经使用 jest 版本、26.0.0react-testing-library 和 node 版本编写了单元测试14.2.0。下面是我的 React 功能组件,它有一个按钮,单击后会发出 ajax 调用来下载报告文件。
const ReportListTable = () => {
const { downloadReports } = useReports();
const onClickDownload = () => {
let fileName = `Report.zip`;
downloadReports()
.then((response) => response.arrayBuffer())
.then((data) => {
const blob = new Blob([data], { type: "octet/stream", endings: "native" });
const url = window.URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.setAttribute("href", url);
anchor.setAttribute("download", fileName);
anchor.click();
window.URL.revokeObjectURL(url);
})
.catch((error?: Error | Response) => {
if (error instanceof Error) { …Run Code Online (Sandbox Code Playgroud) 我正在使用 Jest 和 React 测试库来测试组件。
我正在尝试测试模式,但我遇到了一个奇怪的问题。当我尝试在触发事件之前通过文本获取“模态标题”时,我收到错误,因为渲染的文档中不存在“模态标题”。如果我在触发“打开模态”按钮后尝试查找“模态标题”,它就会起作用。但我还想测试模态在触发事件之前不存在。所以我决定期望“模态标题”为假,但这不起作用。到目前为止,我已经尝试过 toBe(false)、toBeFalsy()、toBeNull() ,甚至尝试查看长度是否为 0,但没有任何提到的工作。我该如何解决这个问题。
it('Test Modal', () => {
const { getByText } = render(<TestApp />);
expect(getByText('Modal Title')).toBe(false);
fireEvent.click(getByText('Open Modal'));
expect(getByText('Modal Title')).toBeTruthy();
})
Run Code Online (Sandbox Code Playgroud) 酶,ReactTestUtils和用于反应测试的react-testing-library有什么区别?
ReactTestUtils文档说:
ReactTestUtils使您可以轻松地在您选择的测试框架中测试React组件。
酵素文件只是说:
Enzyme是一种用于React的JavaScript测试实用程序,使断言,操作和遍历React Components的输出变得更加容易。
React-Testing-Library文档:
react-testing-library是用于测试React组件的非常轻巧的解决方案。它在react-dom之上提供了轻量级的实用程序功能。
为什么实际上每个解决方案都更容易,而另一个解决方案却无法实现?
我正在尝试使用打字稿中的react-testing-library创建带有样式的Material-UI组件的测试。我发现很难访问组件的内部功能以进行模拟和断言。
Form.tsx
export const styles = ({ palette, spacing }: Theme) => createStyles({
root: {
flexGrow: 1,
},
paper: {
padding: spacing.unit * 2,
margin: spacing.unit * 2,
textAlign: 'center',
color: palette.text.secondary,
},
button: {
margin: spacing.unit * 2,
}
});
interface Props extends WithStyles<typeof styles> { };
export class ExampleForm extends Component<Props, State> {
async handleSubmit(event: React.FormEvent<HTMLFormElement>) {
// Handle form Submit
...
if (errors) {
window.alert('Some Error occurred');
return;
}
}
// render the form
}
export default …Run Code Online (Sandbox Code Playgroud) 您好我想测试与材料的UI创建一个Slider组件,但我不能让我的测试通过。我想使用fireEventwith测试值的变化@testing-library/react。我一直在关注这篇文章以正确查询 DOM,但我无法获得正确的 DOM 节点。
提前致谢。
<Slider /> 成分
// @format
// @flow
import * as React from "react";
import styled from "styled-components";
import { Slider as MaterialUISlider } from "@material-ui/core";
import { withStyles, makeStyles } from "@material-ui/core/styles";
import { priceRange } from "../../../domain/Search/PriceRange/priceRange";
const Wrapper = styled.div`
width: 93%;
display: inline-block;
margin-left: 0.5em;
margin-right: 0.5em;
margin-bottom: 0.5em;
`;
// ommited code pertaining props and styles for simplicity
function Slider(props: SliderProps) {
const initialState = …Run Code Online (Sandbox Code Playgroud) 我正在尝试测试我的路由器是否按预期工作。但我无法让路由器指向另一个位置/
这是我的简化测试代码。
App.tsx
import React from 'react';
import {Route, Switch, BrowserRouter} from 'react-router-dom';
const App: React.FC = () => {
return (
<div>
<BrowserRouter>
<Switch>
<Route path={'/test'}>test</Route>
<Route path={'/'}>index</Route>
</Switch>
</BrowserRouter>
</div>
);
};
export default App;
Run Code Online (Sandbox Code Playgroud)
App.test.tsx
import React from 'react';
import App from './App';
import {MemoryRouter} from 'react-router-dom';
import {render} from '@testing-library/react';
test('renders /test route', async () => {
const app = render(
<MemoryRouter initialEntries={['/test']} initialIndex={0}>
<App/>
</MemoryRouter>);
expect(app.getByText(/test/i)).toBeInTheDocument();
});
Run Code Online (Sandbox Code Playgroud)
我收到以下错误消息
Error: Unable to find an element …Run Code Online (Sandbox Code Playgroud) 为什么打字稿在这里抱怨变量未分配?我是否遗漏了一些明显的范围?
test('test', async () => {
let renderResult: RenderResult;
await act(async () => {
renderResult = render(<Component />);
});
await act(async () => {
renderResult.rerender(<Component />);
});
// ERRROR: Variable 'renderResult' is used before being assigned.ts(2454)
expect(renderResult.container.firstElementChild!.getAttribute('src')).toBe('original');
});
Run Code Online (Sandbox Code Playgroud) data-testid我通过查找带有with的按钮来调用函数"show_more_button"
<OurSecondaryButton test={"show_more_button"} onClick={(e) => showComments(e)} component="span" color="secondary">
View {min !== -1 && min !== -2 ? min : 0} More Comments
</OurSecondaryButton>
Run Code Online (Sandbox Code Playgroud)
显示评论
const showComments = (e) => {
e.preventDefault();
if (inc + 2 && inc <= the_comments) {
setShowMore(inc + 2);
setShowLessFlag(true);
} else {
setShowMore(the_comments);
}
};
Run Code Online (Sandbox Code Playgroud)
这使得这个
const showMoreComments = () => {
return filterComments.map((comment, i) => (
<div data-testid="comment-show-more" key={i}>
<CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
</div>
));
};
Run Code Online (Sandbox Code Playgroud)
在执行 …
我目前正在学习 React-Testing-Library。
我想测试鼠标与元素的交互。目前我有点不清楚 userEvent.click(element) 和 fireEvent.click(element) 之间的区别。两者都推荐使用,并且在下面的示例中它们是否被正确实施?
const mockFunction = jest.fn(() => console.info('button clicked'));
const { getByTestId } = render(<MyAwesomeButton onClick={mockFunction} />);
const myAwesomeButton = getByTestId('my-awesome-button');
// Solution A
fireEvent(myAwesomeButton)
expect(mockFunction.toHaveBeenCalledTimes(1);
// Solution B
userEvent.click(myAwesomeButton);
expect(mockFunction).toHaveBeenCalledTimes(1);
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的澄清。
reactjs ×9
jestjs ×4
material-ui ×2
typescript ×2
enzyme ×1
javascript ×1
react-router ×1
react-window ×1
testing ×1
unit-testing ×1