'how I can split a function which writes color code of an element to txt file, into 2 different functions in cypress

I have this function in cypress which determine the color code of an element and write that color code in txt file.

rgbToHexConverter.js'```

```export default function writeElementColorToFile(element, color, file) {
  element.invoke('css', color).then(colorCode => {
    cy.writeFile(`${file}`, rgbToHexConverter(colorCode) + '\n', { flag: 'a+' })
  })
}```

I would like to have 2 functions like getElementColorCode(element,color)=> returns colorCode and writeElementClorCodeToFile(colorcode,file)=> writes colorCode in txt file n hex format, so in future I can use them independently.


Solution 1:[1]

You could write them as two separate Cypress custom commands as such:

Cypress.Commands.add('getElementColorCode', {prevSubject: 'element'}, (subject) => {
  return subject.css('color')
})

Cypress.Commands.add('writeColorCodeToFile', {prevSubject: true}, (subject, file) => {
  cy.writeFile(file, rgbToHexConverter(subject) + '\n', { flag: 'a+' });
});

// Example usage
cy.get('foo')
  .getElementColorCode()
  .writeColorCodeToFile('foo.txt');

So, what's happening? In the first command, we're chaining it off of a previous subject. In the example, that's the subject yielded from cy.get('foo'). We've set validation in that first command to only accept elements, but if that was too strict, we could change that to {prevSubject: true}. We're then using the JQuery .css() command to get the CSS Color. Since we're returning that, it is the yielded value from .getElementColorCode()

In the second command, we're again using the prevSubject to automatically pass the value in. We then need to provide our file (in the example, foo.txt), which we then pass into the cy.writeFile() command.

The first command will work fine, so long as an element is always passed in, so I don't see any need to potentially modify it. If you were thinking of not always having the second command as a child command in a Cypress chain, we could do some slight modification to allow it to sometimes be a parent chain.

Cypress.Commands.add('writeColorCodeToFile', {prevSubject: 'optional'}, (subject, file, color?) => {
  cy.writeFile(file, rgbToHexConverter(subject ?? color) + '\n', { flag: 'a+' });
});

// Example usage
cy.writeColorCodeToFile('foo.txt', 'rgb(255, 255, 255)'
// or
cy.get('foo').then(($el) => {
  cy.writeColorCodeToFile('foo.txt', $el.css('color'));
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 agoff