我正在使用 TypeScript 构建一个 React Native 应用程序。我正在使用React Native 测试库进行组件测试。
我有一个简单的组件,它呈现两个可点击的图标和一个文本。这是一个可以递增和递减数字的计数器。
import React, { PureComponent } from "react";
import { Text, TouchableOpacity, View } from "react-native";
import { Button, Icon } from "react-native-elements";
import { getIconName } from "../../services/core";
import styles from "./styles";
export interface AmountButtonProps {
amount: number;
onDecrement: () => void;
onIncrement: () => void;
size: "small" | "large";
}
export class AmountButtons extends PureComponent<AmountButtonProps> {
render() {
const { amount, onDecrement, onIncrement, size } = this.props;
const …Run Code Online (Sandbox Code Playgroud) unit-testing typescript reactjs react-native react-testing-library
我正在尝试按照Reat-Testing-Library 文档中的本指南来包装我想要测试的所有组件。我这样做是因为我需要访问在我正在测试的组件中的 _app.js 中定义的各种上下文提供程序。
这是我的 /pages/_app.js 文件:
export class MyApp extends App {
public componentDidMount() {
const jssStyles = document.querySelector("#jss-server-side");
if (jssStyles && jssStyles.parentNode) {
jssStyles.parentNode.removeChild(jssStyles);
}
}
public render() {
const { Component, pageProps, apolloClient } = this.props;
return (
<Container>
<StateProvider>
<ThemeProvider theme={theme}>
<ApolloProvider client={apolloClient}>
<CssBaseline />
<Component {...pageProps} />
<SignUp />
<Snackbar />
</ApolloProvider>
</ThemeProvider>
</StateProvider>
</Container>
);
}
}
export default withApollo(MyApp);
Run Code Online (Sandbox Code Playgroud)
这是我的 /utils/testProviders.js 文件:
class AllTheProvidersWrapped extends App {
public componentDidMount() {
const …Run Code Online (Sandbox Code Playgroud) 让我们假设一个组件在 render 方法中返回 null,基于一些 prop。
使用 expect 来确保不呈现组件的最佳方法是什么?
例子:
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import Pagination from '../Pagination';
it('should not render if totaPages is 0', () => {
const { container } = render(<Pagination activePage={1} totalPages={0} />);
expect(container.firstChild).toBeNull();
});
Run Code Online (Sandbox Code Playgroud)
上面的代码够吗?
javascript testing unit-testing reactjs react-testing-library
概述:
问题:
我是测试新闻,这是我的问题
我有那个简单的登录组件:
import React, { useState } from "react";
export default function Login() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
function handleLogin(event) {
event.preventDefault();
console.log(email, password);
}
return (
<form data-testid="login-form" onSubmit={handleLogin}>
<input
data-testid="useremail"
type="email"
placeholder="Email"
value={email}
onChange={event => setEmail(event.target.value)}
/>
<input
data-testid="userpassword"
type="password"
placeholder="Password"
value={password}
onChange={event => setPassword(event.target.value)}
/>
<button onClick={handleLogin}>login</button>
</form>
);
}
Run Code Online (Sandbox Code Playgroud)
我在这里我的测试尝试:
import React from "react";
import Login from "../pages/Login";
import { render, fireEvent } from "@testing-library/react";
describe("Login component", () => { …Run Code Online (Sandbox Code Playgroud) 在我当前的 React 项目中,我正在测试一个组件,其中包括Material UI 中的Dialog 组件作为子组件。
假设它必须onClose()在用户按下Esc键时运行该功能。我手动测试了它,它运行得非常好。现在我正在做同样的测试,这次使用Jest + React Testing Library。你可以看到下面的代码:
fireEvent.keyDown(container, {
key: "Escape",
code: "Escape",
keyCode: 27,
charCode: 27
});
Run Code Online (Sandbox Code Playgroud)
并且测试没有通过。经过一些调试后,我意识到该事件实际上已被触发,但由于某种原因并未对<Dialog/>组件产生影响。
所以我确实在 Google Chrome 上运行了该组件,并使用以下代码从开发工具控制台触发了相同的事件:
document.dispatchEvent(
new KeyboardEvent(
"keydown", {
key: "Escape",
code: "Escape",
keyCode: 27,
charCode: 27
}
)
);
Run Code Online (Sandbox Code Playgroud)
......它也不起作用。
我该怎么做才能通过此测试?
我正在使用反应测试库进行组件测试。材质 UI 选择选项在弹出窗口中呈现。调试不列出选项。在选择选项的情况下如何触发点击事件。
以下是我选择的组件。
import TextField from '@material-ui/core/TextField';
import { MenuItem } from '@material-ui/core';
<TextField
select
id="fruit"
inputProps={{ id: "fruit" }}
SelectProps={{
SelectDisplayProps: {
'data-testid': "fruit"
}
}}
fullWidth
variant="outlined"
{...errors}
>
{options.map(option => (
<MenuItem key={option[valueFieldName]} value={option[valueFieldName]}>
{option[labelFieldName]}
</MenuItem>
))}
</TextField>
Run Code Online (Sandbox Code Playgroud)
什么查询选择器应该用于 onclick 事件。
这是 debug() 记录该字段的方式
<div class="MuiFormControl-root MuiTextField-root MuiFormControl-fullWidth">
<label
class="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-formControl MuiInputLabel-animated MuiInputLabel-outlined"
data-shrink="false"
for="fruit"
id="fruit-label"
>
Action on failure
</label>
<div class="MuiInputBase-root MuiOutlinedInput-root MuiInputBase-fullWidth MuiInputBase-formControl">
<div
aria-haspopup="listbox"
aria-labelledby="fruit-label fruit"
class="MuiSelect-root MuiSelect-select MuiSelect-selectMenu MuiSelect-outlined MuiInputBase-input …Run Code Online (Sandbox Code Playgroud) 我该如何解决这个问题。我只是想创建一个测试来确保该组件呈现,但由于某种原因,即使该组件已经在内部,仍然会出现此问题<Router>。
我在这里读过其他类似的问题,答案都说将组件放入<Router/>,但这对我来说似乎不是问题。请告诉我我错过了什么?
** 我的应用程序.tsx**
import './App.scss';
import { AuthContexProvider } from './Utils/Contexs/AuthContext';
import { Routes, Route } from 'react-router-dom';
import { LogoLarge } from './Components/Logo/Logo';
import { SignInView } from './Views/SignInView';
import { ErrorPage } from './Views/ErrorView';
import { SignUpView } from './Views/SignUpView';
import { SwipeView } from './Views/SwipeView';
import { ResetPasswordView } from './Views/ResetPasswordView';
import { CreateProfileView } from './Views/CreateProfileView';
import { PrivateRoute } from './Utils/PrivateRoute';
import { ProfileView } from './Views/ProfileView';
import { SwipeContexProvider …Run Code Online (Sandbox Code Playgroud) testing reactjs jestjs react-router-dom react-testing-library
我想测试我为导航创建的侧边栏是否有效,这是我所做的一个简单示例
<ul>
<li><Link to="/location1">location 1</Link></li>
<li><Link to="/location2">location 2</Link></li>
</ul>
Run Code Online (Sandbox Code Playgroud)
这是我的测试
const routerWrapper = ({children}) => <BrowserRouter>{children}</BrowserRouter>
// The first one runs fine
it('navigation to location 1' , () => {
render(<SideBar/> , {wrapper:routerWrapper})
// get the element and click on it
// check if title of page is correct
})
it('navigation to location 2' , () => {
render(<SideBar/> , {wrapper:routerWrapper})
// can't run because location is at /location1
})
Run Code Online (Sandbox Code Playgroud)
当我使用 RTL 测试导航时,第一个测试运行良好,但之后位置仍保留在该目录中以进行下一个测试,如何在每次测试后清除位置?或者有什么建议我应该如何测试导航?
\n我正在学习 React 测试,但 fireEvent 不会改变我输入的值。无奈,不知道为什么?
\n我正在渲染 BuyPlace 组件。在这个组件中,我有一个包含输入组件的表单(这些组件只是带有输入的标签,我将道具传递给表单上的这个组件)。
\n在 screen.debug() 上,我可以看到我的组件是使用此表单和所有这些输入正确呈现的。
\n另外,我的输入在我的测试中被正确捕获,我检查了这一点。
\n这是我的测试:
\ntest("should change input value", async () => {\nrender(\n<HashRouter>\n<UserContext.Provider value={{ user: true }}>\n<BuyPlace />\n</UserContext.Provider>\n</HashRouter>\n);\nconst nameInputEl = screen.getByPlaceholderText("Podaj w\xc5\x82asn\xc4\x85 nazw\xc4\x99");\nfireEvent.change(nameInputEl, {\ntarget: { value: "Micha\xc5\x82" },\n});\nawait waitFor(() => {\nexpect(nameInputEl.value).toBe("Micha\xc5\x82");\n});\n});\nRun Code Online (Sandbox Code Playgroud)\n测试未通过。当然,我的应用程序运行正常,但在测试中它不起作用。
\n这是我的组件上的handleInputChange:
\nconst handleInputChange = (e: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) => {\nsetInputValues((prevValues) => {\nreturn {\n...prevValues,\n[e.target.name]: e.target.value,\n}\n});\n};\nRun Code Online (Sandbox Code Playgroud)\n我发现的每个解决方案都不起作用...我的输入值始终是空字符串。有人可以帮我弄这个吗?我想学习编写好的测试,但我不知道问题出在哪里。
\n编辑\n我在 screen.debug() 上看到了一些有趣的东西。
\n我在测试中的输入在没有 onchange 属性的情况下呈现,这在测试中正常吗?看一下这个:
\n <input\n id="name"\n name="name"\n placeholder="Podaj w\xc5\x82asn\xc4\x85 nazw\xc4\x99"\n type="text"\n …Run Code Online (Sandbox Code Playgroud) reactjs ×8
jestjs ×6
testing ×5
javascript ×2
material-ui ×2
unit-testing ×2
next.js ×1
react-native ×1
setstate ×1
tdd ×1
typescript ×1