我正在尝试测试一个具有 anendAdornment IconButton和另一个带有 a 的组件TreeView,但是 theIconButton和ExpandIcon/CollapseIcon都没有很好的选项来调度测试事件。
这是TextField我正在使用的组件:
<TextField
fullWidth
label="Label"
onChange={handleChange}
type="text"
InputProps={{
endAdornment: (
<InputAdornment >
<IconButton onClick={openAssetHierarchy}>
<Folder />
</IconButton>
</InputAdornment>
),
}}
/>
Run Code Online (Sandbox Code Playgroud)
这是TreeView组件:
<TreeView
defaultCollapseIcon={<ArrowDropDown />}
defaultExpandIcon={<ArrowRight />}
defaultEndIcon={<div style={{ width: 24 }} />}
onNodeToggle={handleToggle}
onNodeSelect={handleSelect}
>
[...]
</TreeView>
Run Code Online (Sandbox Code Playgroud)
用于TreeView使用 Test Playground 获取图标时

没有很好的查询来获取测试图标。我怎样才能获得这些选项?
假设我有一个简单的基于图像的组件:
\n// ./Figure.js\n\nconst Figure = ({src}) => (\n <img\n src={src}\n width="100%"\n />\n);\nRun Code Online (Sandbox Code Playgroud)\n我想测试它的宽度是100%。
我的测试:
\n// ./Figure.test.js\n\nimport Figure from './Figure'\nimport { render, screen } from '@testing-library/react'\n\ndescribe('Figure', () => {\n const setup = () => {\n return render(\n <Figure\n src="https://src.com"\n />\n )\n }\n\n it('has the right width', () => {\n setup()\n\n const image = screen.getByAltText('alt')\n\n expect(image.src).toBe('https://src.com/')\n expect(image.width).toBe("100%")\n })\n})\nRun Code Online (Sandbox Code Playgroud)\n但是,这给了我一个错误:
\n \xe2\x97\x8f Figure \xe2\x80\xba renders\n\n expect(received).toBe(expected) // Object.is equality\n\n Expected: "100%"\n Received: 0\nRun Code Online (Sandbox Code Playgroud)\n问题:如何在不使用快照的情况下使用 React …
我正在使用testing-library/react进行路由单元测试,下面是我的代码,我的测试用例通过了,但我收到控制台错误
React 无法识别warnKeyDOM 元素上的 prop。
任何想法 ?下面是我的代码和错误截图
import {render, screen} from '@testing-library/react'
import {createMemoryHistory} from 'history'
import React from 'react'
import {Router} from 'react-router-dom'
import '@testing-library/jest-dom/extend-expect'
import AdminPanel from './AdminPanel'
test('full app rendering/navigating',async () => {
const history = createMemoryHistory()
render(
<Router history={history}>
<AdminPanel />
</Router>,
)
let title = await screen.findByText(/Admin Portal/i)
expect(title).toBeInTheDocument()
})
Run Code Online (Sandbox Code Playgroud)
我正在尝试测试一个函数被调用
import React from 'react';
import { render, cleanup, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import MyForm from './MyForm';
afterEach(cleanup);
const testFunction = jest.fn();
test('my form', () => {
const { getByTestId } = render(<MyForm />);
const myButton = getByTestId('submit-button');
expect(myButton.tagName).toBe('BUTTON');
fireEvent.click(myButton)
expect(testFunction).toHaveBeenCalledTimes(1)
});
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是它似乎没有绑定到模拟函数,但它确实调用了组件中的函数。
import React from 'react';
export default function myForm() {
function testFunction() {
console.log('hello from inside');
}
return (
<div>
<form onSubmit={testFunction}>
<input type="text" />
<button type="submit" data-testid="submit-button">submit</button>
</form>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
如何获取被调用的模拟函数而不是“真实”函数。
expect(jest.fn()).toHaveBeenCalledTimes(1)
Expected mock …Run Code Online (Sandbox Code Playgroud) 我用testing-library
如果您有语法解决方案,我无法定位该元素,我正在尝试检索标签并比较xlinkHref. 我可以获得整个组件,但没有类名或 ID,这让我很困扰 // Type.test.jsx
import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import Type from '../index';
describe('Type', () => {
it('Watch Type', () => {
const {container} = render(<Type type="Watch Type" />);
expect(container.firstElementChild.getAttribute('xlinkHref')).toHaveAttribute('xlinkHref', 'https://www.test.com/')
});
});
Run Code Online (Sandbox Code Playgroud)
// 类型.jsx
import React from 'react';
const Type = (props) => {
const type = props.type;
if (type === 'Watch Type') {
return (
<span className="platform-icon">
<svg>
<use xlinkHref="https://www.test.com/" />
</svg>
</span>
)
} …Run Code Online (Sandbox Code Playgroud) HTML打开弹出窗口后,我有一个组件按照以下代码渲染弹出窗口。我想使用测试库编写测试来验证单击弹出项目后aria-expanded的值。false有没有更好的方法让我验证 aria-expanded?
// component
<body>
<div>
<div >
<button aria-expanded="true" class="btn">
Flyout button
</button>
<div class="flyoutContainer>
<ul class="flyoutItem" role="listbox" >
<li aria-selected="false" class="item" role="option" >
<div class="option" >
<span >Data is here</span>
</div>
</li>
</ul>
</div>
</div>
</div>
</body>
// test
render(<flyout />);
const item = screen.getByText(/Data is here/, {selector: 'span'});
fireEvent.click(item);
const flyoutButton = screen.getByRole('button', {name: 'Flyout button'});
expect(flyoutButton).toHaveClass('aria-expanded').;
expect(flyoutButton).toHaveAttribute('aria-expanded', 'false')
Run Code Online (Sandbox Code Playgroud) todoElement 应该包含一个 Strike 元素,但我的测试表明不然。我在我的 Todo 函数中声明,如果文本完成,那么它应该呈现一个包含 h1 元素的 Strike 元素。为什么我的测试无法识别罢工元素?
// Todo.js
import React from 'react'
function Todo({ todo }) {
const { id, title, completed } = todo
const h1 = <h1>{title}</h1>
const text = completed ? <strike>{h1}</strike> : h1
return <div data-testid={`todo-${id}`}>{text}</div>
}
export default Todo
Run Code Online (Sandbox Code Playgroud)
// App.js
import Todo from './components/Todo'
function App() {
const todos = [
{ id: 1, title: 'wash dishes', completed: false },
{ id: 2, title: 'make dinner', completed: true },
] …Run Code Online (Sandbox Code Playgroud) 我有以下代码:
<div className="button">
<a href={SOME_URL}>
...
...
</a>
</div>
Run Code Online (Sandbox Code Playgroud)
在我的测试中,如果我尝试这样做:
const link = screen.getByRole('link');
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
TestingLibraryElementError: Unable to find an accessible element with the role "link"
Run Code Online (Sandbox Code Playgroud)
运行screen.debug(),我得到以下信息:
<div
class="button"
>
<a>
Run Code Online (Sandbox Code Playgroud)
那怎么找不到呢?
我无法获得 Jest 与 Webpack 5 和 TypeScript 一起使用的类型,我已经尝试了针对同一问题的其他解决方案。在我下面的示例测试中,问题仅在于“screen”和“toBeInTheDocument”。我倾向于认为这是 ESLint 配置问题。
我无法运行测试,它们失败了Property 'toBeInTheDocument' does not exist on type 'JestMatchers<HTMLElement>'.。我正在使用纱线 3.1.0。我已经尝试过这个答案和许多其他答案,包括通过导入类型tsconfig.json。我究竟做错了什么?
测试示例 ( src/components/Example/spec/test.spec.tsx):
import * as React from 'react';
import { render, screen } from '@testing-library/react';
import { Example } from './Example';
import "@testing-library/jest-dom/extend-expect";
import "@testing-library/jest-dom";
test("Renders correctly", () => {
render(<Example />);
const example = screen.getByAltText("Example");
expect(example).toBeInTheDocument();
});
Run Code Online (Sandbox Code Playgroud)
笑话.config.js:
module.exports = {
// An array of directory names to be searched recursively up …Run Code Online (Sandbox Code Playgroud) 我的组件:
import React from 'react'
const TestAsync = () => {
const [counter, setCounter] = React.useState(0)
const delayCount = () => (
setTimeout(() => {
setCounter(counter + 1)
}, 500)
)
return (
<>
<h1 data-testid="counter">{ counter }</h1>
<button data-testid="button-up" onClick={delayCount}> Up</button>
<button data-testid="button-down" onClick={() => setCounter(counter - 1)}>Down</button>
</>
)
}
export default TestAsync
Run Code Online (Sandbox Code Playgroud)
我的测试文件:
describe("Test async", () => {
it("increments counter after 0.5s", async () => {
const { getByTestId, getByText } = render(<TestAsync />);
fireEvent.click(getByTestId("button-up"));
const counter …Run Code Online (Sandbox Code Playgroud) reactjs ×9
jestjs ×3
javascript ×2
typescript ×2
unit-testing ×2
eslint ×1
function ×1
image ×1
material-ui ×1
mocking ×1
react-hooks ×1
testing ×1
webpack ×1