はじめに
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って書いてるのに、そこは対応できないんかい...って思いましたが
なるほど。