2

我正在尝试编写一个测试来检查我的应用程序是否正确呈现。在初始页面上,我添加了一个 data-testid 为“start”。所以我的顶级测试检查初始组件是否已被渲染。

import React from "react";
import { render } from "react-testing-library";
import App from "../App";

test("App - Check the choose form is rendered", () => {
  const wrapper = render(<App />);
  const start = wrapper.getByTestId("start");
  // console.log(start)
  // start.debug();
});

如果我console.log(start)可以看到节点的所有属性。但是,如果我尝试debug()然后它错误地说它不是一个函数。

我上面的测试似乎确实有效。如果我将 getByTestId 从更改start为其他任何内容,则它会出错。但是我没有使用该expect功能,所以我违反了最佳实践吗?

4

1 回答 1

4

这个问题有两个部分 -

为什么console.log(start)有效,为什么无效start.debug()

getByTestId返回一个 HTMLElement。使用 时console.log(start),会记录 HTMLElement 详细信息。但是 HTMLElement 没有debug功能。相反,react-testing-library在您用于渲染组件debug时为您提供了一个功能。render因此start.debug(),您应该使用 ,而不是使用wrapper.debug()

因为您没有expect函数,所以编写这样的测试是一个好习惯吗?

我不确定什么可能是一个很好的答案,但我会告诉我使用它的方式。getByTestId使用 data-testid和获取元素有两种变体queryByTestId。不同之处在于,getByTestId如果未找到具有测试 id 的元素,则会引发错误,而queryByTestId在这种情况下返回 null。这意味着它getByTestId本身就是对元素存在的断言。因此,如果您使用getByTestId. queryByTestId如果我要断言元素的存在/不存在,我宁愿使用。下面的例子 -

test("App - Check the "Submit" button is rendered", () => {
 const { queryByTestId } = render(<App />)
 expect(queryByTestId('submit')).toBeTruthy()
});

我会getByTestId在这样的测试中使用我知道元素存在并且我们期望元素的属性(而不是元素的存在/不存在)。下面的例子 -

test("App - Check the "Submit" button is disabled by default", () => {
 const { getByTestId } = render(<App />)
 expect(getByTestId('submit')).toHaveClass('disabled')
});

在上面的测试中,如果getByTestId找不到提交按钮,则失败并抛出错误,并且不执行toHaveClass. 这里我们不需要测试元素的存在/不存在,因为这个测试只关心按钮的“禁用”状态。

于 2019-02-05T20:35:50.770 回答