unmock-core
Version:
[][npmjs] [](https://circleci.com/gh/unmock/unmock-js) [](h
87 lines • 3.04 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const debug_1 = require("debug");
const expect = require("expect");
const fs = require("fs");
const lodash_1 = require("lodash");
const os_1 = require("os");
const path_1 = require("path");
const expect_extend_1 = require("./expect-extend");
const snapshot_writer_reader_1 = require("./snapshot-writer-reader");
const debugLog = debug_1.default("unmock:snapshotter");
exports.DEFAULT_SNAPSHOT_DIRECTORY = path_1.resolve(os_1.tmpdir(), ".unmock");
const DEFAULT_OPTIONS = {
outputFolder: exports.DEFAULT_SNAPSHOT_DIRECTORY,
};
exports.resolveOptions = (userOptions) => {
return lodash_1.merge({}, DEFAULT_OPTIONS, userOptions);
};
const ensureDirExists = (directory) => {
if (!fs.existsSync(directory)) {
debugLog(`Creating snapshot directory: ${directory}`);
return fs.mkdirSync(directory);
}
if (!fs.lstatSync(directory).isDirectory()) {
throw Error(`Destination exists but is not directory: ${directory}`);
}
debugLog(`Directory exists: ${directory}`);
return;
};
class FsSnapshotter {
constructor(options) {
this.writer = new snapshot_writer_reader_1.FsSnapshotWriterReader(options.outputFolder);
FsSnapshotter.extendExpectIfInJest(this.writer);
}
static getOrUpdateSnapshotter(newOptions) {
if (typeof FsSnapshotter.instance !== "undefined") {
if (newOptions) {
const updatedOptions = exports.resolveOptions(newOptions || {});
ensureDirExists(updatedOptions.outputFolder);
FsSnapshotter.instance.update(updatedOptions);
}
return FsSnapshotter.instance;
}
const options = exports.resolveOptions(newOptions || {});
ensureDirExists(options.outputFolder);
FsSnapshotter.instance = new FsSnapshotter(options);
return FsSnapshotter.instance;
}
static extendExpectIfInJest(writer) {
if (!FsSnapshotter.runningInJest) {
return;
}
expect.extend({
unmockSnapshot: expect_extend_1.unmockSnapshot(writer),
});
}
static reset() {
FsSnapshotter.instance = undefined;
FsSnapshotter.removeExtendExpect();
}
static removeExtendExpect() {
expect.extend({
unmockSnapshot() { },
});
}
static get runningInJest() {
return typeof process.env.JEST_WORKER_ID !== "undefined";
}
readSnapshots() {
return this.writer.read();
}
deleteSnapshots() {
return this.writer.deleteSnapshots();
}
update(newOptions) {
this.writer = new snapshot_writer_reader_1.FsSnapshotWriterReader(newOptions.outputFolder);
FsSnapshotter.extendExpectIfInJest(this.writer);
}
notify(input) {
if (!FsSnapshotter.runningInJest) {
return;
}
return expect(input).unmockSnapshot();
}
}
exports.default = FsSnapshotter;
//# sourceMappingURL=index.js.map