1
0
Fork 0
mirror of https://github.com/datashard/snapshot.git synced 2025-06-03 19:37:22 +00:00

Compare commits

..

No commits in common. "master" and "v2.1.8" have entirely different histories.

44 changed files with 19987 additions and 649 deletions

12
.eslintrc Normal file
View file

@ -0,0 +1,12 @@
{
"extends": [
"plugin:cypress-dev/general"
],
"rules": {
"comma-dangle": "off",
"no-debugger": "warn"
},
"env": {
"node": true
}
}

Binary file not shown.

Before

(image error) Size: 9 KiB

Binary file not shown.

Before

(image error) Size: 14 KiB

Binary file not shown.

Before

(image error) Size: 76 KiB

View file

@ -1,12 +0,0 @@
name: Cypress
on: [push, pull_request, workflow_call, workflow_dispatch]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install Dependencies
run: npm i
- name: Test
run: npm run cypress:run

2
.gitignore vendored
View file

@ -2,5 +2,3 @@ node_modules/
.DS_Store
npm-debug.log
cypress/videos/
cypress/screenshots/
cypress/snapshots/Arrays.json

View file

@ -1,5 +0,0 @@
cypress/
cypress.config.js
.github/workflows/
.vscode/
renovate.json

2
.npmrc
View file

@ -1,4 +1,4 @@
registry=https://registry.npmjs.org/
registry=http://registry.npmjs.org/
save-exact=true
progress=false
package-lock=true

22
LICENSE
View file

@ -1,22 +0,0 @@
Copyright (c) 2023-2024 Joshua data@shard.wtf
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

177
README.md
View file

