'Can I use cy.writeFile() to write a formatted txt file?
By my test script I want to display the background color (hex value) of some of my web element to a .txt file but I want to display like this the background color of login button hex value. The hex value will be good to be highlighted. Is there any way I can do it.
Solution 1:[1]
Assuming there is a button that has a CSS as color and has a hex value #000000 and has some text, You can do something like this.
cy.get('button').then(($ele) => {
cy.writeFile(
'cypress/fixtures/colors.txt',
'The background color of the element ' +
$ele.text() +
' is ' +
$ele.css('color'),
{flag: 'a+'}
)
})
If you have multiple elements with the same selector, you can just replace then() with each()
cy.get('button').each(($ele) => {
cy.writeFile(
'cypress/fixtures/colors.txt',
'The background color of the element ' +
$ele.text() +
' is ' +
$ele.css('color'),
{flag: 'a+'}
)
})
Your colors.txt file should look like this:
The background color of the element Button-1 is #000000
The background color of the element Button-2 is #FFFFFF
...
...
...
The {flag: 'a+'} will make sure that all the new texts are added to the end of the file rather than overwriting it.
Solution 2:[2]
No, .txt files generally do not have bold formatting, but you could use an HTML file.
Wrap the text with <b>my text</b>, and add <br> to give new line.
const html = `<b>the background color of ${selector}</b> <span style="background-color: yellow">${hex}</span><br>`
cy.writeFile('cypress/backgroundColors.html', html, {flag: 'a+'})
HTML output
Converting rgb to hex
jQuery returns rgb not hex, but sometimes its rgb(0, 0, 0) and sometimes rgba(0, 0, 0, 0) (depending on what sets it).
Here's my full test that covers the conversion,
Cypress.Commands.add('hexBG', (selector) => {
cy.get(selector)
.invoke('css', 'background-color')
.then(rgb => {
const hex = (x) => ("0" + parseInt(x).toString(16)).slice(-2);
const rgb2hex = (rgb) => {
const match = rgb.match(/^rgb(a*)\((\d+),\s*(\d+),\s*(\d+)/);
return "#" + hex(match[2]) + hex(match[3]) + hex(match[4]);
}
return rgb2hex(rgb)
})
})
cy.visit('http://example.com')
const selector = 'h1'
cy.hexBG('h1')
.then(hex => {
const html = `<b>the background color of ${selector}</b> <span style="background-color: yellow">${hex}</span><br>`
cy.writeFile('cypress/backgroundColors.html', html, {flag: 'a+'})
})
cy.get('h1').invoke('css', 'background-color', 'green') // make it more interesting
cy.hexBG('h1')
.then(hex => {
const html = `<b>the background color of ${selector}</b> <span style="background-color: yellow">${hex}</span><br>`
cy.writeFile('cypress/backgroundColors.html', html, {flag: 'a+'})
})
HTML output
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 | Alapan Das |
| Solution 2 |


