Page Object Methods? - javascript

I'm having trouble setting up my page object to work. It's probably a simple syntax problem, but I haven't been able to find a solution. I am trying to do something like this:
Test:
test('Verify that a user can update their billing profile', async (t) => {
await t
.billingPage.enterBillingInformation('4111111111111111')
.click(billingPage.saveButton)
.expect(billingPage.successMessage.exists).ok();
});
Page:
import { Selector, t } from 'testcafe';
export default class billingPage {
constructor() {
this.cardNameInput = Selector('#cc_name');
this.cardNumberInput = Selector('#credit-card-number');
this.saveButton = Selector('button').withText('Save Card');
this.successMessage = Selector('div').withText('Your billing information has been successfully updated.');
}
async enterBillingInformation(cardNum) {
await t
.typeText(this.cardNameInput, 'Foo Bar')
.typeText(this.cardNumberInput, cardNum)
}
}
This was working when I had the function contents all within the test, but I want to write a second test with invalid credentials and, obvs, I want to reuse code (the actual function is way longer with many more fields). But I can't figure out what I'm doing wrong.
I get this error:
TypeError: Cannot read property 'enterBillingInformation' of undefined
An example in the docs of how to use methods in the page object would be really helpful! This page seems to show how to set up the function, but there is no corresponding code snippet to show how to actually use it in the test.
http://devexpress.github.io/testcafe/documentation/test-api/test-code-structure.html#test-controller

The "t" object is not known inside the billingPage class. You need to pass it to the enterBillingInformation function from the parent test. Here is complete code:
index.js
import { Selector, ClientFunction } from 'testcafe';
import BillingPage from './billingPage';
const billingPage = new BillingPage();
fixture `Getting Started`
.page `Your page`;
test('Verify that a user can update their billing profile', async t => {
await billingPage.enterBillingInformation("4111111111111111", t);
await t
.click(billingPage.saveButton)
.expect(billingPage.successMessage.exists).ok();
});
billingPage.js
import { Selector } from 'testcafe';
export default class BillingPage {
constructor () {
this.cardNameInput = Selector('#cc_name');
this.cardNumberInput = Selector('#credit-card-number');
this.saveButton = Selector('button').withText('Save Card');
this.successMessage = Selector('div').withText('Your billing information has been successfully updated.');
}
async enterBillingInformation(cardNum, t) {
await t
.typeText(this.cardNameInput, 'Foo Bar')
.typeText(this.cardNumberInput, cardNum)
}
}
You can learn more about the TestCafe Page model here.

Related

How to call a method in another module JavaScript?