@ -1,56 +1,55 @@
# @datashard/snapshot
> Adds JSON Snapshot comparison to Cypress
> Adds value / object / DOM element snapshot testing support to Cypress test runner
## ⚠️ Breaking Changes ⚠️
<details>
<summary>Changes between <code>@datashard/snapshot</code> and <code>@cypress/snapshot</code></summary>
<br>
They're mostly the same, as this is a fork of the Latter, though it's not a drop-in replacement.
- With V3, the `readFileMaybe` task has been removed, we now rely on `cy.fixture` internally.
- the previous `SNAPSHOT_UPDATE` Environment/Config Variable has been changed to `updateSnapshots`
Unlike `@cypress/snapshot`, this saves snapshots in their own files with a sensible default and strives to have ongoing Support for future Cypress Versions
> [!DANGER]
This means that previous tests will likely be broken, *please make sure that your tests pass before updating to the latest version of this Plugin*.
</details>
This current release will be released as `3.0.0-beta`, should Bugs be found by me or my Employer, I will open Issues/PRs to fix those, should anyone else find Bugs/Edgecases, etc. please open an Issue.
<!-- [![NPM][npm-icon] ][npm-url] -->
## Install
Requires Node 16 or above
Requires [Node](https://nodejs.org/en/) version 10 or above.
```sh
npm i --save-dev @datashard/snapshot
npm install --save-dev @datashard/snapshot
```
## Import
After Installing, you'll need to add the following import into your Commands/Support File
> by default this will be `cypress/support/e2e.js`
After installing, add the following to your `cypress/support/commands.js` file
```js
require('@datashard/snapshot').regsiter()
require("@datashard/snapshot").register();
```
This will register a new Command `.snapshot()`, to create and compare JSON Snapshots.
This registers a new command to create new snapshot or compare value to old snapshot
## Config
You can pass `updateSnapshots` and `useFolders` as options in the `cypress.config.js` file
![Example Settings for the Module](./.github/assets/config.png)
Alternatively, you can also add `snapshotUpdate` as an Environment Variable to update your snapshots.
Simply pass `--env updateSnapshots=true` when running Cypress.
## Usage
If properly added, usage of this plugin is rather simple, just add `.snapshot()` to cypress functions that return valid JSON. (i.e. `cy.wrap`)
When properly added, you can chain `.snapshot()` off of `cy` functions like `cy.wrap`, just make sure they return valid JSON.
### Example
and add the following to your `cypress.config.js`
```js
describe("my test", () => {
e2e: {
setupNodeEvents(on, config) {
require("@datashard/snapshot").tasks(on, config)
},
```
> **Note** \
> \
> `@datashard/snapshot` **requires** the `readFileMaybe` plugin to be included, which can be easily done using the code above
# Usage
Currently, if you want to take more than one snapshot, you need to pass a Step Name to prevent overwrites / test failures
```js
describe("my tests", () => {
it("works", () => {
cy.log("first snapshot");
cy.wrap({ foo: 42 }).snapshot("foo");
@ -60,33 +59,107 @@ describe("my test", () => {
});
```
This Plugin will then save your snapshots as
```ts
// useFolders: false
cypress/fixtures/my-test__works__foo.json
cypress/fixtures/my-test__works__bar.json
// useFolders: true
cypress/fixtures/my-test/works/foo.json
cypress/fixtures/my-test/works/bar.json
// {fixtureFolder}/<Context>-<Describe>-<It>-<Name?>.json
// {fixtureFolder}/<Context>/<Describe>/<It>/<Name?>.json
In the above case, you can find the stored snapshot in their own files, mentioned above them
```json
// cypress/snapshots/my-tests-works-foo.json
{ "foo": 42 }
// cypress/snapshots/my-tests-works-bar.json
{ "bar": 101 }
```
Snapshots will generally be saved using this the Convention mentioned in the Comment of the above Codeblock, which is provided by the named Cypress Test Steps.
If you change the site values, the saved snapshot will no longer match, throwing an error
Passing a name to the Snapshot function is required, but not checked, if you want to take multiple snapshots in the same block.
(picture taken from `cypress/snapshots/Arrays.json`)
![Snapshot mismatch](.github/assets/updated-mismatch.png)
If you have two or more Snapshots in the same Block, the next one ***WILL*** always overwrite the previous one while updating, causing the First Snapshot in the Block to Fail.
While running your Tests, if a value changed, it will, of course, no longer match the snapshot and throw an Error.
Click on the `SNAPSHOT` step in the Command Log to see expected and current value printed in the DevTools.
Which will look like this:
### Options
![](./.github/assets/Error.png)
You can control snapshot comparison and behavior through a few options.
When the Test succeeds, it will instead log a Success in the Log and let you know where the File has been saved to, relative to the Fixture Snapshot Folder
```js
cy.get(...).snapshot({
snapshotName: 'Snapshot Name', // to use as a File Name
snapshotPath: 'cypress/not_snapshots', // where to save the Snapshot
json: false // convert DOM elements into JSON
}) // when storing in the snapshot file
![](./.github/assets/Correct.png)
// will save as
// cypress/not_snapshots/Snapshot-Name.json
```
You can also pass a "Step Name" to the Function
```js
cy.get(...).snapshot("Intercepted API Request")
// will save as
// cypress/snapshots/<context>-<describe>-<it>-Intercepted-API-Request.json
// to prevent duplications
```
or both
```js
cy.get(...).snapshot("Intercepted API Request", {
snapshotPath: "cypress/snapshots/api",
snapshotName: "first_intercept"
})
// will save as
// cypress/snapshots/api/first_intercept.json
```
### Configuration
This module provides some configuration options:
#### snapshotPath
Sets the default Path for saving Snapshots (default: `cypress/snapshots`)
#
### Small print
Authors:
- Joshua &lt;[data@shard.wtf](mailto:data@shard.wtf)&gt;
- Gleb Bahmutov &lt;gleb@cypress.io&gt;
<br>
License: MIT - do anything with the code, but don't blame us if it does not work.
Support: If you find any problems with this module [open an issue](https://github.com/cypress-io/snapshot/issues) on Github
## MIT License
Copyright (c) 2017-2022 Cypress.io &lt;hello@cypress.io&gt; & Joshua &lt;data@shard.wtf&gt;
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
[npm-icon]: https://nodei.co/npm/@datashard/snapshot.svg?downloads=true
[npm-url]: https://npmjs.org/package/@datashard/snapshot
[semantic-url]: https://github.com/semantic-release/semantic-release
[renovate-badge]: https://img.shields.io/badge/renovate-app-blue.svg
[renovate-app]: https://renovateapp.com/

View file

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

View file

@ -1,78 +0,0 @@
/* eslint-env mocha */
/* global cy */
describe("datashard/snapshot", () => {
context("simple types"
// , { env: { updateSnapshots: 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: {
updateSnapshots: true,
},
},
() => {
cy.wrap([1, 2, 3, 4]).snapshot({
snapshotPath: "cypress/fixtures/snapshots",
snapshotName: "Arrays",
});
}
);
});
context("complex types"
// , { env: { SNAPSHOT_UPDATE: true } }
, () => {
it('works with more "complicated" Objects', () => {
cy.wrap({
"status": 200,
"response": {
"array": [0, 1, 2, "4"],
"object": {
"with": "more details"
}
},
"thisisnew": "wtf"
}).snapshot()
})
it("works based on fixtures", () => {
cy
.wrap({
"jsonapi": {
"version": "2.0"
},
"included": [
{
"type": "users",
"id": "2",
"attributes": {
"name": "Test"
}
}
]
})
.snapshot();
});
})
});

View file

@ -3,21 +3,25 @@
describe("Random Describe", () => {
context("Random Context", () => {
it("Random It", () => {
cy.wrap(42).snapshot("Numbers");
cy.wrap("foo-bar").snapshot("Strings");
cy.wrap([1, 2, 3]).snapshot("Arrays");
cy.fixture("File").snapshot("Fixture File", {
humanName: "Random Fixture File"
});
// cy.fixture("File2").snapshot("Fixture File",
});
// it("works with numbers", () => {
// console.log(cy.wrap(42))
// cy.wrap(42).snapshot();
// });
// it("works with strings", () => {
// console.log(cy.wrap("foo-bar"))
// cy.wrap("foo-bar").snapshot();
// });
// it("works with arrays", () => {
// console.log(cy.wrap([1, 2, 3]))
// cy.wrap([1, 2, 3]).snapshot();
// });
});
});

33
cypress/e2e/spec.cy.js Normal file
View file

@ -0,0 +1,33 @@
/* eslint-env mocha */
/* global cy */
describe("@cypress/snapshot", () => {
context("simple types", () => {
it("works with objects", () => {
cy.fixture("File2").snapshot({
snapshotPath: "cypress/snapshots",
snapshotName: "Objects",
});
});
it("works with numbers", () => {
cy.wrap(42).snapshot({
snapshotPath: "cypress/snapshots",
snapshotName: "Numbers",
});
});
it("works with strings", () => {
cy.wrap("foo-bar").snapshot({
snapshotPath: "cypress/snapshots",
snapshotName: "Strings",
});
});
it("works with arrays", () => {
cy.wrap([1, 2, 3]).snapshot({
snapshotPath: "cypress/snapshots",
snapshotName: "Arrays",
});
});
});
});

View file

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

View file

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

View file

@ -1,7 +0,0 @@
{
"data": [
1,
2,
3
]
}

View file

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

View file

@ -1,15 +0,0 @@
{
"status": 200,
"response": {
"array": [
0,
1,
2,
"4"
],
"object": {
"with": "more details"
}
},
"thisisnew": "wtf"
}

View file

@ -1,8 +0,0 @@
{
"data": [
1,
2,
3,
4
]
}

View file

@ -0,0 +1 @@
{"data":[1,2,3]}

View file

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

View file

@ -0,0 +1 @@
{"data":42}

View file

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

View file

@ -0,0 +1 @@
{"data":"foo-bar"}

View file

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

19617
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,8 +1,8 @@
{
"name": "@datashard/snapshot",
"description": "Adds JSON Snapshot testing support to Cypress",
"version": "3.0.0-beta.1",
"author": "Joshua <data@shard.wtf>",
"description": "Adds value / object / DOM element snapshot testing support to Cypress test runner",
"version": "2.1.8",
"author": "Joshua <data@shard.wtf>, Gleb Bahmutov <gleb@cypress.io>",
"bugs": "https://github.com/datashard/snapshot/issues",
"engines": {
"node": ">=6"
@ -13,13 +13,13 @@
"src/*/**",
"!src/*-spec.js"
],
"homepage": "https://shard.wtf/snapshot",
"homepage": "https://github.com/datashard/snapshot#readme",
"keywords": [
"cypress",
"cypress-io",
"plugin",
"snapshot",
"testing", "json"
"testing"
],
"license": "MIT",
"main": "src/index.js",
@ -29,22 +29,39 @@
"url": "https://github.com/datashard/snapshot.git"
},
"scripts": {
"ban": "ban",
"deps": "deps-ok && dependency-check --no-dev .",
"issues": "git-issues",
"license": "license-checker --production --onlyunknown --csv",
"lint": "eslint --fix src/*.js",
"pretest": "npm run lint",
"size": "t=\"$(npm pack .)\"; wc -c \"${t}\"; tar tvf \"${t}\"; rm \"${t}\";",
"unused-deps": "dependency-check --unused --no-dev . --entry src/index.js",
"test": "npm run unit",
"unit": "mocha src/*-spec.js",
"unused-deps": "dependency-check --unused --no-dev . --entry src/add-initial-snapshot-file.js",
"semantic-release": "semantic-release",
"cypress:open": "cypress open",
"cypress:update": "cypress run --env updateSnapshots=true",
"cypress:run": "cypress run"
},
"devDependencies": {
"cypress": "12.13.0",
"ban-sensitive-files": "1.9.15",
"cypress": "10.6.0",
"debug": "3.2.7",
"dependency-check": "2.10.1"
"dependency-check": "2.10.1",
"deps-ok": "1.4.1",
"eslint": "4.19.1",
"eslint-plugin-cypress-dev": "1.1.2",
"git-issues": "1.3.1",
"license-checker": "15.0.0",
"mocha": "6.2.3",
"semantic-release": "17.4.3"
},
"dependencies": {
"@wildpeaks/snapshot-dom": "1.6.0",
"check-more-types": "2.24.0",
"js-beautify": "1.13.13",
"lazy-ass": "1.6.0"
"lazy-ass": "1.6.0",
"snap-shot-compare": "3.0.0",
"snap-shot-store": "1.2.3"
}
}

View file

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

View file

@ -1,119 +0,0 @@
const lazy = require("lazy-ass");
const is = require("check-more-types");
const snapshot = require("./snapshot");
const baseStyles = [
{
name: 'info',
color: '#cbd5e1',
},
{
name: 'success',
color: '#10b981',
},
{
name: 'warning',
color: '#fbbf24',
},
{
name: 'error',
color: '#dc2626',
},
]
/**
* Helper function to convert hex colors to rgb
* @param {string} hex - hex color
* @returns {string}
*
* @example
* // returns "255 255 255"
* hex2rgb("#ffffff")
*/
function hex2rgb(hex) {
const r = parseInt(hex.slice(1, 3), 16)
const g = parseInt(hex.slice(3, 5), 16)
const b = parseInt(hex.slice(5, 7), 16)
return `${r} ${g} ${b}`
}
baseStyles.forEach((style) => {
createCustomLog(style.name, style.color)
})
/**
* Create a custom log
* @param {string} name - Name of the custom log
* @param {string} baseColor - Base color of the custom log in hex format
*
* @example
* // Create a custom log with name "misc" and base color "#9333ea"
* createCustomLog("misc", "#9333ea")
*/
function createCustomLog(name, baseColor) {
if (!name || !baseColor) {
throw new Error('Missing parameters')
}
const logStyle = document.createElement('style')
logStyle.textContent = `
.command.command-name-log-${name} span.command-method {
margin-right: 0.5rem;
min-width: 10px;
border-radius: 0.125rem;
border-width: 1px;
padding-left: 0.375rem;
padding-right: 0.375rem;
padding-top: 0.125rem;
padding-bottom: 0.125rem;
text-transform: uppercase;
border-color: rgb(${hex2rgb(baseColor)} / 1);
background-color: rgb(${hex2rgb(baseColor)} / 0.2);
color: rgb(${hex2rgb(baseColor)} / 1) !important;
}
.command.command-name-log-${name} span.command-message{
color: rgb(${hex2rgb(baseColor)} / 1);
font-weight: normal;
}
.command.command-name-log-${name} span.command-message strong,
.command.command-name-log-${name} span.command-message em {
color: rgb(${hex2rgb(baseColor)} / 1);
}
`
Cypress.$(window.top.document.head).append(logStyle)
}
/**
* Print a message with a formatted style
* @param {Object} log - The message to be printed.
* @param {string} log.title - The title of the message.
* @param {string} log.message - The content of the message.
* @param {('info' | 'warning' | 'error' | 'success')} log.type - The type of the message.
*
* @example
* // Print a message with a formatted style e.g. success
* cy.print({ title: 'foo', message: 'bar', type: 'success' })
*/
function cyPrint({ title, message, type }) {
Cypress.log({
name: `log-${type}`,
displayName: `${title}`,
message,
})
}
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);
Cypress.Commands.add('SNAPSHOT_prettyprint', cyPrint)
};

16
src/snapshot-spec.js Normal file
View file

@ -0,0 +1,16 @@
'use strict'
/* eslint-env mocha */
const api = require('.')
const la = require('lazy-ass')
const is = require('check-more-types')
describe('@datashard/snapshot', () => {
it('is an object', () => {
la(is.object(api))
})
it('has register', () => {
la(is.fn(api.register))
})
})

View file

@ -1,124 +0,0 @@
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;
};
/**
*
* @param {string} text
* @returns {string}
*/
const parseTextToJSON = (text) => text.replace(/\| [✅➖➕⭕]/g, "").trim().replace(/(.*?),\s*(\}|])/g, "$1$2").replace(/},(?!")$/g, "}").replaceAll(/[╺┿╳]/g, "")
const store_snapshot = ({ value, name, raiser } = { value, name, raiser }) => {
if (Cypress.env().updateSnapshots || Cypress.config('snapshot').updateSnapshots) {
cy.SNAPSHOT_prettyprint({ title: "INFO", type: "info", message: "Saving Snapshot" })
cy.writeFile(path.join(Cypress.config().fixturesFolder, `${name}.json`), JSON.stringify(value, null, 2))
} else {
cy.fixture(name).then(expected => raiser({ value, expected }))
}
};
const set_snapshot = ({ snapshotName, serialized, value }) => {
let devToolsLog = { $el: serialized };
if (Cypress.dom.isJquery(value)) {
devToolsLog.$el = value;
}
let options = {
name: "snapshot",
message: snapshotName,
consoleProps: () => { return devToolsLog },
...(value && { $el: value })
};
const raiser = ({ value, expected }) => {
const result = compareValues({ expected, value });
if ((!Cypress.env().updateSnapshots || !Cypress.config('snapshot').updateSnapshots) && !result.success) {
devToolsLog = () => {
return { expected, value }
};
const error = (inError) => `
Snapshot Difference found.\nPlease Update the Snapshot ${inError ? `\n${JSON.stringify(JSON.parse(parseTextToJSON(result.result)), null, 3).replaceAll(' ', "&nbsp;")}` : ""}`
Cypress.log({ message: error(true) })
throw new Error(error());
} else {
cy.SNAPSHOT_prettyprint({
title: "SUCCESS",
message: snapshotName,
type: "success"
})
}
};
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);
let useFolders;
if(Cypress.config('snapshot').useSnapshotFolder === undefined || Cypress.config('snapshot').useSnapshotFolder === true) {
useFolders = true
} else {
useFolders = false
}
options.asFolder = Cypress.config('snapshot').useFolders || false
set_snapshot({
snapshotName: `/${useFolders ? "snapshots/" : ""}${get_snapshot_name(options.asFolder, stepName)}`,
serialized,
value,
});
};

View file

@ -1,79 +0,0 @@
const containsDiffChars = str => ["╺", "┿", ""].some(emoji => str.includes(emoji));
const isNestedData = (expected, value) => expected && value && typeof expected == 'object' && typeof value == 'object';
const checkDataState = (expected, value) => {
let result;
if (expected === value) {
result = `| ✅ "${value}",`;
} else {
result = `| ⭕ "⭕╳ ${JSON.stringify(expected)?.replaceAll('"', "'")} | ${value?.replaceAll('"', "'")}",`;
}
return result;
};
const compare = (expected, value) => {
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);
}
try {
return {
success: !containsDiffChars(compareResult),
result: compareResult,
};
} catch (error) {
return { success: false, result: compareResult };
}
};
/**
*
* @param {{
* expected: { [k:string]: any},
* value: {[k:string]:any}
* }} values
*/
module.exports = function compareValues(values) {
return compare(values.expected, values.value);
};

View file

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

View file

@ -0,0 +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: true }, snapshot);
return snapshot;
};

28
src/utils/index.js Normal file
View file

@ -0,0 +1,28 @@
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,6 +1,7 @@
const stripTransientIdAttributes = require("./stripTransientIdAttributes");
const beautify = require("js-beautify").html;
module.exports = (el$) => {
const html = el$[0].outerHTML;
const stripped = stripTransientIdAttributes(html);

View file

@ -0,0 +1,6 @@
const compare = require("snap-shot-compare");
module.exports = function compareValues({ expected, value }) {
const noColor = false;
const json = true;
return compare({ expected, value, noColor, json });
};

View file

@ -0,0 +1,130 @@
const serializeDomElement = require("../serializers/serializeDomElement");
const serializeToHTML = require("../serializers/serializeToHTML");
const compareValues = require("./compareValues");
const { initStore } = require("snap-shot-store");
const path = require("path");
const identity = (x) => x;
const pickSerializer = (asJson, value) => {
if (Cypress.dom.isJquery(value)) {
return asJson ? serializeDomElement : serializeToHTML;
}
return identity;
};
let counters = {};
const newStore = (name) => {
return initStore(name);
};
const get_snapshot_key = (key) => {
if (key in counters) {
// eslint-disable-next-line immutable/no-mutation
counters[key] += 1;
} else {
// eslint-disable-next-line immutable/no-mutation
counters[key] = 1;
}
return counters[key];
};
const store_snapshot = (store, props = { value, name, path, raiser }) => {
const fileName = props.name
.join("_")
.replace(/ /gi, "-")
.replace(/\//gi, "-");
const snapshotPath =
props.path ||
Cypress.config("snapshot").snapshotPath ||
"cypress/snapshots";
const expectedPath = path.join(snapshotPath, `${fileName}.json`);
cy.task("readFileMaybe", expectedPath).then((exist) => {
if (exist) {
props.raiser({ value: props.value, expected: JSON.parse(exist) });
} else {
cy.writeFile(expectedPath, JSON.stringify(props.value));
}
});
};
const set_snapshot = (
store,
{ snapshotName, snapshotPath, serialized, value }
) => {
if (!store) return;
const message = Cypress._.last(snapshotName);
console.log("Current Snapshot name", snapshotName);
const devToolsLog = { $el: serialized };
if (Cypress.dom.isJquery(value)) {
devToolsLog.$el = value;
}
const options = {
name: "snapshot",
message,
consoleProps: () => devToolsLog,
};
if (value) options.$el = value;
const raiser = ({ value, expected }) => {
const result = compareValues({ expected, value });
result.orElse((json) => {
devToolsLog.message = json.message;
devToolsLog.expected = expected;
delete devToolsLog.value;
devToolsLog.value = value;
throw new Error(
`Snapshot Difference. To update, delete snapshot file and rerun test.\n${json.message}`
);
});
};
Cypress.log(options);
store_snapshot(store, {
value,
name: snapshotName,
path: snapshotPath,
raiser,
});
};
const get_test_name = (test) => test.titlePath;
const get_snapshot_name = (test, custom_name) => {
const names = get_test_name(test);
const index = custom_name;
names.push(String(index));
if (custom_name) return [custom_name];
return names;
};
module.exports = (value, step, options) => {
if (typeof step === "object") options = step;
if (typeof value !== "object" || Array.isArray(value))
value = { data: value };
console.log("value", value);
const name = get_snapshot_name(
Cypress.currentTest,
options.snapshotName || step
);
const serializer = pickSerializer(options.json, value);
const serialized = serializer(value);
const store = newStore(serialized || {});
console.log({ step, options });
set_snapshot(store, {
snapshotName: name,
snapshotPath: options.snapshotPath,
serialized,
value,
});
};

View file

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