Skip to content

Instantly share code, notes, and snippets.

@KleaTech
Created July 24, 2024 13:01
Show Gist options
  • Save KleaTech/5032ebbd5eb91d1bda58e99cf19a84bf to your computer and use it in GitHub Desktop.
Save KleaTech/5032ebbd5eb91d1bda58e99cf19a84bf to your computer and use it in GitHub Desktop.
Cypress custom command similar to .then() but with retry-ability
declare global {
namespace Cypress {
interface Chainable<Subject> {
/**
* Custom command similar to cy.then() but with retry-ability
* @example cy.get('@jsonString').transformValue(JSON.parse).should('deep.equal', expectedValue)
* Note: If a .should() assertion is successful, the retry chain is stopped.
* So eg. cy.get('@jsonString').should('exist').transformValue(JSON.parse) will not query the jsonString again once it exists.
*/
transformValue<T>(transformFn: (subject: Subject) => T): Chainable<T>;
}
}
}
Cypress.Commands.addQuery('transformValue', transformFn => {
return subject => transformFn(subject);
});
function extractItem() {
return cy.window()
.its('localStorage')
.invoke('getItem', 'STORED_ITEM')
.transformValue(item => {
// We need to put this in an if statement to avoid flooding the logs
// We also cannot use .should() because it will stop the retry chain and the localStorage will not be queried again
if (!item) expect(item).to.exist;
try {
return JSON.parse(item as string);
} catch (exception: any) {
expect.fail(`Error parsing JSON: ${exception.message}`);
}
});
}
extractItem.should((item: any[]) => {
assert.equal(item.length, 42);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment