Best JavaScript code snippet using storybook-root
index.js
Source:index.js
1'use strict'2/* global cy, Cypress */3const itsName = require('its-name')4const { initStore } = require('snap-shot-store')5const la = require('lazy-ass')6const is = require('check-more-types')7const compare = require('snap-shot-compare')8const path = require('path')9const {10 serializeDomElement,11 serializeToHTML,12 identity,13 countSnapshots14} = require('./utils')15const DEFAULT_CONFIG_OPTIONS = {16 // using relative snapshots requires a simple17 // 'readFileMaybe' plugin to be configured18 // see https://on.cypress.io/task#Read-a-file-that-might-not-exist19 useRelativeSnapshots: false,20 snapshotFileName: 'snapshots.js'21}22/* eslint-disable no-console */23function compareValues ({ expected, value }) {24 const noColor = true25 const json = true26 return compare({ expected, value, noColor, json })27}28function registerCypressSnapshot () {29 la(is.fn(global.before), 'missing global before function')30 la(is.fn(global.after), 'missing global after function')31 la(is.object(global.Cypress), 'missing Cypress object')32 const useRelative = Cypress.config('useRelativeSnapshots')33 const config = {34 useRelativeSnapshots: useRelative === undefined ? DEFAULT_CONFIG_OPTIONS.useRelativeSnapshots : useRelative,35 snapshotFileName: Cypress.config('snapshotFileName') || DEFAULT_CONFIG_OPTIONS.snapshotFileName36 }37 console.log('registering @cypress/snapshot')38 let storeSnapshot39 // for each full test name, keeps number of snapshots40 // allows using multiple snapshots inside single test41 // without confusing them42 // eslint-disable-next-line immutable/no-let43 let counters = {}44 function getSnapshotIndex (key) {45 if (key in counters) {46 // eslint-disable-next-line immutable/no-mutation47 counters[key] += 148 } else {49 // eslint-disable-next-line immutable/no-mutation50 counters[key] = 151 }52 return counters[key]53 }54 let snapshotFileName = config.snapshotFileName55 if (config.useRelativeSnapshots) {56 let relative = Cypress.spec.relative57 if (Cypress.platform === 'win32') {58 relative = relative.replace(/\\/g, path.sep)59 }60 snapshotFileName = path.join(path.dirname(relative), config.snapshotFileName)61 }62 function evaluateLoadedSnapShots (js) {63 la(is.string(js), 'expected JavaScript snapshot source', js)64 console.log('read snapshots.js file')65 const store = eval(js) || {}66 console.log('have %d snapshot(s)', countSnapshots(store))67 storeSnapshot = initStore(store)68 }69 global.before(function loadSnapshots () {70 let readFile71 if (config.useRelativeSnapshots) {72 readFile = cy73 .task('readFileMaybe', snapshotFileName)74 .then(function (contents) {75 if (!contents) {76 return cy.writeFile(snapshotFileName, '', 'utf-8', { log: false })77 }78 return contents79 })80 } else {81 readFile = cy82 .readFile(snapshotFileName, 'utf-8')83 }84 readFile.then(evaluateLoadedSnapShots)85 // no way to catch an error yet86 })87 function getTestName (test) {88 const names = itsName(test)89 // la(is.strings(names), 'could not get name from current test', test)90 return names91 }92 function getSnapshotName (test, humanName) {93 const names = getTestName(test)94 const key = names.join(' - ')95 const index = humanName || getSnapshotIndex(key)96 names.push(String(index))97 return names98 }99 function setSnapshot (name, value, $el) {100 // snapshots were not initialized101 if (!storeSnapshot) {102 return103 }104 // show just the last part of the name list (the index)105 const message = Cypress._.last(name)106 console.log('current snapshot name', name)107 const devToolsLog = {108 value109 }110 if (Cypress.dom.isJquery($el)) {111 // only add DOM elements, otherwise "expected" value is enough112 devToolsLog.$el = $el113 }114 const options = {115 name: 'snapshot',116 message,117 consoleProps: () => devToolsLog118 }119 if ($el) {120 options.$el = $el121 }122 const cyRaiser = ({ value, expected }) => {123 const result = compareValues({ expected, value })124 result.orElse((json) => {125 // by deleting property and adding it at the last position126 // we reorder how the object is displayed127 // We want convenient:128 // - message129 // - expected130 // - value131 devToolsLog.message = json.message132 devToolsLog.expected = expected133 delete devToolsLog.value134 devToolsLog.value = value135 throw new Error(`Snapshot difference. To update, delete snapshot and rerun test.\n${json.message}`)136 })137 }138 Cypress.log(options)139 storeSnapshot({140 value,141 name,142 raiser: cyRaiser143 })144 }145 const pickSerializer = (asJson, value) => {146 if (Cypress.dom.isJquery(value)) {147 return asJson ? serializeDomElement : serializeToHTML148 }149 return identity150 }151 function snapshot (value, { name, json } = {}) {152 console.log('human name', name)153 const snapshotName = getSnapshotName(this.test, name)154 const serializer = pickSerializer(json, value)155 const serialized = serializer(value)156 setSnapshot(snapshotName, serialized, value)157 // always just pass value158 return value159 }160 Cypress.Commands.add('snapshot', { prevSubject: true }, snapshot)161 global.after(function saveSnapshots () {162 if (storeSnapshot) {163 const snapshots = storeSnapshot()164 console.log('%d snapshot(s) on finish', countSnapshots(snapshots))165 console.log(snapshots)166 snapshots.__version = Cypress.version167 const s = JSON.stringify(snapshots, null, 2)168 const str = `module.exports = ${s}\n`169 cy.writeFile(snapshotFileName, str, 'utf-8', { log: false })170 }171 })172 return snapshot173}174module.exports = {175 register: registerCypressSnapshot...
test-bodies.ts
Source:test-bodies.ts
1import 'jest-specific-snapshot';2import { StoryshotsTestMethod, TestMethodOptions } from './api/StoryshotsOptions';3const isFunction = (obj: any) => !!(obj && obj.constructor && obj.call && obj.apply);4const optionsOrCallOptions = (opts: any, story: any) => (isFunction(opts) ? opts(story) : opts);5type SnapshotsWithOptionsReturnType = (6 options: Pick<TestMethodOptions, 'story' | 'context' | 'renderTree' | 'snapshotFileName'>7) => any;8export function snapshotWithOptions(9 options: { renderer?: any; serializer?: any } | Function = {}10): SnapshotsWithOptionsReturnType {11 return ({ story, context, renderTree, snapshotFileName }) => {12 const result = renderTree(story, context, optionsOrCallOptions(options, story));13 function match(tree: any) {14 let target = tree;15 const isReact = story.parameters.framework === 'react';16 if (isReact && typeof tree.childAt === 'function') {17 target = tree.childAt(0);18 }19 if (isReact && Array.isArray(tree.children)) {20 [target] = tree.children;21 }22 if (snapshotFileName) {23 expect(target).toMatchSpecificSnapshot(snapshotFileName);24 } else {25 expect(target).toMatchSnapshot();26 }27 if (typeof tree.unmount === 'function') {28 tree.unmount();29 }30 }31 if (typeof result.then === 'function') {32 return result.then(match);33 }34 return match(result);35 };36}37export function multiSnapshotWithOptions(options = {}): StoryshotsTestMethod {38 return ({ story, context, renderTree, stories2snapsConverter }) => {39 const snapshotFileName = stories2snapsConverter.getSnapshotFileName(context);40 return snapshotWithOptions(options)({ story, context, renderTree, snapshotFileName });41 };42}43export const shallowSnapshot: StoryshotsTestMethod = ({44 story,45 context,46 renderShallowTree,47 options = {},48}) => {49 const result = renderShallowTree(story, context, options);50 expect(result).toMatchSnapshot();51};52export function renderWithOptions(options = {}): StoryshotsTestMethod {53 return ({ story, context, renderTree }) => {54 const result = renderTree(story, context, options);55 if (typeof result.then === 'function') {56 return result;57 }58 return undefined;59 };60}61export const renderOnly = renderWithOptions();...
storyshots.test.js
Source:storyshots.test.js
1// @flow2import initStoryshots, {3 Stories2SnapsConverter,4} from '@storybook/addon-storyshots';5import { mount } from 'enzyme';6import toJson from 'enzyme-to-json';7initStoryshots({8 test: ({ story, context }) => {9 /**10 * ref: https://github.com/storybooks/storybook/blob/master/addons/storyshots/storyshots-core/src/Stories2SnapsConverter.test.js#L311 */12 const converter = new Stories2SnapsConverter();13 const snapshotFileName = converter.getSnapshotFileName(context);14 const storyElement = story.render(context);15 const tree = mount(storyElement)16 .find('#snapshot')17 .children()18 .first();19 const json = toJson(tree);20 if (snapshotFileName) {21 // Remind: property `toMatchSpecificSnapshot`. Property not found in Jest flowtype22 (expect(json): any).toMatchSpecificSnapshot(snapshotFileName);23 }24 },...
Using AI Code Generation
1import { snapshotFileName } from 'storybook-root';2export default {3 parameters: {4 },5};6export const MyComponent = () => <div>My Component</div>;7import { snapshotFileName } from 'storybook-root';8export default {9 parameters: {10 fileName: (context) => {11 const { kind, story } = context;12 return `${kind}_${story}`;13 },14 },15};16export const MyComponent = () => <div>My Component</div>;17import { snapshotSerializer } from 'storybook-root';18export default {19 parameters: {20 serializer: (context) => {21 const { kind, story } = context;22 return `${kind}_${story}`;23 },24 },25};26export const MyComponent = () => <div>My Component</div>;
Using AI Code Generation
1const rootRequire = require('storybook-root-require');2const path = require('path');3const snapshotFileName = rootRequire('src/storybook/snapshotFileName');4const filename = path.basename(__filename);5const snapshotName = snapshotFileName(filename);6test('test snapshot', () => {7 expect(1).toMatchSnapshot(snapshotName);8});9MIT © [saurabh](
Using AI Code Generation
1import { snapshotFileName } from 'storybook-root';2import { snapshotTest } from 'storybook-snapshots';3snapshotTest({4 snapshotFileName: snapshotFileName(__filename),5 storybook: require('./story.js'),6 storybookOptions: { depth: 1 },7});8import { storybookRoot } from 'storybook-root';9export default storiesOf('test', module)10 .add('test', () => {11 return storybookRoot(12 );13 });14| `storybookOptions`| `object` | No | `{}` | Options to pass to the `storybookRoot` function. See the [storybookRoot](#storybookRoot) section for more details. |15| `enzymeOptions` | `object` | No | `{}` | Options to pass to the [Enzyme `mount`](
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!