I have a class with method performing login
LoginPage.js
class loginPage {
fillCredentials(username, password) {
cy.get('[id=username]').type(username);
cy.get('[id=password]').type(password);
return this;
}
clickLogin() {
cy.contains("Login").click();
}
}
export default loginPage;
I have another spec file for testing:
login.spec.js
import {fillCredentials,clickLogin} from '../../support/PageObjects/loginPage'
describe('User Onboarding Emails', () => {
it('Verification email', () => {
cy.visit('/')
fillCredentials('username','password')
clickLogin()
});
});
However, it is giving an error of
(0 , _loginPage.fillCredentials) is not a function
I know its a wrong way of calling a method. Is there any way I can use the methods without creating an instance of class to access methods
You can do so if you make the methods static
class loginPage {
static fillCredentials(username, password) {
cy.get('[id=username]').type(username);
cy.get('[id=password]').type(password);
//return this; // you can't return "this" because there is no this for static methods
}
static clickLogin() {
cy.contains("Login").click();
}
}
export default loginPage;
import {fillCredentials,clickLogin} from '../../support/PageObjects/loginPage'
describe('User Onboarding Emails', () => {
it('Verification email', () => {
cy.visit('/')
fillCredentials('username','password')
clickLogin()
});
});
With static methods you lose this which refers to the class instance, and therefore lose the ability to chain methods,
import {fillCredentials,clickLogin} from '../../support/PageObjects/loginPage'
describe('User Onboarding Emails', () => {
it('Verification email', () => {
cy.visit('/')
fillCredentials('username','password').clickLogin() // can't do this with static
});
});
As functions instead of a class, this is the pattern
// LoginPage.js
export const fillCredentials = (username, password) => {
cy.get('[id=username]').type(username);
cy.get('[id=password]').type(password);
return this;
}
export const clickLogin = () => {
cy.contains("Login").click();
}
// login.spec (same as you have above)
import { fillCredentials, clickLogin } from '../../support/PageObjects/loginPage'
describe('User Onboarding Emails', () => {
it('Verification email', () => {
cy.visit('/')
fillCredentials('username','password')
clickLogin()
});
})
Be wary of encapsulating test code in page objects, it can lead to over-complicated code.
For example, if you now want to test what happens if password is not entered, you can't use fillCredentials because you can't omit the password parameter. So do you add a fillCredentialsWithoutPassword function? Do you modify fillCredentials to test if password is undefined?
So, what's going on is that you are mixing up the module structure with is defined by Closures with the class-instance pattern.
For this scenario (which is class-instance) the functions are NOT part of the object itself, but of it's PROTOTYPE.
So in order to get that function you should access it's prototype.
//create a class (class syntax and this one is pretty much the same)
function xx (){}
//this is what class syntax makes to create a method for the class
xx.prototype.theFunctionIwant = function (){}
//create an instance
var example = new xx()
//this is how you can spy that function in the test
xx.prototype.theFunctionIwant
//ƒ (){}
Try it out : )
The other answers given will work and solve your exact question, but I fear that making the functions static is an anti-pattern for the Page Object Model. Check out this article on how to set up a POM for Cypress. I would highly encourage you to instantiate the class, similar to below.
//LoginPage.js
export class LoginPage { ... }
//login.spec.js
import { LoginPage } from '../../support/PageObjects/loginPage';
describe('User Onboarding Emails', () => {
it('Verification email', () => {
const loginPage = new LoginPage()
cy.visit('/')
loginPage.fillCredentials('username','password')
loginPage.clickLogin()
});
});
You could also use a beforeEach() block to instantiate the variable before each test.
describe('User Onboarding Emails', () => {
let loginPage: LoginPage;
beforeEach(() => {
loginPage = new LoginPage();
});
it('Verification email', () => {
...
});
})
As an aside, it is usually preferred to name classes beginning with an uppercase (LoginPage vs. loginPage). When naming a class this way, you can easily differentiate the class vs. the instantiated variable.

Javascript - Cannot use import statement outside a module

So I have major problem with importing from one class to another and what I have done is in my "main" class which I call
detailsPage.js
import { DetailsPage } from '../tests/detailsPageObj';
const utils = require("../utils/utils");
const assert = require('../node_modules/chai').assert;
const userData = require('../globalContent.json');
describe('Details page', function () {
const detailsPage = new DetailsPage();
// The details page is accessible by the specified URL
it(`Is defined by the URL: ${userData.url}`, async function () {
await detailsPage.navigate();
});
// Details page has a form and it can be filled out with user data
it('Has a form that can receive user data', async function () {
await detailsPage.fillFormWithUserData(); // If you want, make the user data passable to the method
await utils.click(detailsPage.form.buttons.nextStep);
});
if (detailsPage.hasStockConflict) {
// Details page allows the user to fix conflicts in stocks
it('Enables resolution of stock conflicts', async function () {
// Wait for stock to fully load
await browser.sleep(2000);
await detailsPage.clickAllRemoveButtons();
await detailsPage.clickAllDecreaseButtons();
});
}
// Details page allows the user to proceed to the next stage when all conflicts (if any) has been resolved
it('Allows the user to proceed to the next stage of purchasing', async function () {
const nextStepButton = detailsPage.form.buttons.nextStep;
await utils.elementToBeClickable(nextStepButton);
await utils.click(nextStepButton);
});
});
and what I am trying tod o is to get DetailsPage from another script which is called:
detailsPageObj
import { element, by } from 'protractor';
const utils = require("../utils/utils");
const userData = require('../globalContent.json');
export class DetailsPage {
get pageUtils() {
return {
qtyRegex: /^Sorry.*?(\d+)/
}
}
private get fields() {
return {
email: element(by.id('email')),
firstName: element(by.id('firstName')),
lastName: element(by.id('lastName')),
postalCode: element(by.id('postalCode')),
addressOne: element(by.id('addressOne')),
addressTwo: element(by.id('addressTwo')),
phone: element(by.id('phone')),
businessCustomerCB: element(by.id('isBusinessCustomer')),
company: element(by.id('company')),
GST: element(by.id('gst')),
}
}
private get groups() {
return {
address: element(by.css('div#addressGroup.input-container.showHiddenGroup'));
company: element(by.id('companyGroup')),
}
}
private get modals() {
return {
contactModalLink: element(by.id('contactModalLink')),
cross: element(by.className('modal-cross')),
}
}
private get formButtons() {
return {
nextStep: element(by.id('submitIdentityFormButton')),
mobile: this.mobileFormButtons
}
}
private get mobileFormButtons() {
return {
continue: element(by.id('stock-conflict-continue-button')),
removeOutOfStockItems: element(by.css('button[id="removeOutOfStockItems"]')), // I just assumed that this is a part of the form
}
}
private get productFrameMobileButtons() {
return {
stockControll: element.all(by.className('stock-controller mobile')),
remove: element.all(by.className('btn btn-remove btn-outlined mobile')),
}
}
private get productFrameDesktopButtons() {
return {
stockControll: element.all(by.className('stock-controller desktop')),
remove: element.all(by.className('btn btn-remove btn-outlined desktop')),
}
}
get form() {
return {
fields: this.fields,
groups: this.groups,
buttons: this.formButtons,
modals: this.modals
}
}
get productFrame() {
return {
buttons: {
decrease: element.all(by.className("btn left")).first(),
mobile: this.productFrameMobileButtons,
desktop: this.productFrameDesktopButtons
}
}
}
get errors() {
return {
stockConflict: element(by.className('generic-error-heading')),
}
}
}
and what I am trying to do is in detailsPage.js im trying to import detailsPageObj.js but whenever I am trying to do it I do get SyntaxError: Cannot use import statement outside a module.
What am I doing wrong
I don't know what is your environment like, but I experienced a similar problem where my environment used a full build step for creating the target JS code from my sources (e.g. from TypeScript or from ES6+) to a bundled/plain JS.
But then my test environment did not have any build step. So when I executed the tests, it only understood plain JS, which by default in a node.js environment does not recognize import but only require.
You can use import in your node.js code without a build step, but you need to follow some steps, e.g. rename your file from *.js to *.mjs. More details here.

