I am a newbie at running Jest puppeteer.
I'm trying to run a test suite locally that I did not write.
All the tests fail to run and I get this error pointing at beforeEach...
"beforeEach(async () => {"
"thrown: "Exceeded timeout of 5000 ms for a hook.
Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test.""
Where / how exactly should I place the setTimeout?
Is there something else I am missing or have in the wrong spot?
const baseURL = "http://localhost:1234";
const puppeteer = require('puppeteer');
beforeEach(() => {
// Reset mock function's states before each test.
jest.clearAllMocks();
});
describe("chatbot", () => {
beforeEach(async () => {
const browser = await puppeteer.launch({headless: false, slowMo: 250,});
const page = await browser.newPage();
await page.goto(baseURL, { waitUntil: "load" });
// set the fade-ins to 0 ms to prevent timeouts in tests
await page.evaluate(() => { window.animationDelay = 0 })
await page.click("#chat-circle");
await browser.close()
});
it("should show contact info when the user enters 'contact'", async () => {
// submit the form with a message, expect to see the response
const message = "contact";
await page.evaluate(() => {
// get this same const in the page's context
const message = "contact";
$("#chat-input").val(message)
});
await page.click("#chat-submit");
await expect(page).toMatch("We have 24 hour phone support. Our phone number is +01 312 555 8432. We look forward to hearing from you!");
});
it("should show credit card help message when the user enters 'credit card'", async () => {
// submit the form with a message, expect to see the response
const message = "credit card";
await page.evaluate(() => {
// get this same const in the page's context
const message = "credit card";
$("#chat-input").val(message)
});
await page.click("#chat-submit");
await expect(page).toMatch("You can pay with any major credit card. Enter your card details and billing address at checkout.");
});
it("should show payment help message when the user enters 'payment'", async () => {
// submit the form with a message, expect to see the response
const message = "payment";
await page.evaluate(() => {
// get this same const in the page's context
const message = "payment";
$("#chat-input").val(message)
});
await page.click("#chat-submit");
await expect(page).toMatch("We have three payment options: credit card, paypal, or apple pay. Choose your preferred method at checkout.");
});
it("should show help options when the users enters 'help'", async () => {
// submit the form with a message, expect to see the response
const message = "help";
await page.evaluate(() => {
// get this same const in the page's context
const message = "help";
$("#chat-input").val(message)
});
await page.click("#chat-submit");
await expect(page).toMatch("Enter a keyword for help with a topic: contact, payment, credit card, destinations.");
});
});
Thank you
You just need to place it on the top
const baseURL = "http://localhost:1234";
const puppeteer = require('puppeteer');
jest.setTimeout(500000);
beforeEach(() => {
// Reset mock function's states before each test.
jest.clearAllMocks();
});
....
Related
I am working on storageState/use for a one-time authentication strategy, the problem is that storageState is not reflected on the page on each test suite while limiting a storageState to a test describe block.
import { faker } from "#faker-js/faker";
import { test, expect } from "#playwright/test";
import TestHelper from "../helpers";
test.describe("Admin Test - Group Manage:", () => {
test.use({ storageState: TestHelper.storageStateByRole("admin") });
test.beforeEach(async ({ page }) => {
await page.goto("/groups/create", { waitUntil: "networkidle" });
await expect(page).toHaveURL(/.*groups\/create/);
});
test("Admin user should access to the group create screen", async ({
page,
}) => {
const titleSelector = '[aria-label="breadcrumb"] >> text=Create Group';
await test.expect((await page.locator(titleSelector)).count()).toEqual(1);
});
test("Admin user can create & delete a group", async ({ page }) => {
const groupName = faker.commerce.productName();
const groupDescription = faker.commerce.productDescription();
// Fill group title
await page.locator('input[type="text"]').fill(groupName);
// Fill group description textarea
await page.locator("textarea").first().fill(groupDescription);
// Save group information
await page.locator('button:has-text("Save Changes")').click();
await expect(page).toHaveURL(/.*groups/);
const rowSelector = `div[role="row"]:has-text("${groupName}")`;
await page.waitForSelector(rowSelector);
await expect(await page.locator(rowSelector).count()).toEqual(1);
const newGroupRow = await page.locator(rowSelector);
await expect(newGroupRow).toContainText(groupName);
await expect(newGroupRow).toContainText(groupDescription);
// Remove created Group
await page
.locator(`div[role="row"]:has-text("${groupName}") >> button`)
.nth(1)
.click();
await page.locator("text=Confirm").click();
await expect(await page.locator(rowSelector).count()).toEqual(0);
});
});
I confirmed that testing the first suite works correctly, but the playwright opened a new worker for the second test suite, I realized that auth cookie wasn't set to the browser. Is that possible, or not?
I'm trying pick some data from followers page, but always return a empty array.
That's my code:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({headless:false});
const page = await browser.newPage();
await page.goto('https://www.instagram.com/accounts/login/', {
waitUntil: 'networkidle0',
});
// Wait for log in form
await Promise.all([
page.waitForSelector('[name="username"]'),
page.waitForSelector('[name="password"]'),
page.waitForSelector('[type="submit"]'),
]);
// Enter username and password
await page.type('[name="username"]', 'yourAccount');
await page.type('[name="password"]', 'yourPassword');
// Submit log in credentials and wait for navigation
await Promise.all([
page.click('[type="submit"]'),
page.waitForNavigation({
waitUntil: 'networkidle0',
}),
]);
await page.goto('https://www.instagram.com/publicProfile /followers/', {waitUntil: 'networkidle0'});
const teste = await page.evaluate(() => {
const followers = document.querySelectorAll("._aaco span");
let followersArray = []
followers.forEach((item) =>{
followersArray.push(item.innerText)
})
return followersArray
})
console.log(teste)
await browser.close();
})();
publicProfile in the URL is a profile that I choose, but for privacy reasons e alterate for publicProfile.
UPDATE: The problem has resolved, as Örvar said the problem was that I wasn't logged, soo I search for help here and I found this (Puppeteer Login to Instagram) question that solved my question.
When you use a tool like Puppeteer to get content from a site where you need to login, you also need to login using Puppeteer, so the site that you are logging into will generate a user cookie.
Log into Instagram using Puppeteer with user credentials
When Puppeteer has logged in with user credentials, you can run the code you have posted above.
I am using JEST + Puppeteer to run functional tests on hosted web app.
here is test code:
const puppeteer = require('puppeteer');
const url = 'https://somewebsite.com';
const login = (async(page, login, password) =>{
await page.goto(url)
await page.waitForSelector('#mat-input-0')
await page.type('#mat-input-0', login)
await page.type('#mat-input-1', password)
await page.click('button')
})
beforeEach(async () => {
browser = await puppeteer.launch({ headless: false });
page = await browser.newPage();
});
afterEach(async () => {
await browser.close();
});
describe('login to website test', () => {
test('non existent user try', async() => {
jest.setTimeout(300000);
await login(page, 'user#email.com', 'upsiforgoTTThepassword')
await page.waitFor(1000)
var element = await page.$eval('.mat-simple-snackbar', (element) => {
return element.textContent.trim()
})
expect(element).toBe('User not Found')
})
})
And the problem I got is, that if I use puppeteer function await browser.close(); to exit browser after test ends It is automatically failed and I get the error in terminal:
● Test suite failed to run
Protocol error: Connection closed. Most likely the page has been closed.
and if I don't close browser after test ends it passes as it should.
I found out if I comment out preset in my jest.config.js, the error stops to occur:
// preset: "jest-puppeteer",
I need to integrate the puppeteer-jest test framework with TestRail using TestRail API. But for that, I need to know what tests are failed and what of the tests are passed
I Search some information in the official GitHub Repository and in the Jest site. But nothing about it.
Test:
describe('Single company page Tests:', () => {
let homePage;
beforeAll(async () => {
homePage = await addTokenToBrowser(browser);
}, LOGIN_FLOW_MAX_TIME);
it('Open the company page from the list', async done => {
await goto(homePage, LIST_PAGE_RELATIVE_PATH);
await listPage.clickSearchByCompanyName(homePage);
await addCompanyNamePopup.isPopupDisplayed(homePage);
await addCompanyNamePopup.fillCompanyName(homePage, companies.century.link);
await addCompanyNamePopup.clickNext(homePage);
await addCompanyNamePopup.fillListName(homePage, listNames[0]);
await addCompanyNamePopup.clickSave(homePage);
await addCompanyNamePopup.clickViewList(homePage);
const nextPage = await clickCompanyName(homePage, browser, companies.century.name);
await companyPage.isOverviewTabPresent(nextPage);
await companyPage.isPeopleTabPresent(nextPage);
await companyPage.isSocialTabPresent(nextPage);
await companyPage.isFinanceTabPresent(nextPage);
await companyPage.isLeaseTabPresent(nextPage);
await homePage.close();
done();
});
}
I expected to get all passed and failed test cases name and write it to JSON with the name of test cases and the result of them.
Actually, I have nothing of this.
You can use true/false assertion approach I like I do in my github project.
for example, try anchor case to some final selector with simple assert:
describe('E2E testing', () => {
it('[Random Color Picker] color button clickable', async () => {
// Setup
let expected = true;
let expectedCssLocator = '#color-button';
let actual;
// Execute
let actualPromise = await page.waitForSelector(expectedCssLocator);
if (actualPromise != null) {
await page.click(expectedCssLocator);
actual = true;
}
else
actual = false;
// Verify
assert.equal(actual, expected);
});
I am using Puppeteer to test the login page of my application.
The below code runs fine on my local system but when run on Jenkins 9 times out of 10, I get error (mentioned below).
I have tried different things to fix this but haven't been successful. Also added setTimeOut but even that doesn't help to fix this.
Here is the sample code:
const puppeteer = require('puppeteer');
const CREDS = require('../creds');
describe('Login & Title', () => {
var browser, page;
var url = 'https://www.example.com/login'
beforeEach (async () => {
browser = await puppeteer.launch({
args: ['--no-sandbox'], headless: true
});
page = await browser.newPage();
await page.goto(url);
})
afterEach (() => {
browser.close()
})
test('Test for Page Title', async () => {
var millisecondsToWait = 500;
setTimeout(function() {
}, millisecondsToWait);
const USERNAME_SELECTOR = '#inputUserName';
const PASSWORD_SELECTOR = '#inputPassword';
const BUTTON_SELECTOR = 'body > div > ng-view > form > div:nth-child(3) > button';
await page.click(USERNAME_SELECTOR);
await page.keyboard.type(CREDS.username);
await page.click(PASSWORD_SELECTOR);
await page.keyboard.type(CREDS.password);
await page.click(BUTTON_SELECTOR);
await page.waitForNavigation();
const title = await page.title();
expect(title).toBe("Example Website");
});
})
I am getting error:
console.assert node_modules/puppeteer/lib/FrameManager.js:597
AssertionError [ERR_ASSERTION]: No node found for selector: #inputUserName
FAIL __tests__/login.test.js
Login & Title
✕ Test for Page Title (513ms)
● Login & Title functionality.. › Test for Page Title
TypeError: Cannot read property 'click' of null
at Frame.click (node_modules/puppeteer/lib/FrameManager.js:598:18)
Any pointers or help would be great! Thanks in Advance.