1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JS】NodeListに対してmap()やfilter()を使う

Posted at

はじめに

Jest勉強中にdocument.querySelectorAll()で取得したNodeListに対して、map()をしようとした際に、少しフリーズしたので備忘です。

問題

tr要素のtextContentを確認するため、mapを使いたいなと思ったのですが、NodeListはforEach()のみなので、そのままではmap()は使えません。

  it("テーブルレコード数チェック", async () => {
    render(
      <ChakraProvider value={defaultSystem}>
        <StudyRecord />
      </ChakraProvider>
    );
    const tableElem = await screen.findByRole("table");

    // ↓↓↓ NodeListOf<Element>型←forEachのみ
    const trElems = tableElem.querySelectorAll("tbody tr");
    expect(trElems.length).toBe(1);
  });

解決方法

スプレット構文を使えばOKです。

  it("テーブルレコード数チェック", async () => {
    render(
      <ChakraProvider value={defaultSystem}>
        <StudyRecord />
      </ChakraProvider>
    );
    const tableElem = await screen.findByRole("table");

    // ↓↓↓ NodeListOf<Element>型←forEachのみ
    const trElems = tableElem.querySelectorAll("tbody tr");

+   const trTexts = [...trElems].map((x) => x.textContent);
    expect(trElems.length).toBe(1);
  });

おわりに

基本をしっかり大事にしていきます。

JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてください!
▼▼▼
https://projisou.jp

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?