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

Playwrightのプロジェクト設定で実現するテストの前処理と後処理について

Last updated at Posted at 2024-12-21

テストの前処理と後処理について

playwright.config.tsのprojectを活用することによって、前処理→テスト→後処理という一連の処理を定義することができます。その一例が以下です。

  projects: [
  
    // ユーザー認証を行い、ユーザー情報を保存する
    { name: 'setup', testMatch: 'auth.setup.ts' },
    
    // 新規記事を作成する
    {
      name: 'articleSetup',
      testMatch: 'newArticle.setup.ts',
      // setupを実行してからarticleSetupを実行
      dependencies: ['setup'],
    },
    
    // 記事のいいねボタンが機能することを確認するテスト
    {
      name: 'likeCounter',
      testMatch: 'likesCounter.spec.ts',
      // storageStateを読み込み、保存しておいたユーザー情報を使用する
      use: { ...devices['Desktop Chrome'], storageState: '.auth/user.json' },
      // articleSetupを実行してからlikeCounterを実行
      dependencies: ['articleSetup'],
      // テストが終了したらarticleCleanUpを実行
      teardown: 'articleCleanUp',
    },
    
    // 記事の削除を行う
    {
      name: 'articleCleanUp',
      testMatch: 'articleCleanUp.setup.ts',
    },
  ],

この一連の処理の中心はlikeCounter です。

これの前処理として setup と articleSetup が、

しして後処理として articleCleanUp が存在しています。

これらは、dependencies と teardown によって順序が制御されています。

dependencies として指定したものが必ず事前に実行されるようになっており、

teardown として指定したものが必ずその後に実行されるようになっています。

グローバルな前処理と後処理の定義について

特定のテストやプロジェクトではない、グローバルなテストの前処理と後処理についてはplaywright.config.ts にて以下のように定義します。

export default defineConfig({
  testDir: './tests',
  /* Run tests in files in parallel */
  fullyParallel: true,
  /* Fail the build on CI if you accidentally left test.only in the source code. */
  forbidOnly: !!process.env.CI,
  /* Retry on CI only */
  retries: process.env.CI ? 2 : 0,
  /* Opt out of parallel tests on CI. */
  workers: process.env.CI ? 1 : undefined,
  /* Reporter to use. See https://playwright.dev/docs/test-reporters */
  reporter: 'html',
  /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
  use: {
    /* Base URL to use in actions like `await page.goto('/')`. */
    // baseURL: 'http://127.0.0.1:3000',

    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
    trace: 'on-first-retry',
    extraHTTPHeaders: {
      Authorization: `Token ${process.env.ACCESS_TOKEN}`,
    },
  },
  // ここに記述
  globalSetup: './global-setup.ts',
  globalTeardown: './global-teardown.ts',
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?