percy / percy-ember

Ember addon for visual regression testing with Percy
https://docs.percy.io/docs/ember
MIT License
73 stars 44 forks source link

Multiple Snapshots in One Test #205

Closed alexlafroscia closed 4 years ago

alexlafroscia commented 4 years ago

Is there a recommended approach to taking multiple snapshots in a single test?

I would be great to be able to pass an additional label when creating a snapshot in addition to assert

await percySnapshot(assert, 'Sub-State')
alexlafroscia commented 4 years ago

I ended up writing my own helper that allows me to provide an optional additional label, which solved my need, but supporting something like this first-class might be nice!

import percySnapshot from '@percy/ember';

/**
 * @param {Assert|string} assert
 * @return {string}
 */
export function nameFromAssert(assert) {
  if (assert.test?.module?.name && assert.test?.testName) {
    return `${assert.test.module.name} | ${assert.test.testName}`;
  } else {
    return assert;
  }
}

/**
 * @param {Assert|string} assert
 * @param {string} label
 * @return {string}
 */
export function createSnapshotName(assert, label) {
  if (label) {
    return `${nameFromAssert(assert)} | ${label}`;
  }

  return nameFromAssert(assert);
}

/**
 * Wrapper for the default `percySnapshot` helper that allows for optionally
 * providing an extra label for your assertion. This is useful when putting multiple
 * snapshots in a single test.
 *
 * @param {Assert|string} assert
 * @param {string|object} labelOrOptions
 * @param {object} optionsOrNothing
 */
export default function percySnapshotWithLabel(assert, labelOrOptions, optionsOrNothing) {
  let label = labelOrOptions;
  let options = optionsOrNothing;

  // Handle options provided as second argument w/o additional label
  if (typeof labelOrOptions !== 'string') {
    options = label;
    label = undefined;
  }

  return percySnapshot(createSnapshotName(assert, label), options);
}
wwilsman commented 4 years ago

Hi @alexlafroscia, thanks for opening an issue!

What you've done here, wrapping the original function, is actually the recommended way going forward for generating your own snapshot names or adding additional functionality to the snapshot function!

In the future, we might even remove the default name generating behavior since it is possible for it to break with other testing frameworks, when tests have the same name, or when taking multiple snapshots for a single test like you're doing.

I'm going to close this since we don't have plans to add more possible name formatting and you've already done what we would have recommended. 😄