can we use the toHaveScreenshot() and toMatchSnaphot() out side the test - playwright

Can we use the toHaveScreenshot() and toMatchSnaphot() outside the test without using config file only simple install NPM i playwright in package.json
I have already one snapshot I want to compare snapshot using toHaveScreenshot() method but I am confused we can use outside the test context?
const { chromium } =require( "playwright");
const example = async () => {
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
await page.goto("https://zversal.com/");
await page.toHaveScreenshot("zeversal.png", {
fullPage: false,
maxDiffPixelRatio: 0.24,
});
};
example();
Console reports error:
toHaveScreenshot() must be called during the test

I don't think this is possible. Afaik, toHaveScreenshot() is part of the #playwright/test package.
If I'm looking at the Page API docs there's no toHaveScreenshot() listed. I'd say it's only available in combination with Playwright Test and it's provided expect method.
await expect(page).toHaveScreenshot();

As similarly noted by stefan judis in his answer, toHaveScreenshot is an assertion matchers method provided by expect which comes from the Playwright Test library and is made to be used inside tests.
While that assertion can’t be used, you can still take screenshots using Playwright, and then compare them manually or with another tool.

I don't know if it's possible to use it outside of testing, but you can create a PlaywrightDevPage helper class to encapsulate common operations on the page.
Simple Usage =>
// models/PlaywrightDevPage.js
class PlaywrightDevPage {
/**
* #param {import('playwright').Page} page
*/
constructor(page) {
this.page = page;
this.getStartedLink = page.locator('a', { hasText: 'Get started' });
this.gettingStartedHeader = page.locator('h1', { hasText: 'Installation' });
this.pomLink = page.locator('li', { hasText: 'Playwright Test' }).locator('a', { hasText: 'Page Object Model' });
this.tocList = page.locator('article div.markdown ul > li > a');
}
async getStarted() {
await this.getStartedLink.first().click();
await expect(this.gettingStartedHeader).toBeVisible();
}
async pageObjectModel() {
await this.getStarted();
await this.pomLink.click();
}
}
module.exports = { PlaywrightDevPage };
More Info => PlaywrightDevPage

Related

Playwright save storage state only for certain files

I currently have a test pack that has >50 files. 49 of the files will use the same authentication, so I have set up the below inside my playwright config file:
storageState: 'myauth.json',
This allows me to store the state and use it across all of the tests,
the issue becomes where I don't want to use this state in one of my tests. How would one go about this?
I'm aware I could pass the state into 49 of the files and ignore it for the one, but this seems like the wrong idea.
If you do not want to use any storageState in your 50th test, then you can use test.use({ storageState: undefined }); in that test:
import { test } from '#playwright/test';
import LoginPage from '../../page/LoginPage';
test.use({ storageState: undefined });
test('This test ignores the storageState and performs a fresh login', async ({ page }) => {
loginPage = new LoginPage(page);
await loginPage.login();
});
You can use fixtures and as default value set the one you use 49 times.
In that case when you are need other auth just overwrite it with keyword "use". It is described in playwright doc. https://playwright.dev/docs/test-fixtures
import { TodoPage } from './todo-page'; //In your case auth1 auth2
import { SettingsPage } from './settings-page';
// Declare the types of your fixtures.
type MyFixtures = {
todoPage: TodoPage;
settingsPage: SettingsPage;
};
// Extend base test by providing "todoPage" and "settingsPage".
// This new "test" can be used in multiple test files, and each of them will get the fixtures.
export const test = base.extend<MyFixtures>({
todoPage: async ({ page }, use) => {
// Set up the fixture.
const todoPage = new TodoPage(page);
await todoPage.goto();
await todoPage.addToDo('item1');
await todoPage.addToDo('item2');
// Use the fixture value in the test.
await use(todoPage);
// Clean up the fixture.
await todoPage.removeAll();
},
settingsPage: async ({ page }, use) => {
await use(new SettingsPage(page));
},
});
Default auth use as you you page in your tests.
And when you need to overwrite in your specific file spec.ts file just write:
test.use({ auth: 'reareAuth' });

