UNPKG

chai-snapshots

Version:
61 lines 2.24 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const _ = require("lodash"); const fs = require("fs"); let snapshotContents; let snapshots = {}; let pathToSnaps = ""; let currentTest; exports.SnapshotMatchers = function (options = {}) { options.pathToSnaps = options.pathToSnaps || "./src/__tests__/snaps.json"; options.ignoredAttributes = options.ignoredAttributes || []; options.devMode = typeof options.devMode === "undefined" ? false : true; pathToSnaps = options.pathToSnaps; return function (chai) { try { snapshotContents = fs.readFileSync(options.pathToSnaps, { flag: "r" }).toString(); } catch (e) { snapshotContents = ""; } if (snapshotContents && snapshotContents.length > 0) { snapshots = JSON.parse(snapshotContents); } chai.Assertion.addMethod('matchSnapshotJSON', function (key) { const obj = this._obj; chai.expect(obj).not.to.be.undefined; chai.expect(obj).not.to.be.null; chai.expect(obj).not.to.be.false; const ctx = this; const path = key || _.snakeCase(currentTest.fullTitle()); let snapshot = snapshots[path]; if (!snapshot || options.devMode) { snapshots[path] = snapshot = _.cloneDeep(obj); } ; const expected = JSON.stringify(snapshot, (key, value) => { if (_.includes(options.ignoredAttributes, key)) return undefined; return value; }, 2); const actual = JSON.stringify(obj, (key, value) => { if (_.includes(options.ignoredAttributes, key)) return undefined; return value; }, 2); chai.expect(expected, "Expected snapshot to match").to.eql(actual); }); }; }; if (after) { after(function () { const data = JSON.stringify(snapshots, undefined, 2); fs.writeFileSync(pathToSnaps, data, { flag: "w+" }); }); } if (beforeEach) { beforeEach(function () { currentTest = this.currentTest; }); } //# sourceMappingURL=index.js.map