Best JavaScript code snippet using cypress
index.test.js
Source:index.test.js
1import { testHook, act, cleanup } from 'react-testing-library';2import 'jest-dom/extend-expect';3import useColorTheme from '../src';4afterEach(cleanup);5const createTestElement = arr => ({6 classList: {7 add: (className) => {8 arr.push({ method: 'add', className });9 },10 remove: (className) => {11 arr.push({ method: 'remove', className });12 },13 },14});15describe('useColorTheme without onChange', () => {16 test('initializing with a default value will return false', () => {17 let value;18 testHook(() => {19 ({ value } = useColorTheme(undefined, { storageKey: null }));20 });21 expect(value).toBe('light-theme');22 });23 test('initializing with a value of dark-theme will return dark-theme', () => {24 let value;25 testHook(() => {26 ({ value } = useColorTheme('dark-theme', { storageKey: null }));27 });28 expect(value).toBe('dark-theme');29 });30 test('initializing with a initial value of light-theme will return light-theme', () => {31 let value;32 testHook(() => {33 ({ value } = useColorTheme('light-theme', { storageKey: null }));34 });35 expect(value).toBe('light-theme');36 });37 test('calling `toggle` will return next iteration in className Array', () => {38 let value;39 let toggle;40 testHook(() => {41 ({ value, toggle } = useColorTheme('light-theme', { storageKey: null }));42 });43 act(toggle);44 expect(value).toBe('dark-theme');45 act(toggle);46 expect(value).toBe('light-theme');47 });48 test('a media change to "light-theme" will return true', () => {49 let callback;50 const mockGlobal = {51 matchMedia: media => ({52 media,53 match: false,54 addListener: (handler) => { callback = handler; },55 removeistener: () => {},56 }),57 };58 let value;59 testHook(() => {60 ({ value } = useColorTheme('light-theme', { storageKey: null, global: mockGlobal }));61 });62 callback({ matches: true });63 expect(value).toBe('dark-theme');64 });65 test('a media change to "color theme" will return false', () => {66 let callback;67 const mockGlobal = {68 matchMedia: media => ({69 media,70 match: true,71 addListener: (handler) => { callback = handler; },72 removeistener: () => {},73 }),74 };75 let value;76 testHook(() => {77 ({ value } = useColorTheme('light-theme', { storageKey: null, global: mockGlobal }));78 });79 callback({ matches: false });80 expect(value).toBe('light-theme');81 });82});83describe('useColorTheme accepts a default `config`', () => {84 test('calling `disable` will call handler with `true`', () => {85 let value;86 testHook(() => {87 ({ value } = useColorTheme(true));88 });89 expect(value).toBe(true);90 });91});92describe('useColorTheme and default `onChange`', () => {93 test('`classNames` and `classNames` default', () => {94 const calls = [];95 const mockElement = createTestElement(calls);96 testHook(() => {97 (useColorTheme('light-theme', {98 storageKey: null,99 element: mockElement,100 }));101 });102 expect(calls.length).toBe(3);103 expect(calls[0]).toEqual({ method: 'remove', className: 'light-theme' });104 expect(calls[1]).toEqual({ method: 'remove', className: 'dark-theme' });105 expect(calls[2]).toEqual({ method: 'add', className: 'light-theme' });106 });107 test('`classNames` and `classNames` can be specified in `config`', () => {108 const calls = [];109 const mockElement = createTestElement(calls);110 let toggle;111 testHook(() => {112 ({ toggle } = useColorTheme('d', {113 storageKey: null,114 element: mockElement,115 classNames: ['d', 'l', 'r'],116 }));117 });118 expect(calls.length).toBe(4);119 expect(calls[0]).toEqual({ method: 'remove', className: 'd' });120 expect(calls[1]).toEqual({ method: 'remove', className: 'l' });121 expect(calls[2]).toEqual({ method: 'remove', className: 'r' });122 expect(calls[3]).toEqual({ method: 'add', className: 'd' });123 act(toggle);124 expect(calls.length).toBe(8);125 expect(calls[4]).toEqual({ method: 'remove', className: 'd' });126 expect(calls[5]).toEqual({ method: 'remove', className: 'l' });127 expect(calls[6]).toEqual({ method: 'remove', className: 'r' });128 expect(calls[7]).toEqual({ method: 'add', className: 'l' });129 });130 test('you can specify a custom `storageProvider` and a `storageKey', () => {131 const data = [];132 const mockProvider = {133 getItem: () => null,134 setItem: (key, value) => { data.push([key, value]); },135 };136 let toggle;137 testHook(() => {138 ({ toggle } = useColorTheme('light-theme', {139 storageKey: 'key',140 storageProvider: mockProvider,141 onChange: () => {},142 }));143 });144 expect(data.length).toBe(1);145 expect(data[0]).toEqual(['key', '"light-theme"']);146 act(toggle);147 expect(data.length).toBe(2);148 expect(data[1]).toEqual(['key', '"dark-theme"']);149 });...
rd-addHook.js
Source:rd-addHook.js
1'use strict'2const DESCRIBE = require('mocha').describe3const BEFORE_EACH = require('mocha').beforeEach4const IT = require('mocha').it5const EXPECT = require('chai').expect6const READING_DATA = require('../index')7BEFORE_EACH(function () {8 READING_DATA.clean()9 READING_DATA.uninstall()10})11DESCRIBE('ReadingData#addHook()', function () {12 IT('should be a function', function () {13 EXPECT(READING_DATA.addHook).to.be.a('function')14 })15 IT('should throw an error if first argument isnât a string', function () {16 try {17 READING_DATA.addHook({ huh: 'this ainât no string' })18 } catch (e) {19 EXPECT(e).to.be.an('error')20 }21 })22 IT('should throw an error if second argument isnât a string', function () {23 try {24 READING_DATA.addHook('newHookWithABadPreposition', { huh: 'this ainât no string' })25 } catch (e) {26 EXPECT(e).to.be.an('error')27 }28 })29 IT('should throw an error if second argument isnât a valid string', function () {30 try {31 READING_DATA.addHook('newHookWithABadPreposition', 'above')32 } catch (e) {33 EXPECT(e).to.be.an('error')34 }35 })36 IT('should throw an error if third argument isnât a string', function () {37 try {38 READING_DATA.addHook('newHookWithABadLocation', 'before', { huh: 'this ainât no string' })39 } catch (e) {40 EXPECT(e).to.be.an('error')41 }42 })43 IT('should throw an error if third argument isnât an existing hook', function () {44 try {45 READING_DATA.addHook('newHookWithABadLocation', 'before', 'nonexistentLocation')46 } catch (e) {47 EXPECT(e).to.be.an('error')48 }49 })50 IT('should add a hook when called with one argument', function () {51 let testHook = 'oneArgumentTestHook'52 READING_DATA.addHook(testHook)53 let hooks = READING_DATA.hooks()54 EXPECT(hooks[hooks.length - 1]).to.equal(testHook)55 })56 IT('should add a hook when called with two arguments (preposition: "before")', function () {57 let testHook = 'twoArgumentsTestHook-Before'58 READING_DATA.addHook(testHook, 'before')59 let hooks = READING_DATA.hooks()60 EXPECT(hooks[0]).to.equal(testHook)61 })62 IT('should add a hook when called with two arguments (preposition: "after")', function () {63 let testHook = 'twoArgumentsTestHook-After'64 READING_DATA.addHook(testHook, 'after')65 let hooks = READING_DATA.hooks()66 EXPECT(hooks[hooks.length - 1]).to.equal(testHook)67 })68 IT('should add a hook when called with three arguments (preposition: "before")', function () {69 let testHook = 'threeArgumentsTestHook-Before'70 READING_DATA.addHook(testHook, 'before', 'process')71 let hooks = READING_DATA.hooks()72 EXPECT(hooks[hooks.indexOf('process') - 1]).to.equal(testHook)73 })74 IT('should add a hook when called with three arguments (preposition: "after")', function () {75 let testHook = 'threeArgumentsTestHook-After'76 READING_DATA.addHook(testHook, 'after', 'process')77 let hooks = READING_DATA.hooks()78 EXPECT(hooks[hooks.indexOf('process') + 1]).to.equal(testHook)79 })80 IT('should not add a hook that is already registered', function () {81 let hook = 'process'82 let hooks = READING_DATA.hooks()83 EXPECT(hooks).to.include(hook)84 let hookIndex = hooks.indexOf(hook)85 READING_DATA.addHook(hook)86 hooks = READING_DATA.hooks()87 EXPECT(hooks.indexOf(hook)).to.equal(hookIndex)88 })...
digitrustIdSystem_spec.js
Source:digitrustIdSystem_spec.js
...33 mockCmp.stubSettings.consents = consents;34}35describe('DigiTrust Id System', function () {36 it('Should create the test hook', function (done) {37 testHook = surfaceTestHook();38 assert.isNotNull(testHook, 'The test hook failed to surface');39 var conf = {40 init: {41 member: 'unit_test',42 site: 'foo'43 },44 callback: function (result) {45 }46 };47 testHook.initDigitrustFacade(conf);48 window.DigiTrust.getUser(conf);49 expect(window.DigiTrust).to.exist;50 expect(window.DigiTrust.isMock).to.be.true;51 done();52 });53 it('Should report as client', function (done) {54 delete window.DigiTrust;55 testHook = surfaceTestHook();56 var conf = {57 init: {58 member: 'unit_test',59 site: 'foo'60 },61 callback: function (result) {62 expect(window.DigiTrust).to.exist;63 expect(result).to.exist;64 expect(window.DigiTrust.isMock).to.be.true;65 }66 };67 testHook.initDigitrustFacade(conf);68 expect(window.DigiTrust).to.exist;69 expect(window.DigiTrust.isClient).to.be.true;70 done();71 });72 it('Should allow consent when given', function (done) {73 testHook = surfaceTestHook();74 setupCmpMock(true, true);75 var handler = function(result) {76 expect(result).to.be.true;77 done();78 }79 testHook.gdpr.hasConsent(null, handler);80 });81 it('Should consent if does not apply', function (done) {82 testHook = surfaceTestHook();83 setupCmpMock(false, true);84 var handler = function (result) {85 expect(result).to.be.true;86 done();87 }88 testHook.gdpr.hasConsent(null, handler);89 });90 it('Should not allow consent when not given', function (done) {91 testHook = surfaceTestHook();92 setupCmpMock(true, false);93 var handler = function (result) {94 expect(result).to.be.false;95 done();96 }97 testHook.gdpr.hasConsent(null, handler);98 });99 it('Should deny consent if timeout', function (done) {100 window.__cmp = function () { };101 var handler = function (result) {102 expect(result).to.be.false;103 done();104 }105 testHook.gdpr.hasConsent({ consentTimeout: 1 }, handler);106 });107 it('Should pass consent test if cmp not present', function (done) {108 delete window.__cmp109 testHook = surfaceTestHook();110 var handler = function (result) {111 expect(result).to.be.true;112 done();113 }114 testHook.gdpr.hasConsent(null, handler);115 });...
useModal.test.jsx
Source:useModal.test.jsx
1import React from 'react';2import { act } from 'react-dom/test-utils';3import { mount } from 'enzyme';4import useModal from './useModal';5const TestHook = ({ callback }) => {6 callback();7 return null;8};9const testHook = callback => {10 mount(<TestHook callback={callback} />);11};12describe('useModal hook', () => {13 let closeModal;14 let isModalOpen;15 let toggleModal;16 test('isModalOpen should return expected default value', () => {17 testHook(() => {18 ({ isModalOpen, toggleModal, closeModal } = useModal());19 });20 expect(isModalOpen).toEqual(false);21 expect(toggleModal).toBeInstanceOf(Function);22 expect(closeModal).toBeInstanceOf(Function);23 });24 test('isModalOpen should return expected initialized value', () => {25 testHook(() => {26 ({ isModalOpen, toggleModal, closeModal } = useModal(true));27 });28 expect(isModalOpen).toEqual(true);29 expect(toggleModal).toBeInstanceOf(Function);30 expect(closeModal).toBeInstanceOf(Function);31 });32 test('should return expected isModalOpen value after modal toggle', () => {33 testHook(() => {34 ({ isModalOpen, toggleModal, closeModal } = useModal());35 });36 expect(isModalOpen).toEqual(false);37 act(() => {38 toggleModal();39 });40 expect(isModalOpen).toEqual(true);41 });42 test('isModalOpen should be false after closeModal is called', () => {43 testHook(() => {44 ({ isModalOpen, toggleModal, closeModal } = useModal());45 });46 expect(isModalOpen).toEqual(false);47 act(() => {48 toggleModal();49 });50 expect(isModalOpen).toEqual(true);51 act(() => {52 closeModal();53 });54 expect(isModalOpen).toEqual(false);55 });...
test.mjs
Source:test.mjs
1import test from 'ava'2import config from './src/index.mjs'3import defaultHooks from './src/default-hooks.mjs'4import toHooks from './src/to-hooks.mjs'5const hooks = toHooks(defaultHooks)6const testHook = Object.keys(hooks)[0]7const testCommand = `echo "${new Date()}"`8test('default', (t) => {9 t.deepEqual(config.hooks, hooks)10})11test('prepend', (t) => {12 const modified = config.prepend({13 [testHook]: testCommand,14 })15 t.is(modified.hooks[testHook], `${testCommand} && ${hooks[testHook]}`)16})17test('append', (t) => {18 const modified = config.append({19 [testHook]: testCommand,20 })21 t.is(modified.hooks[testHook], `${hooks[testHook]} && ${testCommand}`)22})23test('overrides', (t) => {24 const modified = config.overrides({25 [testHook]: [testCommand],26 })27 t.is(modified.hooks[testHook], testCommand)28})29test('overrides with falsely value', (t) => {30 const modified = config.overrides({31 [testHook]: null,32 })33 t.is(modified.hooks[testHook], undefined)34})35test('chained', (t) => {36 const modified = config37 .overrides({38 [testHook]: null,39 })40 .prepend({41 [testHook]: ['prepend', testCommand],42 })43 .append({44 [testHook]: ['append', testCommand],45 })46 t.is(47 modified.hooks[testHook],48 ['prepend', testCommand, 'append', testCommand].join(' && '),49 )...
tree.spec..js
Source:tree.spec..js
1// enables intelligent code completion for Cypress commands2// https://on.cypress.io/intelligent-code-completion3/// <reference types="cypress" />4const testHook = (hook) => `[data-test-hook="${hook}"]`;5context("Tree menu e2e test", () => {6 beforeEach(() => {7 cy.visit("http://localhost:3000");8 });9 it("Tree menu", function () {10 cy.get(testHook("tree-item")).contains("Meet IntelliJ IDEA");11 cy.get(testHook("tree-item")).contains("Getting help").should("not.exist");12 cy.get(testHook("tree-item")).contains("Meet IntelliJ IDEA").click();13 cy.get(testHook("tree-item")).contains("Getting help");14 cy.get(testHook("tree-item")).contains("Learn more").should("not.exist");15 cy.get(testHook("tree-item")).contains("Getting help").click();16 cy.get(testHook("tree-item")).contains("Learn more");17 cy.get(testHook("filter")).type("Feedback");18 cy.get(testHook("tree-item")).should("have.length", 1);19 cy.get(testHook("tree-item"))20 .contains("Meet IntelliJ IDEA")21 .should("not.exist");22 cy.get(testHook("tree-item")).contains("Sending Feedback");23 });...
hook.test.js
Source:hook.test.js
1const Hook = require('../hooks/hook')2describe('Hook', () => {3 let TestHook4 beforeEach(() => {5 TestHook = new Hook('mockEvent')6 })7 it('subscribes callbacks', () => {8 TestHook.subscribe( jest.fn() )9 TestHook.subscribe( jest.fn() )10 expect(TestHook.getSubscriptions()).toHaveLength(2)11 })12 it('calls subscribed callbacks', () => {13 let fn = jest.fn()14 TestHook.subscribe(fn)15 TestHook.broadcast()16 expect(fn).toHaveBeenCalled()17 })18 it('calls subscribed callbacks ordered by priority', () => {19 let finishLine = 020 let first = () => finishLine === 0? finishLine = 'first' : false21 let second = () => finishLine === 0? finishLine = 'second' : false22 TestHook.subscribe(first).priority(0)23 TestHook.subscribe(second).priority(1)24 TestHook.broadcast()25 expect(finishLine).toBe('first')26 })27 it('prevents from running due to validation', () => {28 TestHook.validateRequest = () => false29 const fn = jest.fn()30 TestHook.subscribe(fn)31 TestHook.process()32 expect(fn).toHaveBeenCalledTimes(0)33 })...
react-tests.js
Source:react-tests.js
...11});12var React = require('react');13var _require2 = require('enzyme'),14 mount = _require2.mount;15var TestHook = function TestHook(_ref) {16 var callback = _ref.callback,17 params = _ref.params;18 callback(params);19 return null;20};21var testHook = function testHook(callback) {22 var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};23 return mount(React.createElement(TestHook, {24 callback: callback,25 params: params26 }));27};...
Using AI Code Generation
1import { TestHook } from 'cypress-react-selector'2describe('My First Test', () => {3 it('Does not do much!', () => {4 cy.contains('type').click()5 cy.url().should('include', '/commands/actions')6 cy.get('.action-email')7 .type('
Using AI Code Generation
1class TestHook {2 constructor(attr, value) {3 }4 toString() {5 return `[data-test="${this.value}"]`6 }7}8Cypress.Commands.add('getByTestHook', (attr, value) => {9 return cy.get(new TestHook(attr, value))10})11cy.getByTestHook('hook', 'my-hook').should('have.text', 'My Hook')
Using AI Code Generation
1require('cypress-react-unit-test/plugins/load-webpack')(on, config);2require('cypress-react-unit-test/plugins/next')(on, config);3require('cypress-react-unit-test/plugins/react-scripts')(on, config);4module.exports = (on, config) => {5 on('before:browser:launch', (browser = {}, launchOptions) => {6 if (browser.name === 'chrome') {7 launchOptions.args = launchOptions.args.filter(8 );9 return launchOptions;10 }11 });12};13require('cypress-react-unit-test/plugins/load-webpack')(on, config);14require('cypress-react-unit-test/plugins/next')(on, config);15require('cypress-react-unit-test/plugins/react-scripts')(on, config);16module.exports = (on, config) => {17 on('before:browser:launch', (browser = {}, launchOptions) => {18 if (browser.name === 'chrome') {19 launchOptions.args = launchOptions.args.filter(20 );21 return launchOptions;22 }23 });24};
Using AI Code Generation
1import { TestHook } from './TestHook'2context('My First Test', () => {3 beforeEach(() => {4 })5 it('finds the content "type"', () => {6 cy.contains('type')7 })8 it('finds the content "type" using TestHook', () => {9 TestHook('type').contains('type')10 })11})12export const TestHook = (hook, ...args) => {13 return cy.get(`[data-test-hook=${hook}]`, ...args)14}
Using AI Code Generation
1Cypress.Commands.add("testHook", (hook, options = {}) => {2 return cy.get(`[data-test=${hook}]`, options);3});4describe("test", () => {5 it("test", () => {6 cy.testHook("test").should("exist");7 });8});
Using AI Code Generation
1import { TestHook } from './TestHook'2describe('Test Hook', () => {3 it('should test TestHook', () => {4 cy.get(TestHook('test-hook')).contains('Hello World')5 })6})7export const TestHook = (hook) => {8 return `[data-cy=${hook}]`9}10import { TestHook } from './TestHook'11describe('Test Hook', () => {12 it('should test TestHook', () => {13 cy.get(TestHook('test-hook')).contains('Hello World')14 })15})16export const TestHook = (hook) => {17 return `[data-cy=${hook}]`18}19import { TestHook } from './TestHook'20describe('Test Hook', () => {21 it('should test TestHook', () => {22 cy.get(TestHook('test-hook')).contains('Hello World')23 })24})25export const TestHook = (hook) => {26 return `[data-cy=${hook}]`27}28import { TestHook } from './TestHook'29describe('Test Hook', () => {30 it('should test TestHook', () => {31 cy.get(TestHook('test-hook')).contains('Hello World')32 })33})34export const TestHook = (hook) => {35 return `[data-cy=${hook}]`36}
Using AI Code Generation
1it('test', () => {2 cy.TestHook('test-hook').should('contain', 'test');3});4cy.TestHook('test-hook')5cy.TestHook('test-hook').each((el) => {6});7cy.TestHook('test-hook').click();8cy.TestHook('test-hook').each((el) => {9 el.click();10});11cy.TestHook('test-hook').click();12cy.TestHook('test-hook').each((el) => {13 el.click();14});
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!!