您如何使用 jest 和 react-testing-library 测试锚元素是否存在?
How do you test for the non-existence of anchor element using jest and react-testing-library?
我的 React 组件根据规则呈现 link。
当 h4 元素中有 link 时,标记将按此呈现。
<h4><a href="">foo</a></h4>
<p>blah blah <a href="">bar</a> blah blah</p>
这是我如何编写测试来验证 link 是否存在。
const props = {
heading: 'foo',
headingLink: '//www.bar.com',
}
test('render the heading text with link', () => {
const { getByText } = render(<Component {...props} />)
getByText(props.heading)
expect(getByText(props.heading).getAttribute('href')).toBe(props.headingLink)
})
我如何测试锚元素是否rendered/doesn不存在于 h4 中?
<h4>foo</h4>
<p>blah blah <a href="">bar</a> blah blah</p>
我会向锚标记添加一个 data-testid
属性并使用 queryBy*
查询并断言值为 null
.
Test IDs
getByTestId
: The user cannot see (or hear) these, so this is only
recommended for cases where you can't match by role or text or it
doesn't make sense (e.g. the text is dynamic).
在您的情况下,锚标记是动态的。
给定 <h4><a data-testid="test" href="">foo</a></h4>
或 <h4>foo</h4>
.
测试用例:
const { queryByTestId } = render(<Component {...props} />);
expect(queryByTestId('test')).toBe(null);
更新
还有Manual Queries使用了container
和querySelector
DOMAPI。它可能看起来像这样。*
给定 <h4><a href="">foo</a></h4>
或 <h4>foo</h4>
.
测试用例:
const { container } = render(<Component {...props} />);
expect(container.querySelector('h4 > a')).toBe(null);
* 我从来没有像这样测试过,但根据文档,这应该非常接近您可能正在寻找的内容。
我的 React 组件根据规则呈现 link。
当 h4 元素中有 link 时,标记将按此呈现。
<h4><a href="">foo</a></h4>
<p>blah blah <a href="">bar</a> blah blah</p>
这是我如何编写测试来验证 link 是否存在。
const props = {
heading: 'foo',
headingLink: '//www.bar.com',
}
test('render the heading text with link', () => {
const { getByText } = render(<Component {...props} />)
getByText(props.heading)
expect(getByText(props.heading).getAttribute('href')).toBe(props.headingLink)
})
我如何测试锚元素是否rendered/doesn不存在于 h4 中?
<h4>foo</h4>
<p>blah blah <a href="">bar</a> blah blah</p>
我会向锚标记添加一个 data-testid
属性并使用 queryBy*
查询并断言值为 null
.
Test IDs
getByTestId
: The user cannot see (or hear) these, so this is only recommended for cases where you can't match by role or text or it doesn't make sense (e.g. the text is dynamic).
在您的情况下,锚标记是动态的。
给定 <h4><a data-testid="test" href="">foo</a></h4>
或 <h4>foo</h4>
.
测试用例:
const { queryByTestId } = render(<Component {...props} />);
expect(queryByTestId('test')).toBe(null);
更新
还有Manual Queries使用了container
和querySelector
DOMAPI。它可能看起来像这样。*
给定 <h4><a href="">foo</a></h4>
或 <h4>foo</h4>
.
测试用例:
const { container } = render(<Component {...props} />);
expect(container.querySelector('h4 > a')).toBe(null);
* 我从来没有像这样测试过,但根据文档,这应该非常接近您可能正在寻找的内容。