meinaart / cypress-plugin-snapshots

Plugin for snapshot tests in Cypress.io
MIT License
491 stars 116 forks source link

(feat) snapshot strings #122

Open bahmutov opened 4 years ago

bahmutov commented 4 years ago

Using this plugin to snapshot strings, like HTML almost works

it.only('sanity check: string snapshots work', () => {
  cy.wrap('hello, world').toMatchSnapshot()
})

saves the snapshot file

exports[`sanity check: string snapshots work #0`] = `
hello, world
`;

but the comparison on the next run fails

Screen Shot 2020-05-29 at 1 52 17 PM

Notice string vs "string"

I logged the task values

expectedRaw >>>
hello, world
<<<
subject >>>hello, world<<<
{
  subject: 'hello, world',
  dataType: 'json',
subject to snapshot >>>"hello, world"<<<
expected >>>
hello, world
<<<
actual >>>"hello, world"<<<

So close!

It would be nice to use for component's HTML snapshots in https://github.com/bahmutov/cypress-react-unit-test/pull/261

it('should render counts', () => {
  mount(<PositiveCounter />)
  cy.get('.increment')
    .click()
    .click()
    .click()
  // make sure the component updates
  cy.contains('Value: 3')
    // previous command yields jQuery element
    // I would like to get its outer HTML which
    // we can do via $el[0].outerHTML shorthand
    .its('0.outerHTML')
    .toMatchSnapshot()
})
iainxt commented 3 years ago

Here is a simplier re-production of the issue

        it.only('Html String Snapshot', () => {
            let innerHTML = `<body>\n  <span>hello</span>\n</body>`;
            cy.wrap(innerHTML).toMatchSnapshot();
        });

As a workaround I am calling .split('\n') and comparing as an array:

        it.only('Html String Snapshot', () => {
            let innerHTML = `<body>\n  <span>hello</span>\n</body>`.split('\n');
            cy.wrap(innerHTML).toMatchSnapshot();
        });
matchu commented 3 years ago

++ to this, I couldn't figure out how to make string snapshots work, and found ways to check what I was looking for as objects as instead 🤔

louMoxy commented 2 years ago

Yeah cheers for your comments everyone, this was really helpful for me, my use case was that I have styled components and charting libraries so both the classes and id are randomly generated, but managed to created a cypress custom command to handle this:

const styledComponentClass = /class="sc-.*?\"/g
const endOfElement = /<\/.*?\>/g
const idAttribute = /id=".*?\"/g

Cypress.Commands.add('matchDomSnapshot', (selector) => {
  cy.get(selector).then(el => {
    cy.wrap(el[0].innerHTML
      .replace(styledComponentClass, '')
      .replace(idAttribute, '') 
      .split(endOfElement)
      .filter(string => string !== '')
    ).toMatchSnapshot()
  })
})