Best JavaScript code snippet using cypress
snapshotCommand.js
Source:snapshotCommand.js
1const _ = require('lodash')2// if we're in Cypress, we'll need to swap this with Cypress.sinon later3let sinon = require('sinon')4const Debug = require('debug')5const chalk = require('chalk')6const stripAnsi = require('strip-ansi')7const { stripIndent } = require('common-tags')8const { printVar, stringifyShort, isObject, addPluginButton, fmt, typeColors } = require('./snapshotUtils')9const debug = Debug('plugin:snapshot')10/**11 * prints nice assertion error in command log with modified error message12 */13function throwErr (e, message, exp, ctx) {14 try {15 ctx.assert(false, message, 'sdf', exp, e.act, true)16 } catch (err) {17 err.message += `\n\n**- expected + actual:**\n${e.message}`18 throw err19 }20}21function getMatchDeepMessage (act, exp) {22 return `Expected **${chai.util.objDisplay(act)}** to deep match: **${chai.util.objDisplay(exp)}**`23}24function saveSnapshot (ctx, exactSpecName, file, exp, act) {25 const message = !exp ? 'new snapshot saved' : 'snapshot updated'26 ctx.assert(true, `ð¸ ${message}: **${exactSpecName}**`, '', exp, act)27 return cy.task('saveSnapshot', {28 file,29 what: act,30 exactSpecName,31 }, { log: false })32}33const registerInCypress = () => {34 // need to use correct sinon version for matcher.isMatcher to work35 sinon = Cypress.sinon36 const $ = Cypress.$37 let snapshotIndex = {}38 chai = window.chai39 chai.Assertion.addMethod('matchDeep', matchDeepCypress)40 chai.Assertion.addMethod('matchSnapshot', matchSnapshotCypress)41 after(() => {42 snapshotIndex = {}43 })44 before(() => {45 addPluginButton($, 'toggle-snapshot-update', '', {46 render () {47 const btnIcon = $(this).children().first()48 return btnIcon.text(top.SNAPSHOT_UPDATE ? 'snapshot\nupdate\non' : 'snapshot\nupdate\noff')49 .css({ 'font-size': '10px', 'line-height': '0.9' })50 .html(btnIcon.html().replace(/\n/g, '<br/>'))51 },52 click () {53 top.SNAPSHOT_UPDATE = !top.SNAPSHOT_UPDATE54 },55 })56 })57 function matchDeepCypress (...args) {58 const exp = args[1] || args[0]59 const ctx = this60 try {61 const res = matchDeep.apply(this, [args[0], args[1], { Cypress, expectedOnly: true }])62 const message = getMatchDeepMessage(res.act, exp)63 ctx.assert(true, message)64 Cypress.log({65 name: 'assert',66 message,67 state: 'passed',68 consoleProps: () => {69 return {70 Actual: res.act,71 }72 },73 })74 } catch (e) {75 throwErr(76 e,77 getMatchDeepMessage(e.act, args[1] || args[0]),78 exp,79 ctx,80 )81 }82 }83 function matchSnapshotCypress (m, snapshotName) {84 const ctx = this85 const file = Cypress.spec.name86 const testName = Cypress.mocha.getRunner().test.fullTitle()87 return cy.then(() => {88 snapshotIndex[testName] = (snapshotIndex[testName] || 1)89 const exactSpecName = snapshotName || `${testName} #${snapshotIndex[testName]}`90 return cy.task('getSnapshot', {91 file,92 exactSpecName,93 }, { log: false })94 .then(function (exp) {95 try {96 snapshotIndex[testName] = snapshotIndex[testName] + 197 const res = matchDeep.call(ctx, m, exp, { message: 'to match snapshot', Cypress, isSnapshot: true, sinon })98 ctx.assert(true, `snapshot matched: **${exactSpecName}**`, res.act)99 } catch (e) {100 if (!e.known) {101 throw e102 }103 // save snapshot if env var or no previously saved snapshot (and no failed matcher assertions)104 if ((top.SNAPSHOT_UPDATE || !exp) && !e.failedMatcher && e.act) {105 return saveSnapshot(ctx, exactSpecName, file, exp, e.act)106 }107 throwErr(e, `**snapshot failed to match**: ${exactSpecName}`, exp, ctx)108 }109 })110 })111 }112}113const matcherStringToObj = (mes) => {114 const res = mes.replace(/typeOf\("(\w+)"\)/, '$1')115 const ret = {}116 ret.toString = () => {117 return `${res}`118 }119 ret.toJSON = () => {120 return `match.${res}`121 }122 return ret123}124const matchDeep = function (matchers, exp, optsArg) {125 let m = matchers126 if (exp === undefined) {127 exp = m128 m = {}129 }130 const opts = _.defaults(optsArg, {131 message: 'to match',132 Cypress: false,133 diff: true,134 expectedOnly: false,135 sinon: null,136 })137 if (!opts.sinon) {138 opts.sinon = sinon139 }140 const match = opts.sinon.match141 const isAnsi = !opts.Cypress142 const act = this._obj143 m = _.map(m, (val, key) => {144 return [key.split('.'), val]145 })146 const diffStr = withMatchers(m, match, opts.expectedOnly)(exp, act)147 if (diffStr.changed) {148 let e = _.extend(new Error(), { known: true, act: diffStr.act, failedMatcher: diffStr.opts.failedMatcher })149 e.message = isAnsi ? `\n${diffStr.text}` : stripAnsi(diffStr.text)150 if (_.isString(act)) {151 e.message = `\n${stripIndent`152 SnapshotError: Failed to match snapshot153 Expected:\n---\n${printVar(exp)}\n---154 Actual:\n---\n${printVar(diffStr.act)}\n---155 `}`156 }157 throw e158 }159 return diffStr160}161const parseMatcherFromString = (matcher) => {162 const regex = /match\.(.*)/163 if (_.isString(matcher)) {164 const parsed = regex.exec(matcher)165 if (parsed) {166 return parsed[1]167 }168 }169}170function parseMatcherFromObj (obj, match) {171 if (match.isMatcher(obj)) {172 return obj173 }174 const objStr = (_.isString(obj) && obj) || (obj && obj.toJSON && obj.toJSON())175 if (objStr) {176 const parsed = parseMatcherFromString(objStr)177 if (parsed) {178 return match[parsed]179 }180 }181 return obj182}183function setReplacement (act, val, path) {184 if (_.isFunction(val)) {185 return val(act, path)186 }187 return val188}189const withMatchers = (matchers, match, expectedOnly = false) => {190 const getReplacementFor = (path = [], m) => {191 for (let rep of m) {192 const wildCards = _.keys(_.pickBy(rep[0], (value) => {193 return value === '*'194 }))195 const _path = _.map(path, (value, key) => {196 if (_.includes(wildCards, `${key}`)) {197 return '*'198 }199 return value200 })201 const matched = _path.join('.').endsWith(rep[0].join('.'))202 if (matched) {203 return rep[1]204 }205 }206 return NO_REPLACEMENT207 }208 const testValue = (matcher, value) => {209 if (matcher.test(value)) {210 return true211 }212 return false213 }214 const NO_REPLACEMENT = {}215 /**216 * diffing function that produces human-readable diff output.217 * unfortunately it is also unreadable code in itself.218 */219 const diff = (exp, act, path = ['^'], optsArg) => {220 const opts = _.defaults({}, optsArg, {221 expectedOnly,222 })223 if (path.length > 15) {224 throw new Error(`exceeded max depth on ${path.slice(0, 4)} ... ${path.slice(-4)}`)225 }226 let text = ''227 let changed = false228 let itemDiff229 let keys230 let subOutput = ''231 let replacement = getReplacementFor(path, matchers)232 if (replacement !== NO_REPLACEMENT) {233 if (match.isMatcher(replacement)) {234 if (testValue(replacement, act)) {235 act = matcherStringToObj(replacement.message).toJSON()236 } else {237 opts.failedMatcher = true238 if (!_.isFunction(act)) {239 act = _.clone(act)240 }241 exp = replacement242 }243 } else {244 act = setReplacement(act, replacement, path)245 }246 } else {247 if (!_.isFunction(act) && !_.isFunction(_.get(act, 'toJSON'))) {248 act = _.clone(act)249 }250 exp = parseMatcherFromObj(exp, match)251 if (match.isMatcher(exp)) {252 if (testValue(exp, act)) {253 act = matcherStringToObj(exp.message).toJSON()254 return {255 text: '',256 changed: false,257 act,258 }259 }260 return {261 text: fmt.wrap('failed', `${chalk.green(printVar(act))} â ${matcherStringToObj(exp.message).toJSON()}`),262 changed: true,263 act,264 }265 }266 }267 if (_.isFunction(_.get(act, 'toJSON'))) {268 act = act.toJSON()269 }270 if (isObject(exp) && isObject(act) && !match.isMatcher(exp)) {271 keys = _.keysIn(exp)272 let actObj = _.extend({}, act)273 let key274 if (_.isArray(exp)) {275 keys.sort((a, b) => +a - +b)276 } else {277 keys.sort()278 }279 for (let i = 0; i < keys.length; i++) {280 key = keys[i]281 const isUndef = exp[key] === undefined282 if (_.hasIn(act, key) || isUndef) {283 itemDiff = diff(exp[key], act[key], path.concat([key]))284 _.defaults(opts, itemDiff.opts)285 act[key] = itemDiff.act286 if (itemDiff.changed) {287 subOutput += fmt.keyChanged(key, itemDiff.text)288 changed = true289 }290 } else {291 subOutput += fmt.keyRemoved(key, exp[key])292 changed = true293 }294 delete actObj[key]295 }296 let addedKeys = _.keysIn(actObj)297 if (!opts.expectedOnly) {298 for (let i = 0; i < addedKeys.length; i++) {299 const key = addedKeys[i]300 const val = act[key]301 const addDiff = diff(val, val, path.concat([key]))302 _.defaults(opts, addDiff.opts)303 act[key] = addDiff.act304 if (act[key] === undefined) continue305 if (opts.failedMatcher) {306 subOutput += addDiff.text307 } else {308 subOutput += fmt.keyAdded(key, act[key])309 }310 changed = true311 }312 }313 if (changed) {314 text = fmt.wrapObjectLike(exp, act, subOutput)315 }316 } else if (match.isMatcher(exp)) {317 debug('is matcher')318 if (!testValue(exp, act)) {319 text = fmt.wrap('failed', `${chalk.green(printVar(act))} â ${matcherStringToObj(exp.message).toJSON()}`)320 changed = true321 }322 } else if (isObject(act)) {323 debug('only act is obj')324 const addDiff = diff({}, act, path, { expectedOnly: false })325 _.defaults(opts, addDiff.opts)326 return _.extend({},327 addDiff, {328 changed: true,329 text: fmt.wrap('removed', `${printVar(exp)}\n${fmt.wrap('added', addDiff.text)}`),330 })331 } else {332 debug('neither is obj')333 exp = printVar(exp)334 act = printVar(act)335 if (exp !== act) {336 text = fmt.wrap('modified', `${exp} ${typeColors['normal']('â®')} ${act}`)337 changed = true338 }339 }340 return {341 changed,342 text,343 act,344 opts,345 }346 }347 return diff348}349module.exports = {350 registerInCypress,351 matchDeep,352 stringifyShort,353 parseMatcherFromString,...
Using AI Code Generation
1import { matchSnapshotCypress } from 'cypress-image-snapshot/command';2describe('My First Test', () => {3 it('Does not do much!', () => {4 cy.get('h1').matchSnapshotCypress();5 });6});7import { matchSnapshotCypress } from 'cypress-image-snapshot/command';8describe('My First Test', () => {9 it('Does not do much!', () => {10 cy.get('h1').matchSnapshotCypress();11 });12});13import { matchSnapshotCypress } from 'cypress-image-snapshot/command';14describe('My First Test', () => {15 it('Does not do much!', () => {16 cy.get('h1').matchSnapshotCypress();17 });18});19import { matchSnapshotCypress } from 'cypress-image-snapshot/command';20describe('My First Test', () => {21 it('Does not do much!', () => {22 cy.get('h1').matchSnapshotCypress();23 });24});25import { matchSnapshotCypress } from 'cypress-image-snapshot/command';26describe('My First Test', () => {27 it('Does not do much!', () => {28 cy.get('h1').matchSnapshotCypress();29 });30});31import { matchSnapshotCypress } from 'cypress-image-snapshot/command';32describe('My First Test', () => {33 it('Does not do much!', () => {34 cy.get('h1').matchSnapshotCypress();35 });36});
Using AI Code Generation
1describe('My First Test', () => {2 it('Does not do much!', () => {3 cy.matchSnapshotCypress()4 })5})6Cypress.Commands.add('matchSnapshotCypress', () => {7 cy.get('body').first().matchImageSnapshot({8 customDiffConfig: {threshold: 0.0},9 })10})11module.exports = (on, config) => {12 on('task', {13 matchSnapshotCypress({image, name, options}) {14 return require('cypress-image-snapshot/plugin')(on, config)15 },16 })17}18{19 "testFiles": "**/*.{feature,features}",20 "env": {21 "cypress-image-snapshot": {22 }23 }24}25{26 "scripts": {
Using AI Code Generation
1it('should match snapshot', () => {2 cy.matchSnapshotCypress('test');3});4it('should match snapshot', () => {5 cy.matchSnapshotJest('test');6});7test('should match snapshot', () => {8 cy.matchSnapshotTestcafe('test');9});10it('should match snapshot', () => {11 cy.matchSnapshotPlaywright('test');12});13it('should match snapshot', () => {14 cy.matchSnapshotPuppeteer('test');15});16test('should match snapshot', () => {17 cy.matchSnapshotTestcafe('test');18});19it('should match snapshot', () => {20 cy.matchSnapshotPlaywright('test');21});22it('should match snapshot', () => {23 cy.matchSnapshotPuppeteer('test');24});25test('should match snapshot', () => {26 cy.matchSnapshotTestcafe('test');27});28it('should match snapshot', () => {29 cy.matchSnapshotPlaywright('test');30});31it('should match snapshot', () => {32 cy.matchSnapshotPuppeteer('test');33});34test('should match snapshot', () => {35 cy.matchSnapshotTestcafe('test');36});37it('should match snapshot', () => {38 cy.matchSnapshotPlaywright('test');39});40it('should match snapshot', () => {41 cy.matchSnapshotPuppeteer('test');42});43test('should match snapshot', () => {44 cy.matchSnapshotTestcafe('test');45});
Using AI Code Generation
1import { matchSnapshotCypress } from 'cypress-image-snapshot/command';2describe('test', function() {3 it('test', function() {4 cy.get('h1').matchSnapshotCypress('test');5 });6});
Using AI Code Generation
1import { matchSnapshotCypress } from 'cypress-image-snapshot/command';2describe('Cypress Image Snapshot', () => {3 it('works', () => {4 cy.wait(1000);5 cy.matchSnapshotCypress('mySnapshot');6 });7});8{9}10const { addMatchImageSnapshotPlugin } = require('cypress-image-snapshot/plugin');11module.exports = (on, config) => {12 addMatchImageSnapshotPlugin(on, config);13 return config;14};15import 'cypress-image-snapshot/command';16import 'cypress-axe';17import 'cypress-sonarqube-reporter/sonarqube-reporter';18Cypress.Commands.add('matchSnapshotCypress', (name) => {19 cy.matchImageSnapshot(name, {20 customDiffConfig: { threshold: 0.1 },21 });22});23Cypress.on('test:after:run', (test, runnable) => {24 if (test.state === 'failed') {25 const item = runnable;26 const { specName } = runnable;27 const videoUrl = `${Cypress.config().videoUploadOnPasses ? 'videos' : 'screenshots'}/${Cypress.spec.name}/${runnable.parent.title} -- ${encodeURIComponent(28 )}.mp4`;29 addContext({ test }, videoUrl);30 }31});32Cypress.on('fail', (error, runnable) => {33 const item = runnable;34 const { specName } = runnable;35 const videoUrl = `${Cypress.config().videoUploadOnPasses ? 'videos' : 'screenshots'}/${Cypress.spec.name}/${runnable.parent.title} -- ${encodeURIComponent(36 )}.mp4`;37 addContext({ test }, videoUrl);38});
Using AI Code Generation
1import { matchSnapshotCypress } from 'cypress-image-snapshot/command';2matchSnapshotCypress();3it('should match snapshot', () => {4 cy.matchSnapshotCypress();5});6it('should update snapshot', () => {7 cy.matchSnapshotCypress('updateSnapshot');8});9import { matchSnapshotCypress } from 'cypress-image-snapshot/command';10matchSnapshotCypress();11Cypress.Commands.add('takeSnapshot', () => {12 cy.matchSnapshotCypress();13});14Cypress.Commands.add('updateSnapshot', () => {15 cy.matchSnapshotCypress('updateSnapshot');16});17it('should match snapshot', () => {18 cy.takeSnapshot();19});20it('should update snapshot', () => {21 cy.updateSnapshot();22});
Using AI Code Generation
1import { matchSnapshotCypress } from 'cypress-image-snapshot/command';2describe('Test Snapshot', () => {3 it('should match snapshot', () => {4 cy.document().matchSnapshotCypress();5 });6});7{8 "env": {9 }10}11{12 "scripts": {13 }14}15const { addMatchImageSnapshotPlugin } = require('cypress-image-snapshot/plugin');16module.exports = (on, config) => {17 addMatchImageSnapshotPlugin(on, config);18 return config;19}20import { addMatchImageSnapshotCommand } from 'cypress-image-snapshot/command';21addMatchImageSnapshotCommand();22{23 {24 }25}26{27 {
Using AI Code Generation
1describe('Test', () => {2 it('test', () => {3 cy.matchSnapshotCypress(win.document.body, 'test');4 });5 });6});7Cypress.Commands.add('matchSnapshotCypress', (element, name) => {8 cy.window({ log: false }).then((win) => {9 const { matchSnapshotCypress } = win;10 if (!matchSnapshotCypress) {11 throw new Error('matchSnapshotCypress is not defined');12 }13 matchSnapshotCypress(element, name);14 });15});16const { addMatchImageSnapshotPlugin } = require('cypress-image-snapshot/plugin');17module.exports = (on, config) => {18 addMatchImageSnapshotPlugin(on, config);19};20import 'cypress-image-snapshot/command';21import 'cypress-iframe';22{23 "env": {24 },25}26I am new to Cypress and I am trying to write a test case for a site that is using iframes. I am trying to click on a button inside the iframe. I have tried clicking the button using cy.iframe().find() but it doesn't work. I have also tried clicking the button using cy.get() but it doesn't work either. I have tried to use the cy.iframe() method to click the button but it doesn't work. I have also tried to use the cy.get() method to click the button but it doesn't work either. I have also tried to use the cy.iframe() method to click the button but it doesn't work. I have also tried to use the cy.get() method to click the button but it doesn't work either. I have also tried to use
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!