幸福なプログラマ

プログラマは幸福になれる。

react-testing-frameworkで要素が「存在しないこと」を確認しようとするとエラーになる

要素が存在しないことを確認しようとして次のようなコードを書いた。

it('check non-existence', () => {
    const { getByText } = render(
        <div>existence</div>
    );
    const element = getByText(/non-existence/i);
    expect(element).toBeNull();
});

すると、以下のエラーが発生してテストが失敗してしまいます

TestingLibraryElementError: Unable to find an element with the text: /test1/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

これは getBy〜 メソッドを使用しているのが原因でした、以下のように queryBy〜 に置き換えることでテストをパスできます。

it('check non-existence', () => {
    const { queryByText } = render(
        <div>existence</div>
    );
    const element = queryByText(/non-existence/i);
    expect(element).toBeNull();
});