How to access a Vue plugin from another plugins (using Vue.prototype)?

I'm trying to write a Vue plugin that's a simple abstraction to manage auth state across my app. This will need to access other Vue plugins, namely vuex, vue-router and vue-apollo (at the moment).
I tried extending Vue.prototype but when I try to access the plugin's properties how I would normally - eg. this.$apollo - I get the scope of the object, and therefore an undefined error. I also tried adding vm = this and using vm.$apollo, but this only moves the scope out further, but not to the Vue object - I guess this is because there is no instance of the Vue object yet?
export const VueAuth = {
install (Vue, _opts) {
Vue.prototype.$auth = {
test () {
console.log(this.$apollo)
}
}
}
}
(The other plugins are imported and added via. Vue.use() in the main app.js)
Alternatively, I tried...
// ...
install (Vue, { router, store, apollo })
// ...
but as a novice with js, I'm not sure how this works in terms of passing a copy of the passed objects, or if it will mutate the originals/pass by ref. And it's also very explicit and means more overhead if my plugin is to reach out to more plugins further down the line.
Can anyone advise on a clean, manageable way to do this? Do I have to instead alter an instance of Vue instead of the prototype?
In the plugin install function, you do not have access to the Vue instance (this), but you can access other plugins via the prototype. For example:
main.js:
Vue.use(Apollo)
Vue.use(VueAuth) // must be installed after vue-apollo
plugin.js:
export const VueAuth = {
install (Vue) {
Vue.prototype.$auth = {
test () {
console.log(Vue.prototype.$apollo)
}
}
}
}
I found a simple solution for this issue:
In plugin installer you need to add value to not just prototype, but Vue itself to be able to use it globally.
There is a code example:
Installer:
import apiService from "../services/ApiService";
// Service contains 'post' method
export default {
install(Vue) {
Vue.prototype.$api = apiService;
Vue.api = apiService;
}
};
Usage in other plugin:
import Vue from "vue";
...
const response = await Vue.api.post({
url: "/login",
payload: { email, password }
});
Usage in component:
const response = await this.$api.post({
url: "/login",
payload: { email, password }
});
I'm not sure if that's a good solution, but that made my scenario work perfectly.
So, I got around this by converting my property from a plain ol' object into a closure that returns an object, and this seems to have resolved my this scoping issue.
Honestly, I've jumped into Vue with minimal JS-specific knowledge and I don't fully understand how functions and the likes are scoped (and I'm not sure I want to look under that rock just yet......).
export const VueAuth = {
install (Vue, opts) {
Vue.prototype.$auth = function () {
let apollo = this.$apolloProvider.defaultClient
let router = this.$router
return {
logIn: function (email, password) {
apollo.mutate({
mutation: LOGIN_MUTATION,
variables: {
username: email,
password: password,
},
}).then((result) => {
// Result
console.log(result)
localStorage.setItem('token', result.data.login.access_token)
router.go(router.currentRoute.path)
}).catch((error) => {
// Error
console.error('Error!')
console.error(error)
})
},
logOut: function () {
localStorage.removeItem('token')
localStorage.removeItem('refresh-token')
router.go()
console.log('Logged out')
},
}
}
It's a rudimental implementation at the moment, but it'll do for testing.

Jasmine Data Provider is not working (jasmine_data_provider_1.using is not a function)

I am trying to achieve Data Driven testing in my project by using jasmine data providers.
I have a data.ts file like below
export const hardshipTestData = {
scenarios: {
scenario1: {
isHome: 'Yes'
},
scenario2: {
isHome: 'No'
}
}
};
I am using above data in spec file
import { using } from 'jasmine-data-provider';
import { hardshipTestData } from '../../data/testdata';
using(hardshipTestData.scenarios, function (data, description) {
it('testing data providers', () => {
console.log(data.isHome);
});
});
My issue here is when I am trying to write data. intelligence is not even giving the option isHome. When I enforce it and run the test I am getting the following error
TestSuite encountered a declaration exception
configuration-parser.js:48
- TypeError: jasmine_data_provider_1.using is not a function
any help is appreciated
You need to change import type. Try to replace:
import { using } from 'jasmine-data-provider';
with:
const using = require('jasmine-data-provider');
Also, keep in mind that firstly should be describe block:
describe('example test', () => {
using(hardshipTestData.scenarios, (data) => {
it('should calc with operator -', () => {
console.log(data.isHome);
});
});
});
Adding to Oleksii answer, his answer is for typescript.
but If you want to use in plain javascript use below:
Add below in your code:
var using = require('jasmine-data-provider');
Example:
var jasminedatasetobj = require("./jasmineDataDrivenData");
var using = require('jasmine-data-provider');
using(jasminedatasetobj.datadrive, function (data, description) {
it('Open NonAngular js website Alerts', async() => {
await browser.get("https://qaclickacademy.github.io/protocommerce/");
element(by.name("name")).sendKeys(data.name);
});
});
You might need to give full path of Jasmine data provider for plain javascripts to avoid module not found error.
var jsondataobj = require('../../../../config/Jsoninput.json');//define the data source location
var using = require('C:/Users/sam/AppData/Roaming/npm/node_modules/jasmine-data-provider');
describe("Test Jasmine Data provider",function(){
you need to declare the variable for "jasmine-data-provider" , because import can use to import the properties/classes.
instead of using variable you can give any name to the varible (I tried use "post" instead of "using" and it is still working as expected)
your code should be like
import { hardshipTestData } from "../Test";
const using = require("jasmine-data-provider");
describe("Login TestCases", () => {
using(hardshipTestData.scenarios, (alldata: any, alldesc: any) => {
it("login with different credentials", async () => {
console.log(data.isHome);
})
})
})
this will resolve you problem.

Parse JS SDK: Cannot use the Master Key, it has not been provided

I need to use masterKey inside my angular2 app, but I can't pass it to initialize function and I can't google out why.
From package.json: "parse": "~1.9.2".
Initialization:
import {Parse} from '~/node_modules/parse/dist/parse';
#Injectable()
export class TFCloudService {
constructor() {
this.parse = Parse;
Parse.initialize(appConfig.parse.appId, null, appConfig.parse.masterKey);
Parse.serverURL = appConfig.parse.clientServerUrl;
Parse.liveQueryServerURL = appConfig.parse.liveQueryServerURL;
}
}
Error source:
this.edittedUser.save(null, {useMasterKey: true})
.then((user) => {
console.log(user);
});
Error text:
Error: Cannot use the Master Key, it has not been provided.
appConfig.parse.masterKey works fine, I checked that line with hard-coded key too, but got the same result.
Actually guessed the right way to pass that key:
Parse.initialize(appConfig.parse.appId);
Parse.masterKey = appConfig.parse.masterKey;

Categories

Resources