Recommand · October 22, 2021 0

Cypress : returns undefined on calling function from objects class in page object model

I am following page page object model in cypress. So get the value from getName() created object on class MHome and call the function getName() but it returns undefined

Object class

Class MHome{
    const loc = locator-A
    const loc1 = locator-B
         cy.getTeam2Home(loc, loc1).then((value)=>{
            // cy.log(value.toString())
             cy.wrap  (value.toString());

Calling the getName () function in cypress test case:

const Sh = new MHome();
And ("verify title of elements, function (){
  cy.log (Sh.get.Name())

cy.log (Sh.get.Name()) returns undefined . Kindly help me in

Because you don’t return anything from the function.

To fix that, write this:

Class MHome {
  loc = 'locator-A';
  loc1 = 'locator-B';
  getName() { 
    return cy
      .getTeam2Home(this.loc, this.loc1)
      .then(value => {
        return cy.wrap(value.toString());

Notice how I use return inside getName(). I also changed the declaration and usage of the locator variables. You can also use a constructor inside MHome class like so:

constructor() {
  this.loc = 'locator-A';
  this.loc1 = 'locator-B';

then I can use it somewhere like this:

const sh = new MHome();
// ...
  .then(value => {

Cypress works asynchronously, that’s why I use chains with .then(). You can read more on that here.

Some other recommendations:

  • try to use names that actually say something; loc, loc1, sh are good as examples, but not really good for real code
  • you might export an instance of the class with for example export default new MHome(); and then avoid typing const Sh = new MHome(); which clutters your checks
  • one convention is to start instance names with a lowel letter, so const sh = new MHome(); instead of const Sh = new MHome();; it is just a convention, you don’t need to do it, but many people follow this rule
  • I tend to use one chain per one line, which at least to me looks more readable than having sth like cy.get().find().then() all on one line; but this is highly subjective, so feel free to ignore me on this one

You seem to have a lot of typos all around, a proper ts syntax would be:

class MHome {
    loc1: string
    constructor() {
        this.loc = "locator-A"
        this.loc1 = "locator-B"
    getName() {
        return cy.getTeam2Home(this.loc, this.loc1).then((value)=>{
            // cy.log(value.toString())

And the instantiate the class and call the method like:

const Sh = new MHome()
Sh.getName().then((value)=> { cy.log(value) }