Rayrun

What is the difference between setup() and test() blocks in Playwright?

Answer

Understanding setup() and test() in Playwright

In Playwright, setup() and test() are two different blocks that serve unique purposes.

The setup() Block

The setup() block is where you prepare everything needed for your tests. This could include creating browser instances, pages, or any other resources. Here's a simple example:

import { test } from '@playwright/test';

test.describe('setup block', () => {
  test.beforeEach(async ({ browser }) => {
    const context = await browser.newContext();
    const page = await context.newPage();
    await page.goto('https://ray.run/');
  });
});

The test() Block

The test() block is where you write your actual test code. This is where you define your test steps and assertions. Here's an example:

import { test } from '@playwright/test';

test('test block', async ({ page }) => {
  await page.goto('https://ray.run/');
  const title = await page.title();
  test.expect(title).toBe('Ray.run');
});

Global Setup and Teardown

Playwright also provides global setup and teardown options. These are useful for setting up resources once before all tests run (globalSetup), or tearing down resources once after all tests have completed (globalTeardown).

Remember, setup() is for preparing your test environment, while test() is for writing your test code. Understanding this will help you write more efficient and effective tests. For more tips on writing efficient Playwright test scripts, check out this blog post.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.