gpt4 book ai didi

reactjs - react 测试库 : Match Number of Buttons

转载 作者:行者123 更新时间:2023-12-04 11:48:43 24 4
gpt4 key购买 nike

我使用 create-react-app 创建了一个应用程序。下面是我的计数器组件和测试文件。我正在尝试为组件中的三个静态按钮创建一个测试。第一个测试运行良好,而第二个测试给出了下面提供的错误。
react 成分:

    import React from "react";
import PropTypes from "prop-types";
import classes from "./Counter.module.css";
function Counter(props) {
return (
<div className={classes.Wrapper}>
<div>
<p>
Click Counter - {props.value}
</p>
</div>
<div>
<button onClick={props.counterIncrement} className={classes.custButton} name="first"> Increment </button>
{/* <button onClick={props.counterDecrement} className={classes.custButton}> Decrement </button>
<button onClick={props.resetCounter} className={classes.custButton}> Reset </button> */}
</div>
</div>
);
}
Counter.propTypes = {
value: PropTypes.number,
clickHandler: PropTypes.func,
};
export default Counter;
测试文件:
    import React from 'react'
import {render, fireEvent, screen, cleanup} from '@testing-library/react'

import Counter from "./Counter";


afterEach(cleanup);

describe('Counter', () => {
test('renders counter value 10', () => {
render(<Counter />);
//screen.debug();
expect(screen.getByText(/Click Counter -/)).toBeInTheDocument();
})

})

test('renders three buttons', () => {
render(<Counter />);
const items = screen.findAllByRole('button');
expect(items).toHaveLength(3);
})
错误信息:

FAIL src/components/Counter/Counter.test.js● renders three buttonsexpect(received).toHaveLength(expected)Matcher error: received value must have a length property whose value must be a numberReceived has type: objectReceived has value: {}19 | render();20 | const items = screen.findAllByRole('button');> 21 | expect(items).toHaveLength(3);| ^22 | })at Object..test (src/components/Counter/Counter.test.js:21:19)*

最佳答案

在您提供的示例中,您使用的是 .findAllByRole('button') ,它返回一个 promise ,需要像这样等待:

test('renders three buttons', async () => {
render(<Counter />)
const items = await screen.findAllByRole('button')
expect(items).toHaveLength(3)
})

另一种解决方案是使用 .getAllByRole('button') ,在这种情况下,您可以立即对结果进行断言。

关于reactjs - react 测试库 : Match Number of Buttons,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63427988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com