I'm currently grappling with a persistent issue and would appreciate some guidance. I am utilizing Cypress for conducting tests, and I'm trying to find a way to avoid repeated logins for each test case.
Below is my test file:
describe("Authenticated User Validations", () => {
beforeEach(() => {
cy.visit(baseUrl);
cy.login(user, password);
});
it("Login and Verify URL", () => {
cy.url().should('include', '/inventory.html');
});
it("Button Order from A-Z by Default", () => {
cy.contains('A to Z').should('exist');
});
});
Commands.js file
const baseUrl = Cypress.env("CYPRESS_BASE_URL");
Cypress.Commands.add('login', (user, password) => {
cy.session([user, password], () => {
cy.visit(baseUrl);
cy.get('[data-test="username"]').type(user);
cy.get('[data-test="password"]').type(password);
cy.get('[data-test="login-button"]').click();
});
});
I'm very confused about where to add the cy.visit , if in the command.js, or the beforeEach, or in test?
I can make it work without the session, but it types and login each time. I saw another solutions but it's not working for me
Thanks in advance
cy.session(id, setup)is command that behaves differently each time it's called.The parameter
setupis only called on the first time it's called (in the first test of the spec).The 2nd time it's called , the saved data is returned instead of running
setup().Here's a small example
The test runner shows
createdfor test1 andrestoredfor test2.What about `cy.visit()`?
Inside both tests the URL is
about:blankwhich is the Cypress default page if nocy.visit()is called.So, each test must make it's own visit the the page you want to test.
This section of the docs Where to call cy.visit() gives the options
The weird stuff
See Session caching
So when you run the spec initially, you see the above log. Run it again and both tests are marked restored instead of test1: created, test2: restored.
You have to manually clear it for the second run with the Clear All Sessions link.
If you modify the test, the session should be cleared automatically but I'm not sure that always happens.