Home > Back-end >  Hot to get custom css variable from any element (cypress)
Hot to get custom css variable from any element (cypress)

Time:12-14

enter image description here Hello everyone, i want to create some tests checking the styles of elements. We use these custom CSS vars. Is there any way to get these in cypress instead of checking for e.g. RGB(0,0,0)?

Thx in advance!

CodePudding user response:

If you use cy.should() alongside have.css, you can specify which CSS property to check, and the value.

Using a simple example from your image, it would look something like this:

cy.get('foo')
  .should('have.css', 'min-width', '211px');

If there are more complex checks going on, you can always run the .should() as a callback.

cy.get('foo').should(($el) => {
  const minHeight =  ($el.css('min-height').split('px')[0]);
  expect(minHeight).to.eql(40);
});

I found myself checking a lot of CSS values on elements, and opted to have a custom command that allowed me to pass in an expected object and check for all of those values.

Cypress.Commands.add('validateCss', { prevSubject: 'element' }, (subject, expected: { [key: string]: any }) => {
  Object.entries(expected).forEach(([key, value]) => {
    cy.wrap(subject).should('have.css', key, value);
  });
});

const expected = { 'min-width': '211px', 'min-height': '40px' };
cy.get('foo').validateCss(expected);

CodePudding user response:

Interacting with browser element or Dynamic CSS can be achieved in may ways ,

most use-full is cy.get() with the help of .should()

you can find here ( However i know you already checked this :) )

https://docs.cypress.io/api/commands/get#Get-vs-Find

for Example

cy.get('#comparison')
  .get('div')
  // finds the div.test-title outside the #comparison
  // and the div.feature inside
  .should('have.class', 'test-title')
  .and('have.class', 'feature')
  • Related