LoginSignup
13
14

More than 3 years have passed since last update.

JestでPuppeteerを動かしてCIで実行する

Last updated at Posted at 2019-09-25

概要

  • Reactで作ったアプリのE2EテストをCIで動かしたときのメモ
  • 簡単なサンプルを作成してGitHub Actionsで動かすところまで紹介します

はまったところ

  • ローカルでPuppeteerを実行する際は、アプリを起動しておいて別ターミナルでテストを実行すればよいので問題なかった
  • CIで動かそうとした際に、その場でアプリを起動してそれに対してE2Eテストを実行したかったがどうやればいいか分からなかった

解決策

  • jest-puppeteerを使うとテスト実行前にアプリを起動してくれるように設定できる

コード

  • アプリのセットアップ
npx create-react-app jest-puppeteer-sample
cd jest-puppeteer-sample
yarn add -D jest puppeteer jest-puppeteer
  • テストを作る
/e2e/sample.e2e.js
beforeAll(async () => {
  await page.goto('http://localhost:3000');
});

afterAll(async done => {
  done();
});

it('ページが表示されること', async () => {
  const text = await page.evaluate(
    () => document.querySelector('p').textContent,
  );
  expect(text).toBe('Edit src/App.js and save to reload.v');
});
  • jestの設定ファイルを作る
/e2e/config.json
{
  "preset": "jest-puppeteer",
  "testMatch": ["/**/*.e2e.js"]
}
  • jest-puppeteerの設定ファイルを作る
    • このファイルが今回実現したかった内容の設定!
    • これを書いておくとテスト実行前にアプリを起動してくれる!
jest-puppeteer.config.js
module.exports = {
  server: {
    command: 'BROWSER=none yarn start',
    port: 3000,
  },
};
  • npm scriptsにE2Eテストの実行コマンドを追加する
package.json
  // ...
  "scripts": {
    // ...
    "e2e": "jest -c ./e2e/config.json"
  },
  // ...

ローカルで実行

  • まずはローカルで実行してみる

スクリーンショット 2019-09-26 8.00.50.png

  • 事前にアプリを起動することなく、このコマンドだけで実行できた

GitHub Actionsで実行

  • CIで回してみる
    • 今回はGitHub Actionsを使ってみる
  • 設定ファイルの追加
    • nodeの環境を作ってライブラリをインストールしてテストを実行している
.github/workflows/main.yml
name: Main
on: [push]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v1
      - name: Use Node.js 12
        uses: actions/setup-node@v1
        with:
          node-version: 12
      - name: install
        run: |
          yarn install
      - name: test
        run: |
          yarn e2e
  • GutHubにPushすると実行される

スクリーンショット 2019-09-26 8.16.52.png

  • CIでもJestを使ってPuppeteerを実行することができた!
13
14
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
13
14