我正在测试一个组件,其中 if ItemLength = 1,render返回null。
const { container, debug } = render(<MyComp ItemLength={1} />);
当我调用debug()我的测试时,它显示一个<div />. 如何检查组件在我的测试中是否返回一个空的 div?
我正在使用 material-ui自动完成组件并尝试使用 react-testing-library 对其进行测试
组件:
/* eslint-disable no-use-before-define */
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
import React from 'react';
export default function ComboBox() {
const [autocompleteInputValue, setAutocompleteInputValue] = React.useState('');
const [isAutocompleteOpen, setIsAutocompleteOpen] = React.useState(false);
const renderInput = (params: any) => <TextField {...params} label='openOnFocus: false' variant='outlined' />;
const getTitle = (option: any) => option.title;
const handleAutocompleteInputChange = (event: any, value: string) => {
setAutocompleteInputValue(value);
};
const updateAutocompletePopper = () => {
setIsAutocompleteOpen(!isAutocompleteOpen);
};
return (
<Autocomplete …Run Code Online (Sandbox Code Playgroud) autocomplete typescript reactjs material-ui react-testing-library
由于某种原因,我的自定义 tsconfig 文件没有在 jest.config.ts 中被选取。这是我的 jest.config.ts:
module.exports = {
setupFilesAfterEnv: [`./jest.setup.ts`],
testEnvironment: `jsdom`,
roots: [
`<rootDir>/test`
],
testMatch: [
`**/__tests__/**/*.+(ts|tsx|js)`,
`**/?(*.)+(spec|test).+(ts|tsx|js)`
],
transform: {
"^.+\\.(ts|tsx)$": `ts-jest`
},
globals: {
"ts-jest": {
tsConfig: `tsconfig.jest.json`
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道该配置的其他部分正在应用。例如,如果我删除全局变量上面的键,我的测试就不会运行。另外,我知道 tsconfig.jest.json 文件中指定的更改是修复我的测试所必需的更改,因为如果我在主 tsconfig.json 文件中进行相同的更改,我的测试运行良好。
我还尝试将所需的 tsconfig 编译器选项直接放入 jest.config.ts 文件中,但这似乎也不起作用:
module.exports = {
setupFilesAfterEnv: [`./jest.setup.ts`],
testEnvironment: `jsdom`,
roots: [
`<rootDir>/test`
],
testMatch: [
`**/__tests__/**/*.+(ts|tsx|js)`,
`**/?(*.)+(spec|test).+(ts|tsx|js)`
],
transform: {
"^.+\\.(ts|tsx)$": `ts-jest`
},
globals: {
"ts-jest": {
tsConfig: {
jsx: `react`
}
}
}
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用react-testing-library 测试Select 组件的onChange事件。
我使用getByTestId效果很好的元素获取元素,然后设置元素的值,然后调用fireEvent.change(select);但onChange从未调用过并且状态从未更新过。
我已经尝试使用 select 组件本身以及获取对底层input元素的引用,但都不起作用。
任何解决方案?或者这是一个已知问题?
我正在使用React 测试库对我的 ReactJS 代码进行单元测试。UI 中有几个异步事件,例如获取数据和单击按钮时显示新页面。React 代码有点像这样:
// Inside ParentComponent.tsx
const [isChildVisible, setChildVisibility] = useState(false);
const showChild = () => setChildVisibility(true);
return(
<>
<button data-testid="show-child" onClick={showChild}>Show Child</button>
{isChildVisible && <ChildComponent {..childProps}/>}
</>
)
Run Code Online (Sandbox Code Playgroud)
在ChildComponent安装时,它会获取一些数据,然后使用水合数据重新渲染自身。我的单元测试如下所示:
jest.mock('../../../src/service'); // mock the fetch functions used by ChildComponent to fetch its data
describe('ParentComponent', () => {
test('renders ChildComponent on button click', async () => {
const screen = render(<ParentComponent />);
userEvent.click(screen.getByTestId('show-child'));
await (waitFor(() => screen.getByText('text rendered by child')));
});
});
Run Code Online (Sandbox Code Playgroud)
当我运行此测试时,出现错误"TestingLibraryElementError: …
我在悬停上显示了一个弹出窗口,我想使用 Jest 和 React 测试库对其进行测试,以查看该元素是否默认隐藏。
当我手动测试时一切正常,而当我使用 RTL 测试时一切正常。
我尝试使用 not.toBeInTheDocument 和 not.toBeVisible 但似乎该元素始终存在于 DOM 中,不知道如何从 DOM 中删除它
JSX 代码:
<label
htmlFor="terms_and_conditions"
className="terms_and_conditions_box"
>
I agree with{" "}
<span className="terms_and_conditions_text" style={{ color: "blue" }}>
Terms and conditions
</span>
<div className="pop_over">No ice cream will be delivered</div>
</label>
Run Code Online (Sandbox Code Playgroud)
CSS代码:
.terms_and_conditions_text:hover + .pop_over {
display: block;
}
.pop_over {
background: rgb(199, 196, 196);
padding: 2rem;
width: 14rem;
border-radius: 15px;
position: absolute;
right: -18rem;
top: -2rem;
display: none;
}
Run Code Online (Sandbox Code Playgroud)
测试代码:
test("popover responds to hover", () …Run Code Online (Sandbox Code Playgroud) 我有一些组件正在呈现已经单独测试的另一个组件(FetchNextPageButton),例如:
const News = () => (
<div>
<h1>News</h1>
...
<FetchNextPageButton query={NEWS_QUERY} path="viewer.news" />
</div>
)
const Jobs = () => (
<div>
<h1>Jobs</h1>
...
<FetchNextPageButton query={JOBS_QUERY} path="viewer.jobs" />
</div>
)
const Posts = () => (
<div>
<h1>Posts</h1>
...
<FetchNextPageButton query={POSTS_QUERY} path="viewer.posts" />
</div>
)
Run Code Online (Sandbox Code Playgroud)
问题是我不想为已经在其他地方测试过的功能在这些组件中的每一个上添加测试,所以我认为这应该足以测试组件是否已呈现并且我正在通过正确的道具。
我本来可以使用 Enzyme 轻松地进行测试,如下所示:
expect(wrapper.find('FetchNextPageButton').props()).toMatchObject({
query: NEWS_QUERY,
path: "viewer.news"
})
Run Code Online (Sandbox Code Playgroud)
所以我想知道使用React 测试库来测试它的最佳方法是什么。
我正在尝试使用react-testing-library测试材质 ui 文本字段。
我面临的问题是,为了测试材质 ui textField 我必须使用这个属性方法
screen.getByLabelText()
Run Code Online (Sandbox Code Playgroud)
这是有效的,但是我不想在 UI 上显示标签,我希望标签保持隐藏,因为我已经在使用 Material UI <FormLabel>。
我尝试使用 inputProps 并data-testId使用该getByTestId()方法传递元素。但我收到这个错误
TestingLibraryElementError:通过以下方式找到多个元素:[data-testid =“bio”]
Run Code Online (Sandbox Code Playgroud)(If this is intentional, then use the `*AllBy*` variant of the query (like `queryAllByText`, `getAllByText`, or `findAllByText`)).
editForm.test.tsx
import "@testing-library/jest-dom";
import React from "react";
import { createMount } from "@material-ui/core/test-utils";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
import EditProfileForm from "./editForm";
import { render as testRender, fireEvent, screen, getByText } from "@testing-library/react";
const …Run Code Online (Sandbox Code Playgroud) 当我运行测试时,即使测试有效,它也会向我发送警告。经过一些研究,我似乎必须把它放在一个,act但它是同一件事
console.error
Warning: An update to Formik 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 printWarning (node_modules/react-dom/cjs/react-dom.development.js:67:30)
at error (node_modules/react-dom/cjs/react-dom.development.js:43:5)
at warnIfNotCurrentlyActingUpdatesInDEV (node_modules/react-dom/cjs/react-dom.development.js:24064:9)
at dispatch (node_modules/react-dom/cjs/react-dom.development.js:16135:9)
at node_modules/formik/src/Formik.tsx:327:11 …Run Code Online (Sandbox Code Playgroud) 我正在尝试制作一个打字稿前端,但我无法使用导入,react-dom/client因为我已经缩小到我的测试库/反应版本与我的反应版本不对应的问题。我已经尝试了多个降级版本,但似乎无法使其工作。
对此有什么解决办法吗?我将package.json在下面附上我的文件。
{
"name": "balls",
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.12.4",
"@material-ui/icons": "^4.11.3",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "12.1.5",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.1",
"@types/node": "^16.11.35",
"@types/react": "^16.8.6",
"@types/react-dom": "^16.8.6",
"@vercel/node": "^1.15.2",
"axios": "^0.27.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "5.0.1",
"typescript": "^4.6.4",
"vercel": "^24.2.3",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead", …Run Code Online (Sandbox Code Playgroud) reactjs ×10
jestjs ×3
material-ui ×2
autocomplete ×1
enzyme ×1
formik ×1
javascript ×1
next.js ×1
ts-jest ×1
typescript ×1