I could use some help with explaining to me how custom commands in cypress work. I am currently writing a function that reads a json file and increments the contents by 1 and want to return it to the test spec so it could be typed into a field. Note* new to JS and Cypress
Here is the code from commands.ts:
Cypress.Commands.add('newUser', () => {
cy.readFile('cypress/fixtures/users.js
const oldUser = user.user;
cy.log(typeof oldUser);
// Getting old number from user
const reg = /d+/gm;
let oldNum = oldUser.match(reg);
cy.log(oldNum);
oldNum = toInteger(oldNum);
cy.log(typeof oldNum);
// New number for user
const newNum = oldNum + 1;
cy.log(newNum.toString());
let newUser = oldUser.split(reg);
cy.log(newUser);
// Add to a specified location
newUser.splice(1, 0, newNum);
cy.log(newUser);
newUser = newUser.join('');
// cy.log(newUser);
cy.writeFile('cypress/fixtures/users.json', { user: newUser });
return newUser;
});
});
and I am trying to use it in the spec file like this:
const newUser = cy.newUser();
cy.log(newUser);
cy.get('[data-cy="email_field"]').type(newUser);
I think part of my issue is not fully understanding how ‘chaining’ works with Cypress and most examples of Custom commands show it using or manipulating something in the DOM but it seems I am more writing a Helper function that I will want to re-use in other tests…
Any guidance is greatly appreciated
I’ve tried using ‘wrap’ and ‘then’ but I don’t think I have the order right (probably due to not fully understanding JS)
2
Answers
Thanks for the help! I was able to make it work by the following:
The correct way is to chain code with a callback function, like this:
I can’t tell if you custom command itself is correct, it’s a real mess. Please consider posting tidier code in your question.