plugin.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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 fs from 'fs';
  17. import { diffStringsUnified } from 'jest-diff';
  18. import { utils } from 'jest-snapshot';
  19. const createSnapshot = (value: any): string => {
  20. let obj = value;
  21. try {
  22. obj = JSON.parse(value);
  23. } catch {
  24. // no-op
  25. }
  26. const serializedObj = utils.serialize(obj);
  27. // replace UUIDs with something generic
  28. return serializedObj.replace(
  29. /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/gi,
  30. 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  31. );
  32. };
  33. interface ISnapshotOptions {
  34. path: string;
  35. value: any;
  36. }
  37. export type ISnapshotResults =
  38. | IPassSnapshotResults
  39. | IFailSnapshotResults
  40. | INewSnapshotResults;
  41. interface IPassSnapshotResults {
  42. status: 'pass';
  43. }
  44. interface IFailSnapshotResults {
  45. status: 'fail';
  46. name: string;
  47. message: string;
  48. }
  49. interface INewSnapshotResults {
  50. status: 'new';
  51. }
  52. export const register = (on: any, _config: any): void => {
  53. on('task', {
  54. matchesSnapshot({ path, value }: ISnapshotOptions): ISnapshotResults {
  55. const newSnap = createSnapshot(value);
  56. if (fs.existsSync(path)) {
  57. const snap = fs.readFileSync(path, { encoding: 'utf-8' });
  58. if (snap !== newSnap) {
  59. const noColor = (string: string): string => string;
  60. const diff = diffStringsUnified(snap, newSnap, {
  61. aColor: noColor,
  62. bColor: noColor,
  63. changeColor: noColor,
  64. commonColor: noColor,
  65. patchColor: noColor
  66. });
  67. return {
  68. status: 'fail',
  69. name: 'Snapshot Match Error',
  70. message: `Value does not match stored snapshot:\n${diff}`
  71. };
  72. }
  73. return { status: 'pass' };
  74. }
  75. if (process.env.CI === 'true') {
  76. return {
  77. status: 'fail',
  78. name: 'Snapshot Not Found',
  79. message: `${path} does not exist.`
  80. };
  81. }
  82. fs.writeFileSync(path, newSnap);
  83. return { status: 'new' };
  84. }
  85. });
  86. };