Rayrun

How do I execute a Playwright test from a JavaScript file without relying on the command line interface?

Answer

Running a Playwright Test from a JavaScript File

To run a Playwright test from a JavaScript file without using the CLI, you can create a custom script that imports and executes the test. Here's a step-by-step guide:

  1. Install @playwright/test: First, make sure you have the @playwright/test package installed in your project. If not, install it using npm or yarn:

    npm install -D @playwright/test
  2. Create a test file: Create a test file, for example, my-test.spec.ts, and write your test using the test object from @playwright/test:

    import { test } from '@playwright/test';
    
    test('Load ray.run homepage', async ({ page }) => {
      await page.goto('https://ray.run/');
      const title = await page.title();
      expect(title).toBe('Ray.run - Playwright Test Automation');
    });
  3. Create a custom script: Create a new JavaScript file, for example, run-test.js, and import the runTests function from @playwright/test. Then, call this function with the test file path as an argument:

    const { runTests } = require('@playwright/test');
    
    (async () => {
      await runTests(['./my-test.spec.ts']);
    })();
  4. Execute the custom script: Finally, run the custom script using Node.js:

    node run-test.js

This will execute your Playwright test without using the CLI. For more tips on writing efficient Playwright test scripts, check out Tips for Writing Efficient Playwright Test Scripts.

Thank you!
Was this helpful?
Still have questions?

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

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.