Skip to content

Instantly share code, notes, and snippets.

@wpscholar
Created January 22, 2020 21:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wpscholar/6a874778c6cab84515b7fa1dceb7a0bf to your computer and use it in GitHub Desktop.
Save wpscholar/6a874778c6cab84515b7fa1dceb7a0bf to your computer and use it in GitHub Desktop.
Cypress setup for conditional WordPress login. (Double dashes in file names should be replaced with slashes)
// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add("login", (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This is will overwrite an existing command --
// Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })
Cypress.Commands.add('login', (username, password) => {
cy.getCookies().then(cookies => {
let hasMatch = false;
cookies.forEach((cookie) => {
if (cookie.name.substr(0, 20) === 'wordpress_logged_in_') {
hasMatch = true;
}
});
if (!hasMatch) {
cy.visit('/wp-login.php').wait(1000);
cy.get('#user_login').type(username);
cy.get('#user_pass').type(`${password}{enter}`);
}
});
});
// ***********************************************************
// This example support/index.js is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************
// Import commands.js using ES2015 syntax:
import './commands';
Cypress.Cookies.defaults({
whitelist: /wp|wordpress/
});
before(() => {
cy.login(Cypress.env('wpUsername'), Cypress.env('wpPassword'));
});
{
"wpUsername": "username",
"wpPassword": "password"
}
@obedparla
Copy link

obedparla commented Dec 26, 2020

Great, simple code, cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment