DEV Community

kaede
kaede

Posted on • Updated on

React testing-library で getByText, expect, debug, を使ってみる

参考

https://qiita.com/ossan-engineer/items/4757d7457fafd44d2d2f#react-testing-library-%E3%82%B3%E3%83%B3%E3%83%9D%E3%83%BC%E3%83%8D%E3%83%B3%E3%83%88%E3%81%AE%E3%83%AC%E3%83%B3%E3%83%80%E3%83%AA%E3%83%B3%E3%82%B0

ossan-engineer さんの記事

プロジェクト作成

npx create-react-app ts-jest --template typescript
Enter fullscreen mode Exit fullscreen mode

これで作成できる

===

App.tsx に文字列を書く

function App() {
  return (
    <div>App Text</div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

シンプルに App Text を入れる

===

App Text が入ってるエレメントが Document にあるかテストする

src/App.test.tsx を

import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import App from './App';

describe('App', () => {
  test('renders App Text', () => {
    render(<App />);
    const appTextElement = screen.getByText('App Text');
    expect(appTextElement).toBeInTheDocument();
  });
})
Enter fullscreen mode Exit fullscreen mode

describe を使ってブロックを作る
test のストーリーを書いて App コンポーネントを表示
App Text のテキストからエレメントを取得して変数に入れる
それがドキュメントにあるか期待する。

===

npm test で動かす

npm test

 PASS  src/App.test.tsx
  App
    ✓ renders App Text (25 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.566 s, estimated 1 s
Ran all test suites related to changed files.
Enter fullscreen mode Exit fullscreen mode

これでテストが通った。

===

中身を変えて通らないテストを打つ

const appTextElement = screen.getByText('App NoText');
Enter fullscreen mode Exit fullscreen mode

これで打ってみる

    Ignored nodes: comments, <script />, <style />
    <body>
      <div>
        <div>
          App Text
        </div>
      </div>
    </body>

       6 |   test('renders App Text', () => {
       7 |     render(<App />);
    >  8 |     const appTextElement = screen.getByText('App NoText');
         |                                   ^
       9 |     expect(appTextElement).toBeInTheDocument();
      10 |   });
      11 | })
Enter fullscreen mode Exit fullscreen mode

しっかりエラーが出てくれる。

===

debug を使ってみる

  console.log
    <body>
      <div>
        <div>
          App Text
        </div>
      </div>
    </body>

    /Users/sato-ryo1/ts-jest/src/App.test.tsx:10:12
       8 |     const appTextElement = screen.getByText('App Text');
       9 |
    > 10 |     screen.debug()
         |            ^

      at logDOM (node_modules/@testing-library/dom/dist/pretty-dom.js:89:13)
Enter fullscreen mode Exit fullscreen mode

エラーではない形で DOM を出してくれる。

===

次は他の取得方法でエレメントを取得してみる

===

Top comments (0)