Playwright Logical expect - playwright

I have two headings on the page and I need to make sure that either the one or the other exists in the page.
let heading = page.getByRole('heading', {name: 'MyFirstHeading'});
let heading2 = page.getByRole('heading', {name: 'MySecondHeading'});
await expect(heading).toBeVisible();
What I tried and worked:
try {
await expect(page.getByRole('heading', {name: 'MyFirstHeading'})).toBeVisible();
} catch (error) {
await expect(page.getByRole('heading', {name: 'MySecondHeading'})).toBeVisible();
}

While clarification on what is wanted would be could, I believe the user is asking for other ways to do this...perhaps. I offer this - playwright retrying:
const heading = page.getByRole('heading', { name: 'MyFirstHeading' });
const heading2 = page.getByRole('heading', { name: 'MySecondHeading' });
await expect(async () => {
const headingIsVisible = await heading.isVisible();
const heading2IsVisible = await heading2.isVisible();
expect(headingIsVisible || heading2IsVisible).toBeTruthy(); }
}).toPass({
timeout: 30000,
});

Related

Jest Twilio Mock

I would like to know how do I mock a Twilio function inside a lib.
I need help taking the test
If anyone has any ideas thanks
I have this method:
joinSession(data: ICallConfig) {
const token = data.providerData.Token.toString();
this._sessionId = data.sessionId;
this._localConnectionId = data.providerData.CustomerId;
const videoCallOptions = {
name: data.providerData.RoomName,
tracks: this._stream.getTracks(),
};
try {
this._room = await connect(token, videoCallOptions);
} catch (e) {
console.log('Twilio video error: ' + e);
}
I need to mock twilio's connect() function
My test:
describe('joinSession', () => {
test('connect user in room', () => {
// Create object
const data: ICallConfig = {
providerData: {
Token: '',
CustomerId: '',
RoomName: 'Room Test',
},
sessionId: '',
};
mockMediaStream.addTrack(new MockTrack('audio'));
mockMediaStream.addTrack(new MockTrack('video'));
twilioService.setMediaStream(mockMediaStream);
twilioService.joinSession(data);
});

Playwright Not able to access foreach variable inside of test

I am using foreach to run the test for multiple users.
I can access the variable from foreach inside of beforeAll, but does not work inside of test
the following line does not get the value as expected, i verified i have value for that column in the .csv
await page.locator('#searchByCode').fill(${user.Code}); // Does not Work , get undefined
import fs from 'fs';
import path from 'path';
import { test, expect, Page } from '#playwright/test';
import { parse } from 'csv-parse/sync'; //requires https://www.npmjs.com/package/csv-parse
const users = parse(fs.readFileSync(path.join(__dirname, '../users.csv')), {
columns: true,
skip_empty_lines: true
});
//Want test inside of describe to run in serial mode
test.describe.configure({ mode: 'serial' });
test.use({ viewport: { width: 600, height: 900 } }); //Affects all Tests
let page: Page;
users.forEach(user => {
console.log(user.Email);
test.describe(`Login for user ${user.Email}`, () => {
test.beforeAll(async ({ browser }) => {
// Create page once and sign in.
page = await browser.newPage();
await page.goto('https://XXXXXXX.com');
await page.fill("#logInEmail",`${user.Email}`); **//This one works**
//find password text(#loginInPassword) and enter password
await page.fill('#loginInPassword', `${user.Password}`); **//This one works**
await Promise.all([
page.waitForNavigation(/*{ url: 'https://getinline.net/' }*/),
page.locator('#loginSignIn').click()
]);
});
test.afterAll(async () => {
await page.close();
});
test('SearchBusinessByCode', async ({ browser }, testInfo) => {
await page.locator('#searchByCode').fill(`${user.Password}`); **// Does not Work , get undefined**
await page.locator('button', { hasText: 'Search' }).click();
});
});
}); //forEach

How to send parallel POST requests in puppeteer?

I want to send parallel POST requests in puppeteer. I have to change the payload with every request (URL remains the same).
I tried using puppeteer cluster, but how do I change payload with every request when I queue the same request?
Using normal puppeteer
(async() => {
const browser = await puppeteer.launch({
args: [
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-web-security",
],
executablePath: 'C:/Program Files/..',
headless: false,
});
for(const id of Ids) {
const page = await browser.newPage();
await page.setDefaultNavigationTimeout(60000);
await page.evaluateOnNewDocument(() => {
// Some code
})
await page.setRequestInterception(true);
// Request intercept handler... will be triggered with
// each page.goto() statement
page.on('request', interceptedRequest => {
// Here, is where you change the request method and
// add your post data
var data = {
'method': 'POST',
'postData': JSON.stringify({
....
"similarMaterialId": `${id}`,
}),
'headers': {
.....
},
};
// Request modified... finish sending!
interceptedRequest.continue(data);
});
const response = await page.goto('https://.../getProductInfo');
const responseBody = await response.json();
try {
let title = responseBody.description;
let price = responseBody.price;
fs.appendFile('temp.tsv', `${title}\t${price}\n`, function (err) {
if (err) throw err;
})
}
catch {
console.log(id)
}
await page.close();
}
console.log("Code ended!!")
await browser.close();
})();
I want to create many pages in parallel on a single browser.

postman schema validation into reporter-htmlextra

I'm currently running some tests with postman where I get a schema and try to validate my results against it.
I know the schema is not consistent with the response I'm getting but I wanted to know how is it possible to expand the results to give a bit more information.
so for example if I have a request like this:
GET /OBJ/{ID}
it just fails with the feedback:
Schema is valid:
expected false to be true
I was hoping to manage to get a bit more feedback in my newman report
this is an example of my test:
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
// only preform tests if response is successful
if (pm.response.code === 200) {
var jsonData = pm.response.json();
pm.test("Data element contains an id", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.id).eql(pm.environment.get("obj_id"));
});
pm.test('Schema is valid', function() {
pm.expect(tv4.validate(jsonData, pm.globals.get("objSchema"))).to.be.true;
});
}
and this is how I run my tests:
const newman = require('newman');
newman.run({
insecure: true,
collection: require('../resources/API.postman_collection.json'),
environment: require('../resources/API.postman_environment.json'),
reporters: 'htmlextra',
reporter: {
htmlextra: {
export: './build/newman_report.html',
logs: true,
showOnlyFails: false,
darkTheme: false
}
}
}, function (err) {
if (err) {
throw err;
}
console.log('collection run complete!');
});
is there a way I can get more information about the validation failure?
I tried a few quick google search but have not come up to nothing that seemed meaningful
it's not exactly what I wanted but I managed to fix it with something like this:
// pre-check
var schemaUrl = pm.environment.get("ocSpecHost") + "type.schema";
pm.sendRequest(schemaUrl, function (err, response) {
pm.globals.set("rspSchema", response.json());
});
// test
var basicCheck = () => {
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
pm.test("Response time is less than 200ms", function () {
pm.expect(pm.response.responseTime).to.be.below(200);
});
};
// create an error to get the output from the item validation
var outputItemError = (err) => {
pm.test(`${err.schemaPath} ${err.dataPath}: ${err.message}`, function () {
pm.expect(true).to.be.false; // just output the error
});
};
var itemCheck = (item, allErrors) => {
pm.test("Element contains an id", function () {
pm.expect(item.id).not.eql(undefined);
});
var Ajv = require('ajv');
ajv = new Ajv({
allErrors: allErrors,
logger: console
});
var valid = ajv.validate(pm.globals.get("rspSchema"), item);
if (valid) {
pm.test("Item is valid against schema", function () {
pm.expect(valid).to.be.true; // just to output that schema was validated
});
} else {
ajv.errors.forEach(err => outputItemError(err));
}
};
// check for individual response
var individualCheck = (allErrors) => {
// need to use eval to run this section
basicCheck();
// only preform tests if response is successful
if (pm.response.code === 200) {
var jsonData = pm.response.json();
pm.test("ID is expected ID", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.id).eql(pm.environment.get("nextItemId"));
});
itemCheck(jsonData, allErrors);
}
}
individualCheck(true);
just create a function to do an item test where I do a stupid assert.false to output each individual error in the schema path

Vue-Resource, can't get this.$http.post working in Vue instance

I am trying to post some data usng this.$http.post and I could not figure out how to pass in the data through the route api..
new Vue({
el: '#root',
data: {
newName: '',
nameList: []
},
methods: {
addName(){
this.nameList = this.nameList.concat(this.newName);
var name = this.newName;
this.newName = '';
this.$http.post('/api/name', {name: name}).then((response) => {
console.log(response.message);
});
}
},
mounted(){
this.$http.get('/api/name').then((response) => {
this.nameList= this.nameList.concat(JSON.parse(response.body));
console.log(this.nameList);
});
}
});
It is not very clear, what is the exact issue, here, what exact API you are trying to hit.
If you are trying to hit: /api/name/:someName, you can do following
this.$http.post('/api/name/'+name ).then((response) => {
console.log(response.message);
});
If you are trying to hit: /api/:someName with payload, you can do following
this.$http.post('/api/' + name, {name: name}).then((response) => {
console.log(response.message);
});
Let me know if it helps.

Resources