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?
3 Answers
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
Comments
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
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.
1 Comment
Community
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.