Want to open a new tab within the same tab using Cypress? This blog post shows you two simple and practical ways to get it done. No fuss, just straightforward methods to level up your web application testing with Cypress. Perfect for both newcomers and experienced users looking to enhance their testing skills!
Method 1 – by removing the target=”_blank” attribute
it("Open a new tab in the same tab - Method 1", () => {
cy.visit("https://customera.ro/");
cy.contains("Projects").invoke("removeAttr", "target").click();
cy.url().should("eq", "https://customera.ro/projects/");
});Method 2 – by attaching a click event handler to prevent the default action of the click
it("Open a new tab in the same tab - Method 2", () => {
cy.visit("https://customera.ro/");
cy.contains("Projects")
.then(($anchor) => {
// Attach a click event handler to prevent the default action
$anchor.on("click", (e) => {
e.preventDefault();
});
})
.click();
cy.contains("Tips & Tricks")
.invoke("attr", "href")
.then((href) => {
cy.visit(href);
cy.url().should("eq", "https://customera.ro/projects/");
});
});