Playwright : How to run the same test on multiple url in the same browser on different tabs and in parallel

I'm looking to run the same test for serverals url (~20) and I want to be the quickest as possible.
I would like to run my 20 tests in parallel in one browser and in a new tab (page) for each but I can't achieve it.
Here my code that open a new browser for each test :
const urlList: string[] = [
'url1',
'url2',
...
];
test.describe.parallel("Same test for multiple url", async () => {
let context;
test.beforeAll(async ({ browser }) => {
context = await browser.newContext();
});
for (const url of urlList) {
test(`${url}`, async () => {
let page = await context.newPage();
await page.goto(url);
});
}
});
This is expected. https://playwright.dev/docs/test-parallel
Every worker starts it own browser.
If you put console.log("Log Before all"): in "Before All" you will see that it will be printed 20 times, in terminal. Even maybe you will expect to execute it only once.
So you must renounce something. You will have parallel execution or you will have one browser. Think that new browsers will not border you. :-)

aws cdk lambda, appconfig typescript example please?

Can anyone provide or point at an AWS-CDK/typescript example provisioning an AWS AppConfig app/env/config consumed by a lambda please? Could not find anything meaningful online.
A little late to this party, If anyone is coming to this question, looking for a quick answer, here you go:
AppConfig Does Not Have Any Official L2 Constructs
This means that one has to work with L1 constructs currently vended here
This is ripe for someone authoring an L2/L3 construct (I am working on vending this custom construct soon - so keep an eye out on updates here).
This does not mean its hard to use AppConfig in CDK, its just that unlike L2/L3 constructs, we have to dig deeper into setting AppConfig up reading their documentation.
A Very Simple Example (YMMV)
Here is a custom construct I have to setup AppConfig:
import {
CfnApplication,
CfnConfigurationProfile,
CfnDeployment,
CfnDeploymentStrategy,
CfnEnvironment,
CfnHostedConfigurationVersion,
} from "aws-cdk-lib/aws-appconfig";
import { Construct } from "constructs";
// 1. https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appconfig-readme.html - there are no L2 constructs for AppConfig.
// 2. https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-working.html- this the CDK code from this console setup guide.
export class AppConfig extends Construct {
constructor(scope: Construct, id: string) {
super(scope, id);
// create a new app config application.
const testAppConfigApp: CfnApplication = new CfnApplication(
this,
"TestAppConfigApp",
{
name: "TestAppConfigApp",
}
);
// you can customize this as per your needs.
const immediateDeploymentStrategy = new CfnDeploymentStrategy(
this,
"DeployStrategy",
{
name: "ImmediateDeployment",
deploymentDurationInMinutes: 0,
growthFactor: 100,
replicateTo: "NONE",
finalBakeTimeInMinutes: 0,
}
);
// setup an app config env
const appConfigEnv: CfnEnvironment = new CfnEnvironment(
this,
"AppConfigEnv",
{
applicationId: testAppConfigApp.ref,
// can be anything that makes sense for your use case.
name: "Production",
}
);
// setup config profile
const appConfigProfile: CfnConfigurationProfile = new CfnConfigurationProfile(
this,
"ConfigurationProfile",
{
name: "TestAppConfigProfile",
applicationId: testAppConfigApp.ref,
// we want AppConfig to manage the configuration profile, unless we need from SSM or S3.
locationUri: "hosted",
// This can also be "AWS.AppConfig.FeatureFlags"
type: "AWS.Freeform",
}
);
// Update AppConfig
const configVersion: CfnHostedConfigurationVersion = new CfnHostedConfigurationVersion(
this,
"HostedConfigurationVersion",
{
applicationId: testAppConfigApp.ref,
configurationProfileId: appConfigProfile.ref,
content: JSON.stringify({
someAppConfigResource: "SomeAppConfigResourceValue",
//... add more as needed.
}),
// https://www.rfc-editor.org/rfc/rfc9110.html#name-content-type
contentType: "application/json",
}
);
// Perform deployment.
new CfnDeployment(this, "Deployment", {
applicationId: testAppConfigApp.ref,
configurationProfileId: appConfigProfile.ref,
configurationVersion: configVersion.ref,
deploymentStrategyId: immediateDeploymentStrategy.ref,
environmentId: appConfigEnv.ref,
});
}
}
Here is what goes inside my lambda handler (please note that you should have lambda layers enabled for AppConfig extension, see more information here):
const http = require('http');
exports.handler = async (event) => {
const res = await new Promise((resolve, reject) => {
http.get(
"http://localhost:2772/applications/TestAppConfigApp/environments/Production/configurations/TestAppConfigProfile",
resolve
);
});
let configData = await new Promise((resolve, reject) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('error', err => reject(err));
res.on('end', () => resolve(data));
});
const parsedConfigData = JSON.parse(configData);
return parsedConfigData;
};
EDIT: As promised, I released a new npm library : https://www.npmjs.com/package/cdk-appconfig, as of this update, this is still pre-release, but time permitting I will release a 1.x soon. But this will allow people to check out/fork if need be. Please share feedback/or open PRs if you'd like to collaborate.
I have no experience with AWS AppConfig. But I would start here and here

