如何解决测试组件:如何使用 getByTestId 访问标签的属性
我在 react(我的第一个)中做一个组件测试,我想验证一个数字,当我传递给它值时,它返回 undefined 并且我删除该值以查看它返回的内容,这很好,找到元素
import React,{ useState } from 'react';
import { render,cleanup,screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Numberupdown } from '../../components/number-
updown/Numberupdown';
import '@testing-library/jest-dom/extend-expect'
const updownNumber = () => {
const [quantity,setQuantity] = useState<number>(1);
const packageType = 'Box'
return (
<Numberupdown
value={quantity}
valuetoShow={
packageType === 'Box' || 'pack' || 'piece' || 'bag' || 'sBox'
? quantity : quantity * 12
}
min={1}
max={5000}
step={1}
onChange={value => setQuantity(value)}
/>
);
};
describe('Plus or minus in the product modal',() => {
afterEach(cleanup);
beforeEach(() => render(<updownNumber />));
it('Validate is if exists',() => {
expect(screen.getByTestId('product-minus')).toBeInTheDocument();
expect(screen.getByTestId('product-input')).toBeInTheDocument();
expect(screen.getByTestId('product-plus')).toBeInTheDocument();
});
it('Validate function onclick',() => {
const minusButton = screen.getByTestId('product-minus');
const plusButton = screen.getByTestId('product-plus');
const input = screen.getByTestId('product-input');
userEvent.click(plusButton);
userEvent.click(plusButton);
expect(getByRole('textBox',{ name: /email/i })).toHaveValue('test@email.com);
expect((input as HTMLInputElement).value).toBe(3);
userEvent.click(minusButton);
expect((input as HTMLInputElement)).toBe(2);
});
});
Expected: 3
Received: <ion-input class="value-cell" data-testid="product-input" type="number"
value="3" />
expect((input as HTMLInputElement).value).toBe(3);
Expected: 3
Received: undefined
解决方法
您已经使用了@testing-library,所以我建议更进一步,添加 https://www.npmjs.com/package/@testing-library/jest-dom 作为 devDependency。如果使用基于 Create React App 的应用程序,您可以向您的 setupTests.js
文件添加类似的导入,例如
import '@testing-library/jest-dom/extend-expect';
然后您可以编写测试以使用以下内容检查字段的值:
expect(getByRole('textbox',{ name: /email/i })).toHaveValue('test@email.com);
使用 jest-dom
可以让您编写读起来更好的测试,但这只是我的看法。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。