add-commands.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright 2018-2022 Elyra Authors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import { kebabCase } from 'lodash';
  17. import { ISnapshotResults } from './plugin';
  18. let snapshotIndexTracker: { [key: string]: number } = {};
  19. beforeEach(() => {
  20. // reset tracker before each test, otherwise test retries will act as if there
  21. // are multiple snapshots in one test case.
  22. snapshotIndexTracker = {};
  23. });
  24. const getSnapshotPath = (test: any): string => {
  25. const names = [];
  26. for (let k = test; k; k = k.parent) {
  27. names.push(k.title);
  28. }
  29. const filename = names
  30. .filter(x => x)
  31. .map(x => kebabCase(x))
  32. .reverse()
  33. .join('/');
  34. if (snapshotIndexTracker[filename] !== undefined) {
  35. snapshotIndexTracker[filename] += 1;
  36. } else {
  37. snapshotIndexTracker[filename] = 1;
  38. }
  39. const index = snapshotIndexTracker[filename];
  40. const snapshotsFolder = Cypress.config('snapshotsFolder');
  41. return `${snapshotsFolder}/${filename}.${index}.snap`;
  42. };
  43. Cypress.Commands.add('matchesSnapshot', { prevSubject: true }, value => {
  44. const test = (Cypress as any).mocha.getRunner().suite.ctx.test;
  45. const path = getSnapshotPath(test);
  46. cy.task<ISnapshotResults>('matchesSnapshot', { path, value }).then(res => {
  47. if (res.status === 'fail') {
  48. const error = new Error(res.message);
  49. error.name = res.name;
  50. throw error;
  51. }
  52. if (res.status === 'new') {
  53. Cypress.log({ message: 'Generating new snapshot...' });
  54. }
  55. });
  56. });