[英]Check if object contains a link in React Testing Library
具有以下單元測試:
const MY_URL = 'example.com'
it('should render MyComponent with url', () => {
const { getByTestId } = render(<MyComponent />);
const myLink = getByTestId(TestIds.LINK);
expect(loggingLink).toContain(MY_URL);
});
測試失敗並顯示以下消息:
Expected value: "example.com"
Received object: <div class="m-3" data-testid="test-link"><a href="example.com">my-link</a></div>
所以似乎toContain
沒有檢查該對象內部的內容。 有沒有一種方法可以檢查 URL 是否在對象內部?
您可以使用ByRole
查詢獲取錨元素。 只需使用link
搜索它,然后檢查屬性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.com');
錨元素只有在存在 href 屬性時才具有link
角色,否則沒有相應的角色。 你可以在這里查看更多信息。
有幾件事。 首先, toContain
用於測試元素是否存在於數組中。 https://jestjs.io/docs/expect#tocontainitem
其次,RTL 的重點不是測試屬性等,而是測試用戶在屏幕上看到的內容。 所以我想這樣做的“RTL方式”是單擊鏈接並查看顯示的內容。 誠然,這並不總是在每種情況下都有幫助!
如果您絕對確定此 url 需要圍繞它進行測試,那么您確實有一個通過底層jest jsdom 選擇器的逃生艙口。 您可以使用沼澤標准querySelector
查詢元素,然后直接測試href
屬性。
事實上,您甚至不需要 querySelector。 getBy
方法都返回一個 jsdom 對象,然后您可以使用getAttribute('href')
對其進行測試
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.