我只能用 react-test-renderer
import React, { useEffect } from 'react';
import '@testing-library/jest-dom/extend-expect';
import { render } from '@testing-library/react';
import { create } from 'react-test-renderer';
function Counter() {
const [count, setCount] = React.useState(0);
useEffect(() => {
setCount(1);
}, []);
return <>{count}</>;
}
describe('react-test-renderer', () => {
const renderer = create(<Counter />);
it('renders 0', () => {
expect(renderer.root.children).toContain('0');
});
it('renders 1', () => {
renderer.update(<Counter />);
expect(renderer.root.children).toContain('1');
});
});
describe('@testing-library/react', () => {
const screen = render(<Counter />);
it('renders 0', () => { …Run Code Online (Sandbox Code Playgroud) 尝试遵循来自https://testing-library.com/docs/example-react-router 的路由的测试示例,但 location.pathname/尽管历史上进行了推送,但仍然存在
import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
import { Router } from "react-router";
import { createMemoryHistory } from 'history'
import { prettyDOM } from '@testing-library/dom'
import App from '../../App.js'
let container = null;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
afterEach(() => {
unmountComponentAtNode(container);
container.remove();
container = null;
});
test('Shows username in navbar after logging in', async () => {
const fakeLoginResponse …Run Code Online (Sandbox Code Playgroud) 我正在尝试将 React 测试库引入 Create React App 项目,但遇到了一个奇怪的问题。对于我的一项测试,我需要使用 jest-dom,但我似乎无法成功导入它。
我已经完成yarn add了,想不出我错过了哪一步。
expect.extend失败,因为它toHaveStyle是未定义的。
这是我的测试文件,减少到最低限度:
import React from 'react';
import {render, screen} from '@testing-library/react';
import {toHaveStyle} from '@testing-library/jest-dom';
import '@testing-library/jest-dom/extend-expect';
//expect.extend({toHaveStyle});
it('is confusing me', () => {
// (Using `toBe(42) as an ersatz `console.log`)
expect([Object.keys(require('@testing-library/jest-dom')), Object.keys(require('@testing-library/react')), toHaveClass]).toBe(42);
});
Run Code Online (Sandbox Code Playgroud)
输出是:
Expected: 42
Received: [[], ["render", "cleanup", "fireEvent", ...], undefined]
Run Code Online (Sandbox Code Playgroud)
而且,这是yarn.lock的相关部分:
"@testing-library/jest-dom@^5.7.0":
version "5.7.0"
resolved "https://registry.yarnpkg.com/@testing-library/jest-dom/-/jest-dom-5.7.0.tgz#b2e2acb4c088a293d52ba2cd1674b526282a2f87"
integrity sha512-ZV0OtBXmTDEDxrIbqJXiOcXCZ6aIMpmDlmfHj0hGNsSuQ/nX0qPAs9HWmCzXvPfTrhufTiH2nJLvDJu/LgHzwQ==
dependencies:
"@babel/runtime" "^7.9.2"
"@types/testing-library__jest-dom" "^5.0.2"
chalk "^3.0.0"
css "^2.2.4"
css.escape "^1.5.1"
jest-diff …Run Code Online (Sandbox Code Playgroud) 我正在针对以下组件运行测试:
const App: React.FC<RouteComponentProps> = ({ history, location, match }) => { ... }
Run Code Online (Sandbox Code Playgroud)
所有的测试都通过了,但是我收到了这个警告:
const { getByText, debug } = render(<MemoryRouter><Route><App/></Route></MemoryRouter>);
Type '{}' is missing the following properties from type 'RouteComponentProps<{}, StaticContext, {}>': history, location, match(2739)
Run Code Online (Sandbox Code Playgroud)
我的印象是<MemoryRouter>&<Route>会提供<App/>缺少的属性......
这是我获取 useAutocomplete 钩子用法的代码。我想测试 onChange 的代码覆盖率。有没有办法通过使用反应测试库来做到这一点。
const {
getRootProps,
getInputProps,
getListboxProps,
getOptionProps,
groupedOptions,
getClearProps
} = useAutocomplete({
id: 'use-autocomplete-demo',
options: routeInformation ? routeInformation : [],
getOptionLabel: (option) => option.routeName,
clearOnEscape: true,
disableClearable: false,
onChange: (event: React.ChangeEvent<{}>, value: any) => {
if (setPreviousRoute && setSelectedRoute) {
setPreviousRoute({...selectedRoute} as RouteInformation);
if ( value ) {
setSelectedRoute({...value} as RouteInformation);
} else {
setSelectedRoute(undefined);
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
我的渲染元素看起来像这样,当我从 react-testing-library 进行测试时,groupedOptions 没有任何数据。
<div>
<div {...getRootProps()} >
<InputBase
data-testid="SearchInput"
{...getInputProps()}
placeholder="Search Route Name"
classes={{
root: classes.inputRoot, …Run Code Online (Sandbox Code Playgroud) react-testing-library 背后的理念对我来说很有意义,但我正在努力将它应用于 css 属性。
例如,假设我有一个简单的切换组件,单击时显示不同的背景颜色:
import React, { useState } from "react";
import "./Toggle.css";
const Toggle = () => {
const [ selected, setSelected ] = useState(false);
return (
<div className={selected ? "on" : "off"} onClick={() => setSelected(!selected)}>
{selected ? "On" : "Off"}
</div>
);
}
export default Toggle;
Run Code Online (Sandbox Code Playgroud)
.on {
background-color: green;
}
.off {
background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
我应该如何测试这个组件?我编写了以下测试,它适用于内联组件样式,但在使用 css 类时失败,如上所示。
import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import Toggle from "./Toggle";
const backgroundColor …Run Code Online (Sandbox Code Playgroud) 目前我正在编写一个测试来测试里面的内容(HTML 内容),但似乎我无法使用 React 测试库正确测试。它可以找到它的 id 值,但是如何获取该元素中的 HTML 内容。
import React from 'react';
export const TopBar = () => {
return (
<div className="dashboard-title-component">
<div>
<div data-testid="title-content">Dashboard Menu</div>
</div>
</div>
)
}
import React from "react";
import { render } from "@testing-library/react";
import { TopBar } from "./TopBar";
import { Provider } from "react-redux";
import { store } from "../../Store";
import { screen } from "@testing-library/dom";
import "@testing-library/jest-dom/extend-expect";
test("It should check if content matches", () => {
render(
<Provider store={store}>
<TopBar/> …Run Code Online (Sandbox Code Playgroud)简而言之,如果我通过它的标签抓取屏幕的一部分:
const foo = screen.getByLabelText('Some Label');
Run Code Online (Sandbox Code Playgroud)
我可以看到我感兴趣的元素存在于输出中:
debug(foo);
...
<div
class=" css-15zcpdi-NoOptionsMessage"
>
Something went wrong
</div>
Run Code Online (Sandbox Code Playgroud)
但是,如果我在屏幕中搜索“出现问题”:
screen.getByText('Something went wrong');
Run Code Online (Sandbox Code Playgroud)
RTL声称它找不到它:
TestingLibraryElementError: Unable to find an element with the text: Something went wrong. ...
Run Code Online (Sandbox Code Playgroud)
我一定在这里做错了什么..什么?
我正在使用https://github.com/testing-library/react-hooks-testing-library来测试我的组件,但不确定如何检查我的组件在此测试中的状态更改后是否已重新渲染
const { container, getAllByText, getAllByRole, queryByLabelText, getByText, getByLabelText } = renderNavBar(
initialState,
dispatchMock,
);
// get all divs
let divs = getAllByRole('div');
.
.
.
const { result, waitForNextUpdate } = renderHook(() => useReducer(Reducer, initialState));
const [ , dispatch ] = result.current;
act(() => {
dispatch({ type: 'SET_ACTIVE_LINK', payload: 'about' });
fireEvent.click(getByText('home'));
});
// get all divs after the state change,
divs = getAllByRole('div'); // <---- this still has the NavBar component with the old state
Run Code Online (Sandbox Code Playgroud)
状态在 …
javascript testing unit-testing reactjs react-testing-library
在我的渲染方法中,我有
<span onClick={handleDelete} className="delete-action">
<FontAwesomeIcon icon="trash-alt" />
</span>
Run Code Online (Sandbox Code Playgroud)
使用 react-testing-library 如何访问上述 span 元素。这是我到目前为止尝试过的
getByText(<FontAwesomeIcon icon="trash-alt" />)
Run Code Online (Sandbox Code Playgroud)
但错误说 matcher.test 不是一个函数。我应该如何处理这个。
reactjs ×10
unit-testing ×3
javascript ×2
css ×1
html ×1
jest-dom ×1
jestjs ×1
material-ui ×1
react-router ×1
testing ×1
typescript ×1