【问题标题】:How do you test for the non-existence of anchor element using jest and react-testing-library?您如何使用 jest 和 react-testing-library 测试锚元素的不存在?
【发布时间】:2021-06-18 14:41:12
【问题描述】:

我的 react 组件根据规则呈现链接。

当 h4 元素中有链接时,标记会被渲染。

<h4><a href="">foo</a></h4>
<p>blah blah <a href="">bar</a> blah blah</p>

这是我编写测试以验证链接是否存在的方式。

  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)
  })

如何测试锚元素未呈现/在 h4 中不存在?

<h4>foo</h4>
<p>blah blah <a href="">bar</a> blah blah</p>

【问题讨论】:

    标签: javascript reactjs jestjs react-testing-library


    【解决方案1】:

    我会在锚标记中添加data-testid 属性并使用queryBy* 查询并断言值为null

    Queries

    来自What queries should I use?

    测试 ID

    getByTestId: 用户看不到(或听到)这些,所以这只是 推荐用于无法按角色或文本进行匹配的情况或它 没有意义(例如,文本是动态的)

    在您的情况下,锚标记是动态的。

    给定&lt;h4&gt;&lt;a data-testid="test" href=""&gt;foo&lt;/a&gt;&lt;/h4&gt;&lt;h4&gt;foo&lt;/h4&gt;

    测试用例:

    const { queryByTestId } = render(<Component {...props} />);
    
    expect(queryByTestId('test')).toBe(null);
    

    更新

    还有Manual Queries 使用containerquerySelector DOM API。它可能看起来像这样。*

    给定&lt;h4&gt;&lt;a href=""&gt;foo&lt;/a&gt;&lt;/h4&gt;&lt;h4&gt;foo&lt;/h4&gt;

    测试用例:

    const { container } = render(<Component {...props} />);
    
    expect(container.querySelector('h4 > a')).toBe(null);
    

    * 我从未进行过这样的测试,但根据文档,这应该非常接近您可能正在寻找的内容。

    【讨论】:

    • 还有其他选择吗?我不想仅仅为了测试目的而添加额外的属性。
    • @calebo 我相信是的。您可以在 container 渲染选项上使用常规 DOM querySelector。我添加了一个我认为对你有用的例子。
    • 谢谢德鲁。第二个 querySelector 选项有效。
    猜你喜欢
    • 2019-03-17
    • 2021-02-11
    • 2020-03-22
    • 2021-02-28
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 2020-05-14
    相关资源
    最近更新 更多