percy/percy-ember

Multiple Snapshots in One Test

Closed this issue · 2 comments

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')

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);
}

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. 😄