'Common used functions abstraction (correct structure)
I do know that there is commands.js where functions can be added that we often use but isnt it gets way to messy if we just have bunch of functions in that js file?
Lets say i have a login form and create account form, for both of them i create page objects to have all the functions there and both of those have email input field and password input field, then i obviously do not want to have two functions in both classes :
class CreateAccPage {
private enterEmail = (email: string) => {
return this;
};
private enterPassword = (password: string) => {
return this;
};
}
class LoginPage {
private enterEmail = (email: string) => {
return this;
};
private enterPassword = (password: string) => {
return this;
};
}
So my concern is having lots of functions in a single commands class which isnt nice in my opinion so what could i do ? creating parent Form class and having those functions there then inherit them or there is a better way. Thank you
Solution 1:[1]
You can have custom commands splitted between several independent JavaScript files, without need of class inheritance. Just remember to import those JavaScript files in Cypress's supportFile.
Solution 2:[2]
Cypress docs clearly states that the common functions defined in cypress/support/commands.js file can be originated something else (very similar to express.js router)
Cypress.Commands.add(name, callbackFn) - cypress
app.get('/', callbackFn) - express.js
In both use cases, you can choose to use inline implementation (as you noted - it will get very messy pretty quickly) or define your functions elsewhere and then use them as delegates. To simplify it - instead of doing this:
Cypress.Commands.add('visit page', (path) => cy.visit(path)
Do this:
/-- Http helpers file: --/
class Http {
static visit(path) {
cy.visit(path)
}
}
/-- commands.js file: --/
Cypress.Commands.add('visit page', Http.visit) // delegation to your function
This way you'll be able to use function from within classes (or without - whatever suits you) and maintain your code properly as a function of time
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tomasz Wojciechowski |
| Solution 2 | ymz |
