I have a React app on http://localhost:3000/ which displays a login page, or if the user is logged in already then it will redirect to http://localhost:3000/home. This is the first time I'm trying Cypress and I'm not sure how to begin my test.
This is what I have so far:
describe("User can access home page after login", () => {
it("displays home page", () => {
cy.visit("http://localhost:3000/");
cy.url().should("contain", "/home");
If the should() fails (so url does not contain "/home") then I want to fill in the login form with the username and password so I can access the rest of the app and run further tests. Is there a way to do some action only when the "should" function fails?
I tried without the should() to go straight to
cy.get('[type="text"]').type("email@email.com");
cy.get('[type="password"]').type("password");
but this gives an error if the user has already logged in because then there is no element in the page with the type="text".
Edit:
I've discovered cy.session but this gives the same error where the type="text" field doesn't exist because the page has already redirected. The cy.wait() doesn't seem to be helping.
describe("User can access home page after login", () => {
beforeEach(() => {
cy.session("user", () => {
cy.visit("http://localhost:3000/");
cy.wait(5000);
if (cy.url() !== "http://localhost:3000/home") {
cy.get('[type="text"]').type("email@email.com");
cy.get('[type="password"]').type("password");
cy.get("section > :nth-child(3)").click();
cy.wait(2000);
}
});
});
I think .should()
is the wrong thing to use, because it fails the test if criteria isn't met.
But .then()
can be used to check the url without failing
describe("User can access home page after login", () => {
it("displays home page", () => {
cy.visit("http://localhost:3000/");
cy.url().then(url => {
if (!url.includes('/home') {
// do your login here
}
})