mass changes

This commit is contained in:
Joshua 2024-01-29 19:08:06 +01:00
parent b61e5c0552
commit 5db74ebcb6
23 changed files with 356 additions and 358 deletions

2
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,2 @@
{
}

View file

@ -1,14 +1,15 @@
const { defineConfig } = require("cypress");
const { functions } = require("./src/utils");
module.exports = defineConfig({
snapshot: {
// snapshotPath: "cypress/snapshots/",
SNAPSHOT_UPDATE: true
// SNAPSHOT_UPDATE: true,
useFolders: true,
},
e2e: {
setupNodeEvents(on, config) {
functions.tasks(on, config);
// implement node event listeners here
},
},
});

View file

@ -1,75 +1,78 @@
/* eslint-env mocha */
/* global cy */
describe("@datashard/snapshot", () => {
context("simple types", () => {
it("works with objects", () => {
cy.wrap({
"foo": "bar",
"Fizzy Drink": "Pop"
}).snapshot(
// "Filename", {
// snapshotPath: "asdasd"
// }
describe("datashard/snapshot", () => {
context("simple types"
// , { env: { SNAPSHOT_UPDATE: true } }
, () => {
it("works with objects", () => {
cy.wrap({
"foo": "bar",
"Fizzy Drink": "Pop"
}).snapshot();
});
it("works with numbers", () => {
cy.wrap(42).snapshot({
snapshotPath: "cypress/fixtures/snapshots",
snapshotName: "Numbers",
});
});
it("works with strings", () => {
cy.wrap("foo-bar").snapshot({
snapshotPath: "cypress/fixtures/snapshots",
snapshotName: "Strings",
});
});
it(
"works with arrays",
{
env: {
SNAPSHOT_UPDATE: true,
},
},
() => {
cy.wrap([1, 2, 3, 4]).snapshot({
snapshotPath: "cypress/fixtures/snapshots",
snapshotName: "Arrays",
});
}
);
// cypress/fixtures/@datashard-snapshot/simple-types/works-with-objects/asdjskadhasj.json
});
// it("works with numbers", () => {
// cy.wrap(42).snapshot({
// snapshotPath: "cypress/fixtures/snapshots",
// snapshotName: "Numbers",
// });
// });
// it("works with strings", () => {
// cy.wrap("foo-bar").snapshot({
// snapshotPath: "cypress/fixtures/snapshots",
// snapshotName: "Strings",
// });
// });
// it(
// "works with arrays",
// {
// env: {
// SNAPSHOT_UPDATE: true,
// },
// },
// () => {
// cy.wrap([1, 2, 3, 4]).snapshot({
// snapshotPath: "cypress/fixtures/snapshots",
// snapshotName: "Arrays",
// });
// }
// );
// it('works with more "complicated" Objects', () => {
// cy.fixture("Complex").snapshot({
// snapshotPath: 'cypress/fixtures/snapshots',
// snapshotName: "Complex"
// })
// })
// it.only("works based on fixtures", () => {
// cy
// .wrap({
// "jsonapi": {
// "version": "2.0"
// },
// "included": [
// {
// "type": "users",
// "id": "2",
// "attributes": {
// "name": "Test"
// }
// }
// ]
// })
// .snapshot({
// snapshotFixture: "generated",
// // snapshotPath: "cypress/fixtures/snapshots",
// // snapshotName: "generated",
// });
// });
});
context("complex types"
// , { env: { SNAPSHOT_UPDATE: true } }
, () => {
it('works with more "complicated" Objects', () => {
cy.wrap({
"status": 200,
"response": {
"array": [0, 1, 2, "Three"],
"object": {
"with": "more details"
}
}
}
).snapshot()
})
it("works based on fixtures", () => {
cy
.wrap({
"jsonapi": {
"version": "2.0"
},
"included": [
{
"type": "users",
"id": "2",
"attributes": {
"name": "Test"
}
}
]
})
.snapshot();
});
})
});

View file

@ -1,4 +0,0 @@
{
"foo": "bar",
"Fizzy Drink": "Soda"
}

View file

@ -1,4 +0,0 @@
{
"foo": "bar",
"Fizzy Drink": "Pop"
}

View file

@ -0,0 +1,14 @@
{
"jsonapi": {
"version": "2.0"
},
"included": [
{
"type": "users",
"id": "2",
"attributes": {
"name": "Test"
}
}
]
}

View file

@ -0,0 +1,14 @@
{
"jsonapi": {
"version": "2.0"
},
"included": [
{
"type": "users",
"id": "2",
"attributes": {
"name": "Test"
}
}
]
}

View file

@ -1,9 +1,14 @@
{
"status": 200,
"response": {
"array": [0, 1, 2, "Three"],
"array": [
0,
1,
2,
"Three"
],
"object": {
"with": "more details"
}
}
}
}

View file

@ -1 +0,0 @@
{"foo":"bar","Fizzy Drink":"Soda"}

View file

@ -1,4 +0,0 @@
{
"foo": "bar",
"Fizzy Drink": "Soda"
}

View file

@ -1,2 +1,2 @@
// register .snapshot() command
require('../..').register()
require('../../src/index').register()

View file

@ -1,7 +1,6 @@
// global cy, Cypress
const { functions } = require("./utils/index");
const register = require("./register");
module.exports = {
register: functions.register,
tasks: functions.tasks,
register
};

View file

@ -1,13 +1,13 @@
const lazy = require("lazy-ass");
const is = require("check-more-types");
const snapshot = require("../snapshots/snapshot");
module.exports = () => {
lazy(is.fn(global.before), "Missing global before function");
lazy(is.fn(global.after), "Missing global after function");
lazy(is.object(global.Cypress), "Missing Cypress object");
Cypress.Commands.add("snapshot", { prevSubject: "optional" }, snapshot);
return snapshot;
};
const lazy = require("lazy-ass");
const is = require("check-more-types");
const snapshot = require("./snapshot");
module.exports = () => {
lazy(is.fn(global.before), "Missing global before function");
lazy(is.fn(global.after), "Missing global after function");
lazy(is.object(global.Cypress), "Missing Cypress object");
Cypress.Commands.add("snapshot", { prevSubject: "optional" }, snapshot);
return snapshot;
};

View file

@ -1,97 +1,112 @@
const serializeDomElement = require("../serializers/serializeDomElement");
const serializeToHTML = require("../serializers/serializeToHTML");
const compareValues = require("./compareValues");
const path = require("path");
const identity = (x) => x;
const pickSerializer = (asJson, value) => {
if (Cypress.dom.isJquery(value)) {
return asJson ? serializeDomElement : serializeToHTML;
}
return identity;
};
const store_snapshot = (props = { value, name, raiser }) => {
if (!Cypress.env().SNAPSHOT_UPDATE) {
cy.fixture(props.name).then(content => props.raiser({ value: props.value, expected: content }))
} else {
cy.writeFile(`${props.name}.json`, JSON.stringify(props.value.null, 2))
}
// cy.fixture(props.name)
// .then(exist => {
// cy.log('fixture 2')
// if (exist && !Cypress.env().SNAPSHOT_UPDATE) {
// cy.log(`fixture exists and doesn't update`)
// props.raiser({ value: props.value, expected: exist, type: "fixture" });
// } else {
// cy.log(`fixture exists and updates`)
// cy.writeFile(expectedPath, JSON.stringify(props.value, null, 2));
// }
// })
};
const set_snapshot = ({ snapshotName, serialized, value }) => {
let devToolsLog = { $el: serialized };
if (Cypress.dom.isJquery(value)) {
devToolsLog.$el = value;
}
const options = {
name: "snapshot",
message: snapshotName,
consoleProps: () => devToolsLog,
};
if (value) options.$el = value;
const raiser = ({ value, expected }) => {
const result = compareValues({ expected, value });
if (!Cypress.env().SNAPSHOT_UPDATE && !result.success) {
devToolsLog = {
...devToolsLog,
message: result,
expected,
value,
};
throw new Error(
`Snapshot Difference found.\nPlease Update the Snapshot\n
${JSON.stringify(result.result.replaceAll(/[╺┿╳]/g, ""), null, 2)}`
);
}
};
Cypress.log(options);
store_snapshot({
value,
name: snapshotName,
raiser,
});
};
const get_snapshot_name = (asFolder, stepName) => {
const names = Cypress.currentTest.titlePath;
const sep = ">>datashard.work<<"
if (stepName) names.push(stepName)
if (asFolder) return names.join(sep).replace(/ /gi, "-").replace(/\//gi, "-").replaceAll(sep, '/')
else return names.join('__').replaceAll(" ", "-").replaceAll("/", "-")
};
module.exports = (value, stepName, options = { json: true, asFolder: false }) => {
if (typeof value !== "object" || Array.isArray(value))
value = { data: value };
const serializer = pickSerializer(options.json, value);
const serialized = serializer(value);
set_snapshot({
snapshotName: path.join(
options.snapshotPath || Cypress.config('snapshot').snapshotPath || 'snapshots',
`/${get_snapshot_name(options.asFolder, stepName)}`),
serialized,
value,
});
};
const serializeDomElement = require("./utils/serializers/serializeDomElement");
const serializeToHTML = require("./utils/serializers/serializeToHTML");
const compareValues = require("./utils/compareValues");
const path = require("path");
const identity = (x) => x;
const pickSerializer = (asJson, value) => {
if (Cypress.dom.isJquery(value)) {
return asJson ? serializeDomElement : serializeToHTML;
}
return identity;
};
const store_snapshot = (props = { value, name, raiser }) => {
if (Cypress.env().SNAPSHOT_UPDATE || Cypress.config('snapshot').SNAPSHOT_UPDATE) {
cy.log(props.name)
console.log(props.name)
cy.writeFile(`${props.name}.json`, JSON.stringify(props.value, null, 2))
} else {
// TODO: Figure out how to replace the fixture folder name if people move it
const fixtureName = props.name.replace("cypress/fixtures", "")
cy.fixture(fixtureName).then(content => props.raiser({ value: props.value, expected: content }))
}
};
const set_snapshot = ({ snapshotName, serialized, value }) => {
let devToolsLog = { $el: serialized };
if (Cypress.dom.isJquery(value)) {
devToolsLog.$el = value;
}
const options = {
name: "snapshot",
message: snapshotName,
consoleProps: () => devToolsLog,
};
if (value) options.$el = value;
const raiser = ({ value, expected }) => {
const result = compareValues({ expected, value });
if (!Cypress.env().SNAPSHOT_UPDATE && !result.success) {
devToolsLog = {
...devToolsLog,
message: result,
expected,
value,
};
throw new Error(
`Snapshot Difference found.\nPlease Update the Snapshot\n
${JSON.stringify(result.result.replaceAll(/[╺┿╳]/g, ""), null, 2)}`
);
}
};
Cypress.log(options);
store_snapshot({
value,
name: snapshotName,
raiser,
});
};
function replaceCharacters(str, asFolder, sep) {
if (asFolder) {
if (!sep) throw new Error("Separator not Passed.")
return str
.replace(/ /gi, '-')
.replace(/\//gi, "-")
.replaceAll('"', '')
.replaceAll(sep, '/')
} else {
return str
.replaceAll(' ', '-')
.replaceAll('/', '-')
.replaceAll('"', '')
}
}
const get_snapshot_name = (asFolder, stepName) => {
const names = Cypress.currentTest.titlePath;
const sep = ">>datashard.work<<"
if (stepName && typeof stepName !== 'object') {
names.push(stepName)
}
if (asFolder) return replaceCharacters(names.join(sep), true, sep)
else return replaceCharacters(names.join('__'), false)
};
module.exports = (value, stepName, options = { json: true }) => {
if (typeof stepName === 'object') options = { ...options, ...stepName }
if (typeof value !== "object" || Array.isArray(value))
value = { data: value };
const serializer = pickSerializer(options.json, value);
const serialized = serializer(value);
options.asFolder = Cypress.config('snapshot').useFolders || false
set_snapshot({
snapshotName: path.join(
options.snapshotPath || Cypress.config('snapshot').snapshotPath || 'cypress/fixtures/snapshots',
`/${get_snapshot_name(options.asFolder, stepName)}`),
serialized,
value,
});
};

View file

@ -1,115 +1,115 @@
const isNestedData = (expected, value) => {
return (
expected && value && typeof expected == `object` && typeof value == `object`
);
};
const checkDataState = (expected, value) => {
let result;
if (expected === value) {
result = `| ✅ "${value}",`;
} else if (expected == undefined) {
result = `| "➖╺ ${JSON.stringify(expected)?.replaceAll('"', "'")}|${value?.replaceAll('"', "'")}",`;
} else if (value == undefined) {
result = `| "➕┿ ${JSON.stringify(expected)?.replaceAll('"', "'")}|${value?.replaceAll('"', "'")}",`;
} else {
result = `| ⭕ "⭕╳ ${JSON.stringify(expected)?.replaceAll('"', "'")}|${value?.replaceAll('"', "'")}",`;
}
return result;
};
/**
*
* @param {string} text
* @returns {string}
*/
function parseTextToJSON(text) {
const lines =
// JSON.stringify(
text
.replace(/\| [✅➖➕⭕]/g, "").trim()
.replace(/(.*?),\s*(\}|])/g, "$1$2")
// )
return lines;
// return JSON.stringify(lines, null, 2);
}
function containsDiffChars(str) {
const emojis = ["╺", "┿", ""];
return emojis.some(emoji => str.includes(emoji));
}
const compare = (expected, value) => {
if(value === undefined){
throw new Error("Please provide Data to compare against.")
}
let compareResult = "";
if (isNestedData(expected, value)) {
if (Array.isArray(expected)) {
compareResult += `[`;
let dataX, dataY;
if (expected.length >= value.length) {
dataX = expected;
dataY = value;
} else {
dataX = value;
dataY = expected;
}
dataX.forEach(function (item, index) {
const resultset = compare(item, dataY[index]);
compareResult += resultset.result;
});
compareResult += `],`;
} else {
let dataX, dataY;
compareResult += `{`;
if (Object.keys(expected).length >= Object.keys(value).length) {
dataX = expected;
dataY = value;
} else {
dataX = value;
dataY = expected;
}
Object.keys(dataX).forEach((key) => {
const resultset = compare(dataX[key], dataY[key]);
compareResult += `"${key}": ${resultset.result}`;
});
compareResult += `},`;
}
} else {
compareResult = checkDataState(expected, value);
}
let result = parseTextToJSON(compareResult).replace(/(},)$/g, `}`);
console.log("compareResult",compareResult)
console.log("result", result.replace(/(},)$/g, `}`))
// let result = compareResult;
try {
return {
success: !containsDiffChars(result),
result,
};
} catch (error) {
return { success: false, result };
}
};
/**
*
* @param {{
* expected: { [k:string]: any},
* value: {[k:string]:any}
* }} values
*/
module.exports = function compareValues(values) {
return compare(values.expected, values.value);
};
const isNestedData = (expected, value) => {
return (
expected && value && typeof expected == `object` && typeof value == `object`
);
};
const checkDataState = (expected, value) => {
let result;
if (expected === value) {
result = `| ✅ "${value}",`;
} else if (expected == undefined) {
result = `| "➖╺ ${JSON.stringify(expected)?.replaceAll('"', "'")}|${value?.replaceAll('"', "'")}",`;
} else if (value == undefined) {
result = `| "➕┿ ${JSON.stringify(expected)?.replaceAll('"', "'")}|${value?.replaceAll('"', "'")}",`;
} else {
result = `| ⭕ "⭕╳ ${JSON.stringify(expected)?.replaceAll('"', "'")}|${value?.replaceAll('"', "'")}",`;
}
return result;
};
/**
*
* @param {string} text
* @returns {string}
*/
function parseTextToJSON(text) {
const lines =
// JSON.stringify(
text
.replace(/\| [✅➖➕⭕]/g, "").trim()
.replace(/(.*?),\s*(\}|])/g, "$1$2")
// )
return lines;
// return JSON.stringify(lines, null, 2);
}
function containsDiffChars(str) {
const emojis = ["╺", "┿", ""];
return emojis.some(emoji => str.includes(emoji));
}
const compare = (expected, value) => {
if(value === undefined){
throw new Error("Please provide Data to compare against.")
}
let compareResult = "";
if (isNestedData(expected, value)) {
if (Array.isArray(expected)) {
compareResult += `[`;
let dataX, dataY;
if (expected.length >= value.length) {
dataX = expected;
dataY = value;
} else {
dataX = value;
dataY = expected;
}
dataX.forEach(function (item, index) {
const resultset = compare(item, dataY[index]);
compareResult += resultset.result;
});
compareResult += `],`;
} else {
let dataX, dataY;
compareResult += `{`;
if (Object.keys(expected).length >= Object.keys(value).length) {
dataX = expected;
dataY = value;
} else {
dataX = value;
dataY = expected;
}
Object.keys(dataX).forEach((key) => {
const resultset = compare(dataX[key], dataY[key]);
compareResult += `"${key}": ${resultset.result}`;
});
compareResult += `},`;
}
} else {
compareResult = checkDataState(expected, value);
}
let result = parseTextToJSON(compareResult).replace(/(},)$/g, `}`);
console.log("compareResult",compareResult)
console.log("result", result.replace(/(},)$/g, `}`))
// let result = compareResult;
try {
return {
success: !containsDiffChars(result),
result,
};
} catch (error) {
return { success: false, result };
}
};
/**
*
* @param {{
* expected: { [k:string]: any},
* value: {[k:string]:any}
* }} values
*/
module.exports = function compareValues(values) {
return compare(values.expected, values.value);
};

View file

@ -1,5 +0,0 @@
const readFileMaybe = require("../tasks/readFileMaybe");
module.exports = (on, config) => {
on("task", { readFileMaybe });
};

View file

@ -1,28 +0,0 @@
const serializeToHTML = require("./serializers/serializeToHTML");
const serializeDomElement = require("./serializers/serializeDomElement");
const compareValues = require("./snapshots/compareValues");
const readFileMaybe = require("./tasks/readFileMaybe");
const identity = (x) => x;
const publicProps = (name) => !name.startsWith("__");
const countSnapshots = (snapshots) =>
Object.keys(snapshots).filter(publicProps).length;
module.exports = {
serializers: {
serializeDomElement,
serializeToHTML,
identity,
countSnapshots,
},
snapshots: {
compareValues,
},
functions: {
register: require("./functions/register"),
tasks: require("./functions/addTasks"),
},
tasks: {
readFileMaybe,
},
};

View file

@ -1,9 +0,0 @@
const fs = require("fs");
module.exports = (filename) => {
if (fs.existsSync(filename)) {
return fs.readFileSync(filename, "utf8");
}
return false;
};