开玩笑,React 测试一个不存在的组件

Jest, React testing a component not exist

我有这个测试:

const rendered = render(
  <TransactionReason
    reason={{ code: defaultReason }}
  />
);

expect(rendered.getByTestId('reasonInput')).toBeNull();

我想做的是:有一个具有 testID = 'reasonInput' 的组件,但是当 reason 属性具有我给出的那个值时,不会呈现该组件(代码:默认原因)。但是我得到一个错误,因为 Jest 找不到那个 id,当然,没有呈现。我认为这会产生错误或空值,这就是为什么我尝试使用 toBeNulltoBeFalsy 或类似的东西。

然后我如何测试该组件是否存在?

the reference所述,getByTestIdqueryByTestId的区别在于前者在没有匹配元素时抛出错误:

getBy* queries return the first matching node for a query, and throw an error if no elements match or if more than one match is found (use getAllBy instead).

queryBy* queries return the first matching node for a query, and return null if no elements match. This is useful for asserting an element that is not present. This throws if more than one match is found (use queryAllBy instead).

应该是:

expect(rendered.queryByTestId('reasonInput')).toBeNull();