Luke Steinbicker
Luke Steinbicker

Reputation: 41

How to run a Playwright test without using the command line

I want to run a playwright test without typing npx playwright test in the command line. My hope is that I can call a playwright file from another file and have it start running without accessing the command line. Is there any way to add a playwright test to another file so that I can run it multiple times or loop the test without typing in the terminal?

Upvotes: 0

Views: 3930

Answers (3)

isak
isak

Reputation: 106

It sound like you would like to use playwright as a library instead of a test runner. Here is an example of a function that opens a website and takes a screenshot (using Playwright as a library):

const { webkit } = require('playwright');
    
const performScreenshot = async () => {
  const browser = await webkit.launch();
  const page = await browser.newPage();
  await page.goto('https://stackoverflow.com/');
  await page.screenshot({ path: `example.png` });
  await browser.close();
};

Reference: https://playwright.dev/docs/library

Upvotes: 2

Berkay Kirmizioglu
Berkay Kirmizioglu

Reputation: 1185

First file

// myTest.spec.js
const { test, expect } = require('@playwright/test');

test('sample test', async ({ page }) => {
  await page.goto('https://stackoverflow.com');
  const title = await page.title();
  expect(title).toBe('Stackoverflow');
});

Second file

// runTests.js
const { runTests } = require('@playwright/test/lib/cli/cli');

async function runMyTest() {
  await runTests({
    files: ['./myTest.spec.js'], // Array of test files to run
    report: false,
    headed: true,
  });
}


// Run the test multiple times
(async () => {
  for (let i = 0; i < 5; i++) {
    console.log(`Running test iteration ${i + 1}`);
    await runMyTest();
  }
  console.log('All test iterations completed');
})();

Then you can try to run your test multiple times or loop the test without typing in the terminal

node runTests.js

Upvotes: 1

Dinesh Kumar Giri
Dinesh Kumar Giri

Reputation: 1

Playwright tests can be run without using the CLI command. Playwright is a Node.js library, so you can write your test scripts in a Node.js file and then run the file using Node.js.

Upvotes: -1

Related Questions