My spectron app.client doesn't contains all the methods

I'm trying to test my electron app using spectron and mocha, here is my file 'first.js' containing my tests:
const assert = require('assert');
const path = require('path');
const {Application} = require('spectron');
const electronPath = require('electron');
describe('GULP Tests', function () {
this.timeout(30000)
const app = new Application({
path: electronPath,
args: [path.join(__dirname, '..', 'main.js')]
});
//Start the electron app before each test
before(() => {
return app.start();
});
//Stop the electron app after completion of each test
after(() => {
if (app && app.isRunning()) {
return app.stop();
}
});
it('Is window opened', async () => {
const count = await app.client.getWindowCount();
return assert.equal(count, 1);
});
it('Clicks on the project creation button', async () => {
await app.client.waitUntilWindowLoaded();
const title = await app.client.
console.log(title);
return assert.equal(title, 'Welcome to GULP, !');
});
});
My first test is passing, but for the second one i'd like to do a click on an element, but my app.client does not contain a .click methods, and also no getText or getHTML. I've tried to import browser from webdriverio but it was the same problem, I get an error when testing saying me that those methods doesn't exists. I've red the spectron documentation and they're using .click and .getText methods regularly, why I don't get them ? I've imported spectron as it's said in the documentation to.
Thanks.
I have struggled with the same issue for a while. After much trial and error i changed my async methods to normal functions.
it('Clicks on the project creation button', function() {
app.client.waitUntilWindowLoaded();
const title = await app.client.
console.log(title);
return assert.equal(title, 'Welcome to GULP, !');
});
Strange but it worked for me. hopefully it helps.

How can I save in Dalekjs terminal

How can I save the content of the 'test' object after its opened?
for example:
module.exports = {
'Page title is correct': function (test) {
test
.open('http://google.com')
// save content of test the HTML DOM
.assert.title().is('Google', 'It has title')
.done();
}
};
or maybe to interact directly with phantomJS
It is possible?
Even if it is not the main purpose of DalekJS to do things like this, it is technically possible to do it like so:
module.exports = {
'Can store html': function (test) {
test.open('http://google.com')
.execute(function () {
this.data('htmlData', window.document.getElementsByTagName('html')[0].outerHTML);
})
.log.message(function () {
var data = test.data('htmlData');
var fs = require('fs');
fs.writeFileSync('nameOfTheFile.html', data);
return data;
})
.assert.title().is('Google', 'It has title')
.done();
}
};
We execute some in browser JavaScript using the execute method & pipe it over to node using the data('key', 'value') storage method.
We access this data later in our log.message method which runs in the node context. This enables us to load the FileSystem module & finally to store the captured html into a file.

Resources