How to use jest-snapshot - 10 common examples

To help you get started, we’ve selected a few jest-snapshot examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github storybookjs / storybook / src / test_runner.js View on Github external
const allTestState = {
    added: 0,
    matched: 0,
    unmatched: 0,
    updated: 0,
    obsolete: 0,
  }

  for (const group of filterStorybook(storybook, grep)) {

    const filePath = path.resolve(`${configDir}`, `${group.kind}`);
    console.log(chalk.underline(`${group.kind}`));
    const fakeJasmine = {
      Spec: () => {}
    }
    const state = jestSnapshot.getSnapshotState(fakeJasmine, filePath);
    const snapshot = state.snapshot;

    for (const story of group.stories) {
      state.setSpecName(story.name);
      state.setCounter(0);
      const key = `${story.name}`
      const hasSnapshot = snapshot.has(key);
      const context = { kind: group.kind, story: story.name };
      const tree = story.render(context);
      const renderer = ReactTestRenderer.create(tree);
      const actual = renderer.toJSON()

      if (!snapshot.fileExists() || !hasSnapshot) {
        // If the file does not exist of snapshot of this name is not present
        // add it.
        logState('added', story.name);
github tivac / modular-css / packages / test-utils / expect / toMatchRollupCodeSnapshot.js View on Github external
output.forEach(({ isAsset, name, code }) => {
            if(isAsset) {
                return;
            }

            chunks.set(name, `\n${code}`);
        });

        const out = Object.create(null);
        
        // Ensure out object is in a consistent order
        [ ...chunks.keys() ].sort().forEach((key) => {
            out[key] = chunks.get(key);
        });

        return toMatchSnapshot.call(
            this,
            out,
        );
    },
});
github tivac / modular-css / packages / test-utils / expect / toMatchRollupAssetSnapshot.js View on Github external
output.forEach(({ isAsset, fileName, source }) => {
            if(!isAsset) {
                return;
            }
            
            assets.set(fileName, `\n${source}`);
        });
        
        const out = Object.create(null);

        // Ensure out object is in a consistent order
        [ ...assets.keys() ].sort().forEach((key) => {
            out[key] = assets.get(key);
        });

        return toMatchSnapshot.call(
            this,
            out,
        );
    },
});
github tivac / modular-css / packages / test-utils / expect / toMatchRollupSnapshot.js View on Github external
toMatchRollupSnapshot({ output }, name = "") {
        const things = new Map();
        
        output.forEach(({ code, isAsset, fileName, source }) => {
            // Leading newline to make diffs easier to read
            things.set(fileName, `\n${isAsset ? source : code}`);
        });
        
        const out = Object.create(null);

        // Ensure out object is in a consistent order
        [ ...things.keys() ].sort().forEach((key) => {
            out[key] = things.get(key);
        });
        
        return toMatchSnapshot.call(
            this,
            out,
            name,
        );
    },
});
github suchipi / chai-jest-snapshot / src / spec / matchSnapshot.spec.js View on Github external
beforeEach(function() {
    // clear out workspace
    rimraf.sync(workspacePath("*"));
    // create the snapshot file that is considered "existing" by these tests
    const existingSnapshotState = new SnapshotState(undefined, {
      snapshotPath: EXISTING_SNAPSHOT_PATH,
      updateSnapshot: "all",
    });
    existingSnapshotState.match(EXISTING_SNAPSHOT_NAME, tree, EXISTING_SNAPSHOT_NAME);
    existingSnapshotState.save();

    object = undefined;
    snapshotFilename = undefined;
    snapshotName = undefined;
    update = false;
    utils = { flag: () => undefined };
  });
