Unable to open Url (.navigateTo) from .before in TestCafe using PageObjects - testing

I am new to JS and TestCafe.
Using PageObjects in TestCafe my goal is to launch a login page and authenticate before running a test.
The .open call works fine from fixtures. Also from with .before.
fixture `Check for new emails`
.page `https://www.mail.com/myemails`
and
fixture `Check for new emails`
.page `https://www.mail.com/myemails`
.beforeEach(async t => {
console.log("before");
.page `https://www.mail.com/login`;
myloginScreen.performLogin();
})
test ('', async t => {
await t
console.log("In the test step");
});)
PageObject look like this:
import { Selector, t } from 'testcafe';
export default class LoginPage {
constructor () {
this.loginInput = Selector('input').withAttribute('id','email');
this.passwordInput = Selector('input').withAttribute('id','password');
this.signInButton = Selector('button').withAttribute('class','big-button');
this.userMenu = Selector('a').withAttribute('data-which-id', 'gn-user-menu-toggle-button');
}
async performLogin() {
console.log("function entered")
.typeText(this.loginInput, 'user#mail.com')
.typeText(this.passwordInput, 'password')
.click(this.signInButton);
console.log("Form submitted");
}
}
But I want to move the Login URL load to the PageObject like this:
async performLogin() {
console.log("function entered")
.navigateTo ("https://www.mail.com/login")
await t
.typeText(this.loginInput, 'user#mail.com')
.typeText(this.passwordInput, 'password')
.click(this.signInButton);
console.log("Form submitted");
}
The code calls the function fine but quits the .before and jumps to the test step.
I am not sure what I am doing wrong here, will appreciate any help.

The performLogin is an asynchronous method. So, you need to call it with the await keyword:
fixture `Check for new emails`
.page `https://www.mail.com/myemails`
.beforeEach(async t => {
console.log("before");
await myloginScreen.performLogin();
});

Related

Invoking Testcafe 't' Handler Through Anonymous Self Executing Function

I have a case where I would like to use invoke the t test handler with the t.ctx context available outside of the test() function. Is this possible at all? From what I see when I run this script I do see the console spitting out all the available handler options to me, but trying to create an empty user form t.ctx.userForm = {} throws the error:
Cannot implicitly resolve the test run in the context of which the test controller action should be executed. Use test function's 't' argument instead.
import { t } from 'Testcafe';
const setFormContext = (t) => {
console.log(t);
t.ctx.userForm = {};
};
export const intializeEmptyForm = (async(t) => {
await setFormContext(t)
})(t);
I basically want to be able to have code like such, but without overcbloating the POM AccountPage object with custom functions not related to what's on the page, or relying on something like firstName to be invoked in order to make the t.ctx.userForm available.
export const AccountPage = {
enterFirstName: async (firstName) => {
let firstNameField = Selector('#firstName');
await t.typeText(firstNameField, firstName);
// t.ctx.userForm = {}; <- ideally not here as it's tied to enterFirstName
t.ctx.userForm.firstName = firstName;
},
enterLastName: async (lastName) => {
let lastNameField = Selector('#lastName');
await t.typeText(lastNameField, lastName);
t.ctx.userForm.lastName = lastName;
}
// ... some logic that maps t.ctx.userForm values to an assertion that checks all form values after clicking 'Save' are actually present.
}
import { AccountPage } from 'AccountPage';
...
test('User form successfully saves and updates correctly', async () => {
await AccountPage.enterFirstName('First');
await AccountPage.enterLastName('Last');
await AccountPage.clickSave()
})
The import {t} from 'testcafe' statement looks for a test(), beforeEach(), afterEach() or other test function in the call stack and gets the t instance from its arguments. This error occurs when an imported t is used in a function that is not called from a test or hook. This is what happens in your case, since the arrow function whose promise is exported in initializeEmptyForm is self-invoked.
As a solution, you can export a function in initializeEmptyForm (not a promise) and call it from test context.
helper.js
import { t } from 'testcafe';
export const initializeEmptyForm = async () => {
await setFormContext(t);
};
test.js
import { initializeEmptyForm } from './helper.js';
fixture 'fixture 1'
.beforeEach(async t => {
await initializeEmptyForm();
});
test('test 1', async t => {
// ...
});
Alternatively, you can export a function that takes t as an argument:
helper.js
export const initializeEmptyForm = async t => {
await setFormContext(t);
};
test.js
import { initializeEmptyForm } from './helper.js';
fixture 'fixture 1'
.beforeEach(async t => {
await initializeEmptyForm(t);
});
test('test 1', async t => {
// ...
});
My thoughts on this are when visiting a form with a click action then it may be cleaner to do so as part of the click action.
import { Selector, t } from 'testcafe';
export const AccountPage = {
clickEditForm: async () => {
let editButton = Selector('button').withText('Edit');
await t.click(editButton);
// guarantees on a click form we have setup the userForm object;
t.ctx.userForm = {};
},
enterFirstName: async (firstName) => {
let firstNameField = Selector('#firstName');
await t.typeText(firstNameField, firstName);
t.ctx.userForm.firstName = firstName;
},
enterLastName: async (lastName) => {
let lastNameField = Selector('#lastName');
await t.typeText(lastNameField, lastName);
t.ctx.userForm.lastName = lastName;
}
// map t.ctx.userForm values to assertions that checks all form values after clicking 'Save'.
verifyAccountFormDetails: async(expectFormValue = []) => {
// Grab form values
// Then map them to parameters desired or something.
}
}
This allows us to then pass the values around in a cleaner manner with the POM.
import { AccountPage } from 'AccountPage';
...
test('User form successfully saves and updates correctly', async () => {
await AccountPage.enterFirstName('First');
await AccountPage.enterLastName('Last');
await AccountPage.clickSave();
...
// After doing something like account form save then verify values
persist based on what you want to check
await AccountPage.verifyAccountFormDetails(['firstName', 'email'])
})

