admin管理员组文章数量:1389779
Having the following unit test:
const MY_URL = 'example'
it('should render MyComponent with url', () => {
const { getByTestId } = render(<MyComponent />);
const myLink = getByTestId(TestIds.LINK);
expect(loggingLink).toContain(MY_URL);
});
The test fails with the following message:
Expected value: "example"
Received object: <div class="m-3" data-testid="test-link"><a href="example">my-link</a></div>
So it seems that toContain
doesn't check what is inside of that object. Is there a method to check that the URL is inside the object?
Having the following unit test:
const MY_URL = 'example.'
it('should render MyComponent with url', () => {
const { getByTestId } = render(<MyComponent />);
const myLink = getByTestId(TestIds.LINK);
expect(loggingLink).toContain(MY_URL);
});
The test fails with the following message:
Expected value: "example."
Received object: <div class="m-3" data-testid="test-link"><a href="example.">my-link</a></div>
So it seems that toContain
doesn't check what is inside of that object. Is there a method to check that the URL is inside the object?
2 Answers
Reset to default 5You can get the anchor element with ByRole
query. Just search it with link
and then check the attribute href
:
// I used screen in this case, but you can get getByRole from render.
const anchorElement = screen.getByRole('link');
expect(anchorElement).toBeInTheDocument();
expect(anchorElement).toHaveAttribute('href', 'example.');
Anchor elements have link
role only when href attribute is present, otherwise no corresponding role. You can check more about it here.
There's a couple of things. First, toContain
is for testing if an element exists in an array. https://jestjs.io/docs/expect#tocontainitem
Second, the point of RTL is not to test properties and such, but to test what users see on the screen. So I guess the "RTL way" of doing this would be to click the link and see what's displayed. Which admittedly is not always helpful in every situation!
If you are absolutely sure this url needs a test around it, then you do have an escape hatch via the underlying jest jsdom selectors. You can query an element using a bog standard querySelector
and then test the href
property directly.
In fact you don't even need querySelector. The getBy
methods all return a jsdom object which you can then test with getAttribute('href')
本文标签: javascriptCheck if object contains a link in React Testing LibraryStack Overflow
版权声明:本文标题:javascript - Check if object contains a link in React Testing Library - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744693443a2620135.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论