Home > front end >  Cypress - import and export functions
Cypress - import and export functions

Time:10-11

How can I better organize my cypress code for testing so that I only need to import some functions?

I want to start by creating a file in which to authenticate on the page, and then I want to import it in a test with several functions.

I tried the following export code and it seems to have been incorrect, with errors:

export function login() {
    cy.visit('https://*********')
    cy.get('input[name="Parameter.UserName"]').type('*****')
    cy.get('input[name="Parameter.Password"]').type('*****')
    cy.contains('Login').click()

}

export default {login};

And in test :

import {login} from 'elements/pages/login.js'

CodePudding user response:

Cypress provides something called the Custom commands for this purpose, you can read about it here.

Go to cypress/support/commands.js and write all your code here like:

Cypress.Commands.add('login', () => {
  cy.visit('https://*********')
  cy.get('input[name="Parameter.UserName"]').type('*****')
  cy.get('input[name="Parameter.Password"]').type('*****')
  cy.contains('Login').click()
})

And then in your any of your test, you can directly add:

cy.login()

CodePudding user response:

Your import needs a relative URL

import {login} from '../elements/pages/login.js'  // relative from cypress/integration

or if under cypress/suport/elements

import {login} from '../support/elements/pages/login.js'  

Absolute imports (where path has no leading ./ or ../) are presumed to be library packages in node_modules.

  • Related