meinaart / cypress-plugin-snapshots

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

(feat) Support 3rd-party serializers #154

Open TheJaredWilcurt opened 3 years ago

TheJaredWilcurt commented 3 years ago

Jest allows you to specify the location of a "snapshot serializer" file. This gives users the power to format the snapshots however they like.

  // jest.config.js
  snapshotSerializers: [
    '<rootDir>/node_modules/jest-serializer-vue-tjw'
  ],

For example, if I wanted to create a serializer that would reverse an html string (simple, contrived example), it would look like this:

module.exports = {
  test: function (received) {
    // if true, it runs the print function
    return typeof(received) === 'string' && received.startsWith('<');
  },
  print: function (received) {
    return received.split('').reverse().join('');
  }
}

The flow for this is:

  1. A test has some type of expectation, like so: expect(INPUT).toMatchSnapshot();
  2. The INPUT is passed to the serializer, as is, (number, object, string, whatever)
  3. Run the serializer test function with the INPUT to see if it is a type of data it wants to serialize
  4. If the serializer test returns truthy, then run the serializer print function passing in the INPUT
  5. When the serializer finishes it returns a modified version of the INPUT
  6. If another serializer was defined in the array in the config, repeat the process
  7. @cypress/snapshot then either stores the modified value, or compares against the existing stored value.

With this, plugins can can made for specific frameworks (Vue, Angular, React, etc) to improve their snapshots.

PLEASE keep the api the same as what Jest uses, so I don't need to maintain two libraries to do the same thing.