chore: remove most code and work based on fixtures

This commit is contained in:
Joshua 2024-01-25 17:30:16 +01:00
parent e2ef9784e4
commit b61e5c0552
6 changed files with 120 additions and 105 deletions

View file

@ -62,9 +62,9 @@ describe("my tests", () => {
In the above case, you can find the stored snapshot in their own files, mentioned above them In the above case, you can find the stored snapshot in their own files, mentioned above them
```jsonc ```jsonc
// cypress/snapshots/my-tests-works-foo.json // cypress/fixtures/snapshots/my-tests-works-foo.json
{ "foo": 42 } { "foo": 42 }
// cypress/snapshots/my-tests-works-bar.json // cypress/fixtures/snapshots/my-tests-works-bar.json
{ "bar": 101 } { "bar": 101 }
``` ```
@ -82,7 +82,7 @@ You can control snapshot comparison and behavior through a few options.
```js ```js
cy.get(...).snapshot({ cy.get(...).snapshot({
snapshotName: 'Snapshot Name', // Overwrite the generated Snapshot name snapshotName: 'Snapshot Name', // Overwrite the generated Snapshot name
snapshotPath: 'cypress/not_snapshots', // Overwrite where the Snapshot should be stored snapshotPath: 'cypress/fixtures/not_snapshots', // Overwrite where the Snapshot should be stored
json: false // convert DOM elements into JSON json: false // convert DOM elements into JSON
}) // when storing in the snapshot file }) // when storing in the snapshot file

View file

@ -3,7 +3,8 @@ const { functions } = require("./src/utils");
module.exports = defineConfig({ module.exports = defineConfig({
snapshot: { snapshot: {
snapshotPath: "cypress/snapshots/", // snapshotPath: "cypress/snapshots/",
SNAPSHOT_UPDATE: true
}, },
e2e: { e2e: {
setupNodeEvents(on, config) { setupNodeEvents(on, config) {

View file

@ -3,45 +3,73 @@
describe("@datashard/snapshot", () => { describe("@datashard/snapshot", () => {
context("simple types", () => { context("simple types", () => {
it("works with objects", () => { it("works with objects", () => {
cy.fixture("File2").snapshot({ cy.wrap({
snapshotPath: "cypress/snapshots", "foo": "bar",
snapshotName: "Objects", "Fizzy Drink": "Pop"
}); }).snapshot(
// "Filename", {
// snapshotPath: "asdasd"
// }
);
// cypress/fixtures/@datashard-snapshot/simple-types/works-with-objects/asdjskadhasj.json
}); });
it("works with numbers", () => { // it("works with numbers", () => {
cy.wrap(42).snapshot({ // cy.wrap(42).snapshot({
snapshotPath: "cypress/snapshots", // snapshotPath: "cypress/fixtures/snapshots",
snapshotName: "Numbers", // snapshotName: "Numbers",
}); // });
}); // });
it("works with strings", () => { // it("works with strings", () => {
cy.wrap("foo-bar").snapshot({ // cy.wrap("foo-bar").snapshot({
snapshotPath: "cypress/snapshots", // snapshotPath: "cypress/fixtures/snapshots",
snapshotName: "Strings", // snapshotName: "Strings",
}); // });
}); // });
it( // it(
"works with arrays", // "works with arrays",
{ // {
env: { // env: {
SNAPSHOT_UPDATE: true, // SNAPSHOT_UPDATE: true,
}, // },
}, // },
() => { // () => {
cy.wrap([1, 2, 3, 4]).snapshot({ // cy.wrap([1, 2, 3, 4]).snapshot({
snapshotPath: "cypress/snapshots", // snapshotPath: "cypress/fixtures/snapshots",
snapshotName: "Arrays", // snapshotName: "Arrays",
}); // });
} // }
); // );
it('works with more "complicated" Objects', () => { // it('works with more "complicated" Objects', () => {
cy.fixture("Complex").snapshot({ // cy.fixture("Complex").snapshot({
snapshotPath: 'cypress/snapshots', // snapshotPath: 'cypress/fixtures/snapshots',
snapshotName: "Complex" // 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",
// });
// });
}); });
}); });

View file

@ -7,7 +7,7 @@ module.exports = () => {
lazy(is.fn(global.after), "Missing global after function"); lazy(is.fn(global.after), "Missing global after function");
lazy(is.object(global.Cypress), "Missing Cypress object"); lazy(is.object(global.Cypress), "Missing Cypress object");
Cypress.Commands.add("snapshot", { prevSubject: true }, snapshot); Cypress.Commands.add("snapshot", { prevSubject: "optional" }, snapshot);
return snapshot; return snapshot;
}; };

View file

@ -1,5 +1,3 @@
// const { expect: chaiExpect } = require("chai");
const isNestedData = (expected, value) => { const isNestedData = (expected, value) => {
return ( return (
expected && value && typeof expected == `object` && typeof value == `object` expected && value && typeof expected == `object` && typeof value == `object`
@ -12,11 +10,11 @@ const checkDataState = (expected, value) => {
if (expected === value) { if (expected === value) {
result = `| ✅ "${value}",`; result = `| ✅ "${value}",`;
} else if (expected == undefined) { } else if (expected == undefined) {
result = `| "➖╺ ${expected}|${value}",`; result = `| "➖╺ ${JSON.stringify(expected)?.replaceAll('"', "'")}|${value?.replaceAll('"', "'")}",`;
} else if (value == undefined) { } else if (value == undefined) {
result = `| "➕┿ ${expected}|${value}",`; result = `| "➕┿ ${JSON.stringify(expected)?.replaceAll('"', "'")}|${value?.replaceAll('"', "'")}",`;
} else { } else {
result = `| ⭕ "⭕╳ ${expected}|${value}",`; result = `| ⭕ "⭕╳ ${JSON.stringify(expected)?.replaceAll('"', "'")}|${value?.replaceAll('"', "'")}",`;
} }
return result; return result;
@ -31,9 +29,11 @@ const checkDataState = (expected, value) => {
function parseTextToJSON(text) { function parseTextToJSON(text) {
const lines = const lines =
text // JSON.stringify(
.replace(/\| [✅➖➕⭕]/g, "").trim() text
.replace(/(.*?),\s*(\}|])/g, "$1$2"); .replace(/\| [✅➖➕⭕]/g, "").trim()
.replace(/(.*?),\s*(\}|])/g, "$1$2")
// )
return lines; return lines;
// return JSON.stringify(lines, null, 2); // return JSON.stringify(lines, null, 2);
} }
@ -44,8 +44,10 @@ function containsDiffChars(str) {
} }
const compare = (expected, value) => { const compare = (expected, value) => {
if(value === undefined){
throw new Error("Please provide Data to compare against.")
}
let compareResult = ""; let compareResult = "";
let compareSuccess = true;
if (isNestedData(expected, value)) { if (isNestedData(expected, value)) {
if (Array.isArray(expected)) { if (Array.isArray(expected)) {
@ -62,7 +64,6 @@ const compare = (expected, value) => {
dataX.forEach(function (item, index) { dataX.forEach(function (item, index) {
const resultset = compare(item, dataY[index]); const resultset = compare(item, dataY[index]);
compareSuccess = resultset.success;
compareResult += resultset.result; compareResult += resultset.result;
}); });
compareResult += `],`; compareResult += `],`;
@ -79,17 +80,16 @@ const compare = (expected, value) => {
Object.keys(dataX).forEach((key) => { Object.keys(dataX).forEach((key) => {
const resultset = compare(dataX[key], dataY[key]); const resultset = compare(dataX[key], dataY[key]);
compareSuccess = resultset.success;
compareResult += `"${key}": ${resultset.result}`; compareResult += `"${key}": ${resultset.result}`;
}); });
compareResult += `}`; compareResult += `},`;
} }
} else { } else {
compareSuccess = false;
compareResult = checkDataState(expected, value); compareResult = checkDataState(expected, value);
} }
let result = parseTextToJSON(compareResult); let result = parseTextToJSON(compareResult).replace(/(},)$/g, `}`);
console.log("compareResult",compareResult)
console.log("result", result.replace(/(},)$/g, `}`))
// let result = compareResult; // let result = compareResult;
try { try {

View file

@ -11,34 +11,36 @@ const pickSerializer = (asJson, value) => {
return identity; return identity;
}; };
const store_snapshot = (props = { value, name, path, raiser }) => { const store_snapshot = (props = { value, name, raiser }) => {
const expectedPath = path.join( if (!Cypress.env().SNAPSHOT_UPDATE) {
props.path || cy.fixture(props.name).then(content => props.raiser({ value: props.value, expected: content }))
Cypress.config("snapshot").snapshotPath || } else {
"cypress/snapshots", cy.writeFile(`${props.name}.json`, JSON.stringify(props.value.null, 2))
`${props.name.join("_").replace(/ /gi, "-").replace(/\//gi, "-")}.json` }
);
cy.task("readFileMaybe", expectedPath).then((exist) => {
if (exist && !Cypress.env().SNAPSHOT_UPDATE) { // cy.fixture(props.name)
props.raiser({ value: props.value, expected: JSON.parse(exist) }); // .then(exist => {
} else { // cy.log('fixture 2')
cy.writeFile(expectedPath, JSON.stringify(props.value, null, 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 = ( const set_snapshot = ({ snapshotName, serialized, value }) => {
{ snapshotName, snapshotPath, serialized, value }
) => {
let devToolsLog = { $el: serialized }; let devToolsLog = { $el: serialized };
if (Cypress.dom.isJquery(value)) { if (Cypress.dom.isJquery(value)) {
devToolsLog.$el = value; devToolsLog.$el = value;
} }
const options = { const options = {
name: "snapshot", name: "snapshot",
message: Cypress._.last(snapshotName), message: snapshotName,
consoleProps: () => devToolsLog, consoleProps: () => devToolsLog,
}; };
@ -46,7 +48,6 @@ const set_snapshot = (
const raiser = ({ value, expected }) => { const raiser = ({ value, expected }) => {
const result = compareValues({ expected, value }); const result = compareValues({ expected, value });
if (!Cypress.env().SNAPSHOT_UPDATE && !result.success) { if (!Cypress.env().SNAPSHOT_UPDATE && !result.success) {
devToolsLog = { devToolsLog = {
...devToolsLog, ...devToolsLog,
@ -55,19 +56,11 @@ const set_snapshot = (
value, value,
}; };
// ╺
// ┿
//
throw new Error( throw new Error(
`Snapshot Difference found.\nPlease Update the Snapshot\n\n${JSON.stringify( `Snapshot Difference found.\nPlease Update the Snapshot\n
JSON.parse(result.result),
null,
2 ${JSON.stringify(result.result.replaceAll(/[╺┿╳]/g, ""), null, 2)}`
)
.replaceAll(" ", " ")
.replaceAll(/[╺┿╳]/g, "")}`
// `Snapshot Difference found.\nPlease Update the Snapshot\n\n${result.result}`
); );
} }
}; };
@ -76,35 +69,28 @@ const set_snapshot = (
store_snapshot({ store_snapshot({
value, value,
name: snapshotName, name: snapshotName,
path: snapshotPath,
raiser, raiser,
}); });
}; };
const get_snapshot_name = (test, custom_name) => { const get_snapshot_name = (asFolder, stepName) => {
const names = test.titlePath; const names = Cypress.currentTest.titlePath;
const sep = ">>datashard.work<<"
if (stepName) names.push(stepName)
const index = custom_name; if (asFolder) return names.join(sep).replace(/ /gi, "-").replace(/\//gi, "-").replaceAll(sep, '/')
names.push(String(index)); else return names.join('__').replaceAll(" ", "-").replaceAll("/", "-")
if (custom_name) return [custom_name];
return names;
}; };
module.exports = (value, step, options) => { module.exports = (value, stepName, options = { json: true, asFolder: false }) => {
if (typeof step === "object") options = step;
if (typeof value !== "object" || Array.isArray(value)) if (typeof value !== "object" || Array.isArray(value))
value = { data: value }; value = { data: value };
const serializer = pickSerializer(options.json, value); const serializer = pickSerializer(options.json, value);
const serialized = serializer(value); const serialized = serializer(value);
set_snapshot({ set_snapshot({
snapshotName: get_snapshot_name( snapshotName: path.join(
Cypress.currentTest, options.snapshotPath || Cypress.config('snapshot').snapshotPath || 'snapshots',
options.snapshotName || step `/${get_snapshot_name(options.asFolder, stepName)}`),
),
snapshotPath: options.snapshotPath,
serialized, serialized,
value, value,
}); });