检查对象是否包含 React 测试库中的链接

Leo*_*ssi 3 javascript unit-testing reactjs jestjs 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);
  });
Run Code Online (Sandbox Code Playgroud)

测试失败并显示以下消息:

 Expected value:  "example.com"
 Received object: <div class="m-3" data-testid="test-link"><a href="example.com">my-link</a></div>
Run Code Online (Sandbox Code Playgroud)

所以看起来并toContain没有检查该对象内部的内容。有没有一种方法可以检查 URL 是否在对象内部?

Lui*_*nto 5

您可以通过查询获取锚元素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');
Run Code Online (Sandbox Code Playgroud)

锚元素link只有当href属性存在时才具有作用,否则没有相应的作用。您可以在此处查看更多相关信息。