1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Unable to find an element with the text: 45. 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.

Last updated at Posted at 2025-04-26

はじめに

JestでDOMを取得する際に遭遇したエラーを共有します。

問題

以下のコードでタイトルのエラーが出ます。

const newTimes = screen.getAllByText(newTodoTime);

これは newTodoTime=45 つまり "45" というテキストが複数のDOMノードに分割されている可能性があるからです。
例えば、

<span><strong>4</strong>5</span>  // DOM的には 2つのノードに分割されている

これに対して getAllByText("45") は失敗します。

解決方法

関数によるテキストマッチャーを使用します。

screen.getAllByText((content, element) =>
  element.textContent === "45"
);

または includes を使う場合

screen.getAllByText((content, element) =>
  element.textContent?.includes("45")
);

おわりに

Allって書いてるのに、そこは対応できないんかい...って思いましたが
なるほど。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?