github ezcater / sosia / packages / sosia / change-tracker.ts View on Github external
export default ({cachePath, updateSnapshot}: {cachePath: string; updateSnapshot: boolean}) => {
  if (!cacheMap.has(cachePath)) {
    cacheMap.set(cachePath, new SnapshotState(cachePath, {updateSnapshot: updateSnapshot} as any));
  }

  const snapshotState = cacheMap.get(cachePath);

  const markAsDirty = (key: string) => {
    snapshotState._dirty = true;
    delete snapshotState._snapshotData[key];
  };

  const match = (page: NamedPage) => {
    const testName = page.name;
    const currentHash = hash(page);

    const {added, updated} = snapshotState;

    // run snapshot to see if there was a match
github Marwan01 / food-converter / node_modules / jest-jasmine2 / build / setup_jest_globals.js View on Github external
var _default = ({config, globalConfig, localRequire, testPath}) => {
  // Jest tests snapshotSerializers in order preceding built-in serializers.
  // Therefore, add in reverse because the last added is the first tested.
  config.snapshotSerializers
    .concat()
    .reverse()
    .forEach(path => {
      (0, _jestSnapshot.addSerializer)(localRequire(path));
    });
  patchJasmine();
  const expand = globalConfig.expand,
    updateSnapshot = globalConfig.updateSnapshot;
  const snapshotResolver = (0, _jestSnapshot.buildSnapshotResolver)(config);
  const snapshotPath = snapshotResolver.resolveSnapshotPath(testPath);
  const snapshotState = new _jestSnapshot.SnapshotState(snapshotPath, {
    expand,
    getBabelTraverse: () => require('@babel/traverse').default,
    getPrettier: () =>
      config.prettierPath ? require(config.prettierPath) : null,
    updateSnapshot
  });
  (0, _expect.setState)({
    snapshotState,
    testPath
  }); // Return it back to the outer scope (test runner outside the VM).

  return snapshotState;
};
github igor-dv / jest-specific-snapshot / src / index.js View on Github external
const absoluteSnapshotFile = getAbsolutePathToSnapshot(this.testPath, snapshotFile);

  // store the common state to re-use it in "afterAll" hook.
  commonSnapshotState = this.snapshotState;
  let snapshotState = snapshotsStateMap.get(absoluteSnapshotFile);

  if (!snapshotState) {
    snapshotState = new SnapshotState(absoluteSnapshotFile, {
      updateSnapshot: commonSnapshotState._updateSnapshot,
      snapshotPath: absoluteSnapshotFile,
    });
    snapshotsStateMap.set(absoluteSnapshotFile, snapshotState);
  }

  const newThis = Object.assign({}, this, { snapshotState });
  const patchedToMatchSnapshot = toMatchSnapshot.bind(newThis);

  return patchedToMatchSnapshot(received, testName);
}
github jest-community / jest-editor-support / src / Snapshot.js View on Github external
});
        }
      },
    };

    traverse(fileNode, {
      enter: path => {
        const visitor = Visitors[path.node.type];
        if (visitor != null) {
          visitor(path, state, this._matchers);
        }
      },
    });

    // NOTE if no projectConfig is given the default resolver will be used
    const snapshotResolver = buildSnapshotResolver(this._projectConfig || {});
    const snapshotPath = snapshotResolver.resolveSnapshotPath(filePath);
    const snapshots = utils.getSnapshotData(snapshotPath, 'none').data;
    let lastParent = null;
    let count = 1;

    return state.found.map(snapshotNode => {
      const parents = snapshotNode.parents.filter(isValidParent);
      const innerAssertion = parents[parents.length - 1];

      if (lastParent !== innerAssertion) {
        lastParent = innerAssertion;
        count = 1;
      }

      const result = {
        content: undefined,
github facebook / jest / packages / jest-circus / src / legacy-code-todo-rewrite / jestAdapterInit.ts View on Github external
dispatch({
      name: 'include_test_location_in_result',
    });
  }

  // Jest tests snapshotSerializers in order preceding built-in serializers.
  // Therefore, add in reverse because the last added is the first tested.
  config.snapshotSerializers
    .concat()
    .reverse()
    .forEach(path => {
      addSerializer(localRequire(path));
    });

  const {expand, updateSnapshot} = globalConfig;
  const snapshotResolver = buildSnapshotResolver(config);
  const snapshotPath = snapshotResolver.resolveSnapshotPath(testPath);
  const snapshotState = new SnapshotState(snapshotPath, {
    expand,
    getBabelTraverse,
    getPrettier,
    updateSnapshot,
  });
  setState({snapshotState, testPath});

  addEventHandler(handleSnapshotStateAfterRetry(snapshotState));

  // Return it back to the outer scope (test runner outside the VM).
  return {globals, snapshotState};
};