Set referrer for Firefox on Test Cafe

Looking to set custom referrer for my tests with Test Cafe but cannot find right solution for that. On Firefox you can easily change referrer with some plugins but how to do it within Test Cafe ?
You can use the Request Hooks mechanism for this purpose. I created an example to demonstrate this approach:
import { RequestHook } from 'testcafe';
fixture `fixture`
.page `http://example.com`;
export class MyRequestHook extends RequestHook {
constructor (requestFilterRules, responseEventConfigureOpts) {
super(requestFilterRules, responseEventConfigureOpts);
}
async onRequest (event) {
event.requestOptions.headers['Referer'] = 'http://my-modified-referer.com';
}
async onResponse (event) {
}
}
const hook = new MyRequestHook();
test.requestHooks(hook)('referer', async t => {
await t.navigateTo('https://www.whatismyreferer.com/');
await t.debug();
});

Adding a Login method in fixture.before hook is giving an error in Testcafe

Agenda: I wanted to run login method before all tests and Logout method after all tests, so that if the before hook fails, the test execution won't happen.
I added login logic in fixture.before hook as shown in the code below. But it's giving the following error, can some help me to fix it.
Test file
import { Selector } from "testcafe";
import LoginPage from '../page-objects/login.po';
const loginPage = new LoginPage();
fixture`Getting Started`
.page`https://example.com/`
.before(async t => {
await loginPage.login();
});
test("My First Test", async t => {
const str = await Selector('.home-container h1').textContent;
console.log(str);
});
Pageobjects class
import { Selector, t } from 'testcafe';
import CommonFunctions from '../commons/common-fns'
export default class LoginPage{
constructor () {
this.emailTxtBox = Selector('input[type="email"]');
this.nextBttn = Selector('button[type="submit"]');
this.microsoftNextBttn = Selector('input[type="submit"]');
this.passwordTxtBox = Selector('input[type="password"]');
this.signinBttn = Selector('input[type="submit"]');
this.noBttn = Selector('#idBtn_Back');
}
async login() {
await t
.typeText(this.emailTxtBox, '')
.click(this.nextBttn)
.typeText(this.emailTxtBox, '')
.click(this.microsoftNextBttn)
.typeText(this.passwordTxtBox, '')
.click(this.signinBttn)
.click(this.noBttn);
}
}
You have to use beforeEach fixture hook instead of before
https://devexpress.github.io/testcafe/documentation/test-api/test-code-structure.html#fixture-hooks

Async/await t test codes are not working in in beforeEach of TestCafe

