LoginSignup
0
0

More than 1 year has passed since last update.

Reactで作ったSPAのユニットテスト

Last updated at Posted at 2022-07-19

モチベーション

  • 単体テストをエクセルで管理したくない
  • バグを修正したときに同じ操作をするのがめんどくさい

環境

  • 言語 TypeScript
    • フレームワーク React
    • UIライブラリ MUI
    • バリデーションライブラリ React Hook Form 

ソースはここ

エラーの発生

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
  • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
  • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
  • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
  • If you need a custom transformation specify a "transform" option in your config.
  • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

 You'll find more details and examples of these config options in the docs:
 https://jestjs.io/docs/configuration
 For information about custom transformations, see:
 https://jestjs.io/docs/code-transformation

上のエラーが発生

対策
https://zenn.dev/yuu383/articles/9c4662ff4a08ea
https://github.com/react-hook-form/resolvers/issues/396
これで動いた

実装

下準備

サンプルなんかを眺めていると

hoge.test.tsx
import { render } from '@testing-library/react';

import App from './App';

describe('TTTTTest', () => {
  test('First Test', () => {
    render(<App />);
  });
});

みたいにレンダリングをしてるけど自分の環境だとうまく動かない。原因を探っていると今回はreact-router-domに原因がありそうだった。聞けばそりゃそうかという感じなのだがtesting-libraryのrenderだとreact-router-domのBrowserRouterがなくなるからみたいだ。なので自分でカスタムレンダーを実装

RenderHelper.tsx
import { render } from "@testing-library/react"
import { BrowserRouter } from "react-router-dom"
import { createTheme, ThemeProvider } from '@mui/material/styles';


export const appRenderer = (component: JSX.Element) => {
    if (typeof (window) === "undefined") {
        throw new Error("This function should be called on browser or jsdom")
    }
    return render(
            <ThemeProvider theme={createTheme({})}>
                    <BrowserRouter>
                        {component}
                    </BrowserRouter>
            </ThemeProvider>
    )
}

hoge.test.tsx
import { appRenderer } from './Helper/RenderHelper';

import App from './App';

describe('TTTTTest', () => {
  test('First Test', () => {
    appRenderer(<App />);
  });
});

例えばreact-cookieのCookiesProviderなんかを使っているときも自分で作ったレンダークラスに書き足していく。

MUI+RHF

基本はMUIのテンプレートを参照
https://mui.com/material-ui/getting-started/templates/sign-in/
各コンポーネントの部分にRHFを当てはめる

SignIn.tsx
・・・
<TextField
    margin="normal"
    required
    fullWidth
    {...register("email")}
    id="email"
    label="Email Address"
    name="email"
    aria-label="email"
    autoComplete="email"
    autoFocus
    error={"email" in errors}
    helperText={errors.email?.message}
/>
<TextField
    margin="normal"
    required
    fullWidth
    {...register("password")}
    label="Password"
    type="password"
    id="password"
    autoComplete="current-password"
    error={"password" in errors}
    helperText={errors.password?.message}
/>
<Button
    className="testButton"
    type="submit"
    fullWidth
    variant="contained"
    sx={{ mt: 3, mb: 2 }}
>
    Sign In
</Button>
・・・

バリデーションはyupで実装。

テスト実装

基本はこれ
https://dev.classmethod.jp/articles/testing-a-little-with-text-field/

ただし、type=passwordにしているTextFieldは単純にgetByLabelTextしても見つからなかった。これは単純にラベルの大文字小文字が合ってなかった説がある。とりあえずOptionsにexact:falseをつければパスワードフォームを見つけてくれた。詳細は下記リンク
https://testing-library.com/docs/queries/about/#precision

API動作テスト

jestのモックを使うとログイン処理部分のようなレスポンが必要な部分を好きな実装に代替できるらしい。これでフロントのテストからバックエンドの部分を分離できる。なぜかまだ動かないので実装出来しだい追記。
[2022/7/24 追記]
以下でAPIのモックが作成できる

test.tsx
global.fetch = jest.fn().mockImplementation(anyMock)

anyMockの部分をたとえば

test.tsx
const anyMock = () =>
    new Promise((resolve) => {
        resolve({ status: 200 })
    })

のようにすれば、ソース内のfetchは全てステータス200を返すAPIとなる。
また今回はログイン処理のようなページ遷移が必要な処理があったが、それについては以下のようになった。

test.tsx
const mockedNavigator = jest.fn();
jest.mock('react-router-dom', () => ({
    ...jest.requireActual('react-router-dom'),
    useNavigate: () => mockedNavigator,
}))

test("ログイン処理", async()=>{
    /** ページを遷移する処理を書く*/
    await waitFor(()=>{
        expect(mockedNavigator).toHaveBeenCalledWith('/top')
    })
})

こちらの記事を参考に実装。
ページ遷移は移動したかどうかを見るのではなく、遷移先のパスを引数にreact-router-domのnavigateが使われたかを見ることによって実装していた

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