我有两个根据屏幕尺寸显示的按钮(对于中屏幕,一个按钮,对于其他屏幕,另一个按钮)。我使用 Material UI 的 MediaQuery 和 theme.breakpoints 来定义屏幕尺寸。
这是我的 UI 代码,我在 React 中使用 Typescript。
import React from "react";
import Button from "@material-ui/core/Button";
import useMediaQuery from "@material-ui/core/useMediaQuery";
import { useTheme } from "@material-ui/core/styles";
export default function SimpleCard() {
const theme = useTheme();
const isMd = useMediaQuery(theme.breakpoints.only("md"));
return (
<div>
{isMd ? (
<Button
data-testid="mediumScreenButton"
onClick={() => console.log("medium")}
>
medium screen
</Button>
) : (
<Button
data-testid="otherScreenButton"
onClick={() => console.log("other")}
>
Other screen
</Button>
)}
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试代码
import …Run Code Online (Sandbox Code Playgroud) unit-testing jestjs material-ui react-testing-library react-hooks
我正在尝试测试一个使用react-redux 进行状态管理的组件。
为了快速测试,我想模拟 useSelector,如下所示:
const templates = [
{
id: ...,
name: ...,
...
},
{
id: ...,
name: ...,
...
},
]
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useSelector: jest.fn(),
}));
describe('some awesome description', () => {
beforeEach(() => {
useSelector.mockImplementation(callback => callback(templates));
});
});
Run Code Online (Sandbox Code Playgroud)
但在运行测试时,会失败,如下所示:
TypeError: Cannot read properties of undefined (reading 'ids')
141 | describe('layouts/TemplatesPanel', () => {
142 | beforeEach(() => {
> 143 | useSelector.mockImplementation(callback => callback(templates));
| ^
Run Code Online (Sandbox Code Playgroud) unit-testing reactjs jestjs react-redux react-testing-library
我正在测试 React Native 0.68.2/jest 29.0 的组件视图Home。简单的测试用例是从 jest doc 复制的:
import React from 'react';\nimport { NavigationContainer } from '@react-navigation/native';\nimport { render, cleanup, screen, fireEvent } from "@testing-library/react-native";\nimport App from '../App';\n\ndescribe ('App ', () => {\n //afterEach(cleanup);\n test ('shall stack screens', async () => {\n const component = (<NavigationContainer>\n <App />\n </NavigationContainer>);\n const {getByText} = render(component);\n\n await waitFor(() => getByText('AppSplash'));\n \n\n })\n})\nRun Code Online (Sandbox Code Playgroud)\n这是 App.js:
\n import React, {useState, useContext, Component} from 'react';\n import { NavigationContainer } from '@react-navigation/native';\n …Run Code Online (Sandbox Code Playgroud) 我在尝试学习如何测试 next.js 应用程序时收到此错误消息我尝试从配置顶部的 utils 导入文本编码器以及测试文件,但没有成功
ReferenceError: TextEncoder is not defined
at Object.<anonymous> (node_modules/whatwg-url/lib/encoding.js:2:21)
at Object.<anonymous> (node_modules/whatwg-url/lib/url-state-machine.js:5:34)
at Object.<anonymous> (node_modules/whatwg-url/lib/URL-impl.js:2:13)
at Object.<anonymous> (node_modules/whatwg-url/lib/URL.js:442:14)
at Object.<anonymous> (node_modules/whatwg-url/webidl2js-wrapper.js:3:13)
at Object.<anonymous> (node_modules/whatwg-url/index.js:3:34)
at Object.<anonymous> (node_modules/mongodb-connection-string-url/src/index.ts:1:1)
at Object.<anonymous> (node_modules/mongodb/src/connection_string.ts:3:1)
at Object.<anonymous> (node_modules/mongodb/src/mongo_client.ts:11:1)
at Object.<anonymous> (node_modules/mongodb/src/change_stream.ts:17:1)
at Object.<anonymous> (node_modules/mongodb/src/index.ts:3:1)
at Object.<anonymous> (node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js:8:16)
at Object.<anonymous> (node_modules/mongoose/lib/drivers/node-mongodb-native/index.js:7:18)
at Object.<anonymous> (node_modules/mongoose/lib/index.js:7:25)
at Object.<anonymous> (node_modules/mongoose/index.js:8:18)
at Object.<anonymous> (library/mongoDB.js:15:56)
at Object.<anonymous> (library/players.js:15:18)
at Object.<anonymous> (pages/index.js:18:18)
at Object.<anonymous> (tests/index.test.js:6:53)
Run Code Online (Sandbox Code Playgroud)
玩笑配置文件
const nextJest = require('next/jest')
const createJestConfig = nextJest({
dir: './',
})
const …Run Code Online (Sandbox Code Playgroud) 当使用 React 测试库编写单元测试时,我们可以通过元素的角色来访问元素getByRole。
例如,如果元素是heading,则它有level选项:
const headingNode = screen.getByRole('heading', { level: 3 });
Run Code Online (Sandbox Code Playgroud)
或者如果是的话radio它有name:
const radioNode = screen.getByRole('radio', { name: 'high'});
Run Code Online (Sandbox Code Playgroud)
我的问题是,在哪里可以找到每种类型的所有可能选项?有这方面的文档吗?没找到。
unit-testing accessibility reactjs jestjs react-testing-library
当尝试测试调度异步 thunk 的组件时,我收到以下警告。它们是由于测试完成后执行的更新而显示的。
console.error
Warning: An update to App inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
at App (/home/karlosos/Dev/nokia/playground/testing-redux/src/App.tsx:6:34)
at Provider (/home/karlosos/Dev/nokia/playground/testing-redux/node_modules/react-redux/lib/components/Provider.js:19:3)
at Wrapper (/home/karlosos/Dev/nokia/playground/testing-redux/src/testUtils.tsx:11:22)
at printWarning (node_modules/react-dom/cjs/react-dom.development.js:86:30)
at error (node_modules/react-dom/cjs/react-dom.development.js:60:7) …Run Code Online (Sandbox Code Playgroud) 我正在尝试测试我的组件并且测试正在通过,但是我不断收到有关在我的终端中更新的状态片段的行为警告:“警告:测试中对 Bird 的更新未包含在 act(...) .”
该警告指的是 const handleRemoveBird = () => { setShowModal(true); };状态更新。
这是否与链接到模态组件的状态有关并且它在测试之外更新?如果是这种情况(或不是),我需要等待/等待什么来修复行为警告?
我的测试:
import { screen, waitFor } from "@testing-library/react";
import user from "@testing-library/user-event";
import { renderWithProviders } from "../utils/utils-for-tests";
import Bird from "../components/Bird";
const modalContainerMock = document.createElement("div");
modalContainerMock.setAttribute("class", "modal-container");
document.body.appendChild(modalContainerMock);
const birdImgMock = jest.mock("../../components/BirdImg", () => {
return () => {
return "Bird Img Component";
};
});
const renderComponent = (bird) => {
renderWithProviders(<Bird bird={bird} />);
};
const bird = {
id: "1",
name: "blue …Run Code Online (Sandbox Code Playgroud) 我将 tRPC 与 Typescript 和 Next.js 结合使用。直到最近我的测试才失败(我认为我没有碰过它们)。我得到了错误Unexpected token 'export'。我尝试过更改我的jest.config.mjs添加transformIgnorePatterns: ["!node_modules/"]以及babel-jest
transform: {\n "^.+\\\\.tsx?$": "ts-jest",\n "^.+\\\\.(js|jsx)$": "babel-jest",\n "node_modules/variables/.+\\\\.(j|t)sx?$": "babel-jest"\n },\nRun Code Online (Sandbox Code Playgroud)\n但无济于事:(有人可以帮助我吗?这是我的错误日志。
\nTest suite failed to run\n\n Jest encountered an unexpected token\n\n Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.\n\n Out of the box Jest supports Babel, which will be used …Run Code Online (Sandbox Code Playgroud) p我有一个 TextField 组件,右侧包含一个单元 ( )。我动态地更改了该单元和文本值之间的填充useEffect,但是当我想确保它使用 Cypress 组件测试正确工作时,我阻止了。
import classNames from "classnames";
import { IProps } from "./type";
import styles from "./style.module.css";
import { useEffect, useRef } from "react";
const TextField = ({
ID,
value,
placeholder,
type,
rounded,
outline,
disabled,
icon,
unit,
onChange,
onFocus,
onBlur,
}: IProps) => {
const unitRef = useRef<HTMLParagraphElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
// How to test this hook
useEffect(() => {
if (unitRef.current && inputRef.current) {
const unitWidth = unitRef.current.getBoundingClientRect().width;
inputRef.current.style.paddingRight = `${unitWidth …Run Code Online (Sandbox Code Playgroud) 使用AirBnB的酶,我们可以设置组件的状态:
const loginComponent = shallow(<Login />);
loginComponent.setState({ error: true });
Run Code Online (Sandbox Code Playgroud)
我想使用react-testing-library做同样的事情。
谢谢!
javascript unit-testing reactjs jestjs react-testing-library
jestjs ×8
reactjs ×5
unit-testing ×4
javascript ×2
react-redux ×2
commonjs ×1
cypress ×1
es6-modules ×1
material-ui ×1
next.js ×1
react-hooks ×1
react-native-testing-library ×1
redux ×1
testing ×1