When I tried to use beforeEach in TestCafe, a function with some test codes inside of it seems not working properly.
I am using doLogin in all different fixtures and tests.
Not working
const doLogin = async (t) => {
const login = new Login();
await t
.maximizeWindow()
.typeText(login.emailInput, accounts.EMAIL_SUCCESS, { replace: true, paste: true })
.expect(login.emailInput.value).eql(accounts.EMAIL_SUCCESS, 'check an email')
.typeText(login.passwordInput, accounts.PASSWORD, { paste: true })
.click(login.loginButton);
};
fixture`App > ${menuName}`
.page`${HOST}`
.beforeEach(async (t) => {
// This function is called
// but tests inside the function were not run
doLogin(t)
});
Working Case with a fixture
fixture`App > ${menuName}`
.page`${HOST}`
.beforeEach(async (t) => {
const login = new Login();
// But this case is working.
await t
.maximizeWindow()
.typeText(login.emailInput, accounts.EMAIL_SUCCESS, { replace: true, paste: true })
.expect(login.emailInput.value).eql(accounts.EMAIL_SUCCESS, 'check an email')
.typeText(login.passwordInput, accounts.PASSWORD, { paste: true })
.click(login.loginButton);
});
Working Case with calling from a test
test(`show all ${menuName} menu's components`, async (t) => {
// When I added a function directly into a test function then it worked.
doLogin(t);
// some codes
Could anyone tell me the problem in this code?
In the official document, it said At the moment test hooks run, the tested webpage is already loaded, so that you can use test actions and other test run API inside test hooks.
Thanks in advance.
It seems you missed the await keyword before the doLogin() call:
fixture`App > ${menuName}`
.page`${HOST}`
.beforeEach(async (t) => {
// Don't forget about await
await doLogin(t)
});
Due to the implementation details it's possible to call an async function without await in some cases, but it's better to not rely on this and always use await with async functions.
If you add the async keyword and it don't fix the test, feel free to create a bug report in the TestCafe repository and provide a complete example that can be run to reproduce the problem.

Conditional test to bypass pop up with Testcafe

I'm using testcafe to run some tests in an ecommerce page, but a random pop up is breaking the test. When it appears on the window, the Testcafe is unable to click on the next selector and move forward with the test, and then fail.
Currently, I'm using .js files to hold the selectors, like:
import { Selector } from 'testcafe';
export default class Checkout {
constructor () {
//address
this.addressName = Selector('input#CC-checkoutCepAddressBook-sfirstname');
this.addressLastname = Selector('input#CC-checkoutCepAddressBook-slastname');
//Rest of selectors...
}
Then, I import them to another .js and declare the tests like functions:
import { ClientFunction } from 'testcafe';
import { Selector } from 'testcafe';
import Fixture from '../../../DesktopModel/Chrome/fixture.js';
import Home from '../../../DesktopModel/Chrome/home.js';
import Cart from '../../../DesktopModel/Chrome/cart.js';
...
const fixtureUrlBase = new Fixture();
const home = new Home();
const pdp = new Pdp();
const cart = new Cart();
...
export async function checkoutLoggedBoleto(t) {
await t
.click(pdp.addToCartBtn)
.click(home.finishOrderBtn)
.click(cart.finishOrderBtn)
//Rest of the test actions...}
Finally, I'm executing another.js where I declare the tests using test command:
test
.before(async t => {
await login(t);
})
('Desktop - User Login + Checkout with Invoice', async t => {
// Function Login => Search => PDP => Checkout with Invoice
await checkoutLoggedBoleto(t);
});
Since it is a random event (it happens in different moments, like sometimes in the product page and sometimes in the checkout page), is possible to use some conditional test just bypass this popup, like if the pop up 'x' appears on the screen, click on 'close popup' and continue with test, else continue with the test.
I search in testcafe Test API and have not found such a function.
I'm using testcafe 0.17.0.
TestCafe doesn't provide an API for that. To handle you case, you can check whether the popup appears before each action.
Optionally, to make your code cleaner, you can wrap TestCafe API actions in the following way:
import { t, Selector } from 'testcafe';
const closePopupBtn = Selector('.close-popup');
async function checkPopup () {
if(await closePopupBtn.exists)
await t.click(closePopupBtn);
}
const tc = {
click: async selector => {
await checkPopup();
await t.click(selector);
}
}
test('my test', async () => {
await tc.click('.btn1');
await tc.click('.btn2');
});