お知らせ

現在サイトのリニューアル作業中のため、全体的にページの表示が乱れています。
投稿日:
開発::自動化サービス::GitHub::GitHub Actions

pull_requestイベントの公式リファレンスが手薄くイベントの意味を明示してないので動きを実際に確認したものをメモ程度に。基本は意味のままだと思いますが…

opened: PRが開いたとき
reopened: PRが開き直されたとき
synchronize: PRに対してPushが走ったとき

特定ブランチから特定ブランチへのPRを阻止する

  • サンプルで作っただけなので中身は適当
    • pull_requestbranchesを先頭に書かないと、指定ブランチ以外でも走るので注意
name: testing on opend PR to main
on:
  pull_request:
    branches:
      - main
    types:
      - opened
      - reopened
      - synchronize
jobs:
  # 事前ブランチチェック
  before-check:
    runs-on: ubuntu-latest
    steps:
      - name: fail case
        if: startsWith(github.head_ref, 'test/') && github.base_ref == 'main'
        # test/* ブランチから main ブランチ宛である場合
        # exit 1で終了することで Workflow を failure 扱いにする
        # https://docs.github.com/ja/actions/creating-actions/setting-exit-codes-for-actions
        run: exit 1
        # 前の if に入らなければ、そのまま次のジョブにつながる
  after-exec:
    # 指定されたジョブの成功を要求、失敗している場合、このジョブを実行しない
    # 必然的に線形実行になる(並列では走らない)
    needs: [before-check]
    runs-on: ubuntu-latest
    steps:
      - name: TEST!
        run: echo "RUN after-exec"

確認環境

Env Ver
next 11.1.2
typescript 4.3.4

サンプルコード

__mocks__/next/router.ts

export const useRouter = () => {
  return {
    route: '/',
    pathname: '',
    query: '',
    asPath: '',
    push: jest.fn(),
    replace: jest.fn(),
    events: {
      on: jest.fn(),
      off: jest.fn(),
    },
    beforePopState: jest.fn(() => null),
    prefetch: jest.fn(() => null),
  };
};
  • global.navigatorをモックにする方法
    • モックというか書き換えてるだけ
  • jestのモック機能はプロパティのモックが出来ないので、実オブジェクトを強制的に書き換えて実施する

サンプルコード

  • Object.defineProperty() を利用して実装
    • value, プロパティが返す値
    • configurable, 再定義可能かどうか、設定しないと再実行でコケる
  • 実際の使用ではユーティリティ関数を作っておき、 afterAll()navigator.userAgentを初期値に戻すのが望ましい
Object.defineProperty(global.navigator, 'userAgent', {
  value:
      'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36',
  configurable: true,
});
  • 理論上可能そうだったので、ひたすら試行錯誤してたらできたのでメモがてら
  • axiosそのものをモックして、その結果に応じた処理が想定通り走っているかどうかを確認したい
  • create-react-appで作成したTypeScript Reactのプロジェクトにnpm tを掛けてテストすることを想定
  • 但し検証用のプロジェクトは@lycolia/ts-boilerplate-generator-cliで作成

確認環境

Env Ver
react 17.0.1
react-scripts 4.0.2
typescript 4.1.3

確認内容

検証対象

  • ページ読み込み時に一回だけAPIを蹴ってなんかすることを想定
import axios from 'axios';
import { useEffect } from 'react';

export const AsyncHookExample = () => {
  useEffect(() => {
    axios
      .get('https://localhost/')
      .then((res) => console.log(res))
      .catch((err) => console.error(err));
  }, []);

  return <p />;
};

検証方法

  • axiosをモックした上で、モック関数のPromiseの解決を待ち、 PromiseのコールバックをspyOnして検査する内容
  • モック関数のPromiseの解決法を求めるのにハマりましたが、これはfoo.mock.results[0].valueに対してawait expect(foo.mock.results[0].value).resolvesとしてやればいける
  • 細かいことはソースコードのコメント参照
import { render } from '@testing-library/react';
import axios from 'axios';
import { AsyncHookExample } from './AsyncHookExample';

// `axios` をモックにする
jest.mock('axios');
// `axios` のモックを取得
const mockedAxios = axios as jest.Mocked<typeof axios>;
// `console.log()` を `spyOn'
const spiedConsoleLog = jest.spyOn(console, 'log');
// `console.error()` を `spyOn'
const spiedConsoleError = jest.spyOn(console, 'error');

describe('AsyncHookExample', () => {
  it('resolve promise in Hook', async () => {
    // テストに期待する結果
    // `axios` はモックなので値は適当
    const beResult = {
      status: 200,
      data: null,
    };
    // `axios` のモックが `resolve` する値を設定
    mockedAxios.get.mockResolvedValue(beResult);
    // コンポーネントを `render` して `useEffect` を走らせる
    render(<AsyncHookExample />);
    // `axios.get()` が呼ばれたことを確認
    expect(mockedAxios.get).toBeCalled();
    // モックの結果を取得
    const testResult = mockedAxios.get.mock.results[0].value;
    // `reject` された値が期待通りであることを確認
    await expect(testResult).resolves.toEqual(beResult);
    // `useEffect` の中の `Promise` の中にある `console.log()` が呼ばれたことを確認
    expect(spiedConsoleLog).toBeCalled();
  });

  it('reject promise in Hook', async () => {
    // テストに期待する結果
    // `axios` はモックなので値は適当
    const beResult = {
      status: 400,
      data: null,
    };
    // `axios` のモックが `reject` する値を設定
    mockedAxios.get.mockRejectedValue(beResult);
    // コンポーネントを `render` して `useEffect` を走らせる
    render(<AsyncHookExample />);
    // `axios.get()` が呼ばれたことを確認
    expect(mockedAxios.get).toBeCalled();
    // モックの結果を取得
    const testResult = mockedAxios.get.mock.results[0].value;
    // `reject` された値が期待通りであることを確認
    await expect(testResult).rejects.toEqual(beResult);
    // `useEffect` の中の `Promise` の中にある `console.error()` が呼ばれたことを確認
    expect(spiedConsoleError).toBeCalled();
  });
});

あとがき

  • mockResolvedValueのスコープやらモックのPromiseを解決させるマッチャやら調べるのに手間取った
    • あとはそもそもPromiseが解決した結果がどこに入るのかとか、兎に角あれこれ
  • expect(mockedAxios.get).toBeCalled()が通るのはすぐに気づいたので、なら出来るだろうとひたすら調べてた
    • とりあえず言えることはJestの公式ドキュメントが大正義なので、ここを穴が開くまで読めば大抵のことは解決する