Best JavaScript code snippet using storybook-root
Snapshot.js
Source:Snapshot.js
1import { expect } from "chai";2import moment from "moment";3import { prettyPrintGasCost } from "./helpers/gasUtils";4import { latestTimestamp } from "./helpers/latestTime";5import increaseTime, { setTimeTo } from "./helpers/increaseTime";6import { eventValue } from "./helpers/events";7import EvmError from "./helpers/EVMThrow";8const TestSnapshot = artifacts.require("TestSnapshot");9const day = 24 * 3600;10contract("Snapshot", () => {11 let snapshotTest;12 const getSnapshotIdFromEvent = tx => eventValue(tx, "LogSnapshotCreated", "snapshotId");13 const createSnapshot = async () => {14 const r = await snapshotTest.createSnapshot();15 assert.equal(r.logs.length, 1);16 return getSnapshotIdFromEvent(r);17 };18 beforeEach(async () => {19 snapshotTest = await TestSnapshot.new(0);20 });21 it("should deploy", async () => {22 await prettyPrintGasCost("createSnapshot", snapshotTest);23 });24 it("should be initially unset", async () => {25 assert.isFalse(await snapshotTest.hasValue.call());26 });27 it("should initially return default", async () => {28 assert.equal(12, await snapshotTest.getValue.call(12));29 assert.equal(42, await snapshotTest.getValue.call(42));30 });31 it("should return correct snapshot id via snapshotAt", async () => {32 // encodes day number from unix epoch on 128 MSB of 256 word33 // day boundary on 00:00 UTC34 function encodeSnapshotId(noOfDays) {35 return new web3.BigNumber(2).pow(128).mul(noOfDays);36 }37 async function expectDays(timestamp, expectedNoOfDays) {38 const snapshotId = await snapshotTest.snapshotAt(timestamp);39 const expectedSnapshotId = encodeSnapshotId(expectedNoOfDays);40 expect(snapshotId).to.be.bignumber.eq(expectedSnapshotId);41 }42 await expectDays(1107795768, 12821);43 await expectDays(0, 0);44 await expectDays(1, 0);45 // get timestamp from UTC time46 const utcDayBoundaryTimestamp = Math.floor(Date.UTC(2017, 11, 15) / 1000);47 const utcDayCount = Math.floor(utcDayBoundaryTimestamp / (24 * 60 * 60));48 await expectDays(utcDayBoundaryTimestamp - 1, utcDayCount - 1);49 await expectDays(utcDayBoundaryTimestamp, utcDayCount);50 await expectDays(utcDayBoundaryTimestamp + 1, utcDayCount);51 await expectDays(utcDayBoundaryTimestamp + 24 * 60 * 60, utcDayCount + 1);52 });53 it("should initially return default when queried by snapshot id", async () => {54 const day0 = await snapshotTest.snapshotAt.call((await latestTimestamp()) + 0 * day);55 expect(await snapshotTest.getValueAt.call(day0, 41)).to.be.bignumber.eq(41);56 });57 it("should create a snapshot", async () => {58 const r = await snapshotTest.createSnapshot();59 await prettyPrintGasCost("createSnapshot", r);60 });61 it("should set a new value", async () => {62 const r = await snapshotTest.setValue(1234);63 await prettyPrintGasCost("Setting new value should of ", r);64 assert.equal(1234, await snapshotTest.getValue.call(12));65 assert.isTrue(await snapshotTest.hasValue.call());66 });67 it("should overwrite last snapshot", async () => {68 const tx1 = await snapshotTest.setValue(1234);69 const snapshotId1 = getSnapshotIdFromEvent(tx1);70 const tx2 = await snapshotTest.setValue(12345);71 const snapshotId2 = await snapshotTest.currentSnapshotId.call();72 await prettyPrintGasCost("overwrite last snapshot", tx2);73 expect(await snapshotTest.getValue.call(12)).to.be.bignumber.eq(12345);74 assert.isTrue(await snapshotTest.hasValue.call());75 expect(snapshotId1).to.be.bignumber.eq(snapshotId2);76 });77 it("should keep values in snapshots", async () => {78 const before = await createSnapshot();79 await snapshotTest.setValue(100);80 const middle = await createSnapshot();81 await snapshotTest.setValue(200);82 const after = await createSnapshot();83 assert.isFalse(await snapshotTest.hasValueAt.call(before.sub(1)));84 assert.isTrue(await snapshotTest.hasValueAt.call(before));85 assert.isTrue(await snapshotTest.hasValueAt.call(middle.sub(1)));86 assert.isTrue(await snapshotTest.hasValueAt.call(middle));87 assert.isTrue(await snapshotTest.hasValueAt.call(after.sub(1)));88 expect(await snapshotTest.getValueAt.call(before.sub(1), 41)).to.be.bignumber.eq(41);89 expect(await snapshotTest.getValueAt.call(before, 41)).to.be.bignumber.eq(100);90 expect(await snapshotTest.getValueAt.call(middle.sub(1), 41)).to.be.bignumber.eq(100);91 expect(await snapshotTest.getValueAt.call(middle, 41)).to.be.bignumber.eq(200);92 expect(await snapshotTest.getValueAt.call(after.sub(1), 41)).to.be.bignumber.eq(200);93 });94 it("should create daily snapshots", async () => {95 const currentTimestamp = await latestTimestamp();96 const day0 = await snapshotTest.snapshotAt.call(currentTimestamp + 0 * day);97 const tx0 = await snapshotTest.setValue(100);98 const snapshotId0 = getSnapshotIdFromEvent(tx0);99 expect(snapshotId0).to.be.bignumber.eq(day0);100 const day1 = await snapshotTest.snapshotAt.call(currentTimestamp + 1 * day);101 await increaseTime(moment.duration({ days: 1 }));102 const tx1 = await snapshotTest.setValue(200);103 const snapshotId1 = getSnapshotIdFromEvent(tx1);104 expect(snapshotId1).to.be.bignumber.eq(day1);105 const day2 = await snapshotTest.snapshotAt.call(currentTimestamp + 2 * day);106 await increaseTime(moment.duration({ days: 1 }));107 const tx2 = await snapshotTest.setValue(300);108 const snapshotId2 = getSnapshotIdFromEvent(tx2);109 expect(snapshotId2).to.be.bignumber.eq(day2);110 const day3 = await snapshotTest.snapshotAt.call(currentTimestamp + 3 * day);111 expect(await snapshotTest.getValueAt.call(day0.sub(1), 41)).to.be.bignumber.eq(41);112 expect(await snapshotTest.getValueAt.call(day0, 41)).to.be.bignumber.eq(100);113 expect(await snapshotTest.getValueAt.call(day1, 41)).to.be.bignumber.eq(200);114 expect(await snapshotTest.getValueAt.call(day2, 41)).to.be.bignumber.eq(300);115 expect(await snapshotTest.getValue.call(41)).to.be.bignumber.eq(300);116 await expect(snapshotTest.getValueAt.call(day3, 41)).to.be.rejectedWith(EvmError);117 });118 it("should throw when queried in the future", async () => {119 const ct = await latestTimestamp();120 const day1 = await snapshotTest.snapshotAt.call(ct + 1 * day);121 await expect(snapshotTest.getValueAt.call(day1, 41)).to.be.rejectedWith(EvmError);122 await expect(snapshotTest.hasValueAt.call(day1)).to.be.rejectedWith(EvmError);123 });124 it("should not delete interim value when set to previous value", async () => {125 // this test may fail if betweend createSnapshot() and setValue() there is a day boundary126 await createSnapshot();127 await snapshotTest.setValue(100);128 await createSnapshot();129 await snapshotTest.setValue(200);130 const after = await createSnapshot();131 await snapshotTest.setValue(100);132 await snapshotTest.setValue(200);133 const afterValue = await snapshotTest.getValueAt.call(after, -1);134 expect(afterValue).to.be.bignumber.eq(200);135 await snapshotTest.setValue(101);136 const afterValueChanged = await snapshotTest.getValueAt.call(after, -1);137 expect(afterValueChanged).to.be.bignumber.eq(101);138 const postMortem = await createSnapshot();139 // no snapshot were created after after140 expect(postMortem).to.be.bignumber.eq(after.add(1));141 });142 it("should perform approximate binary search", async () => {143 // this search must return previous value for approximate matches144 // due to end condition it's never O(1)145 // so let's test it146 const binSearch = (values, value) => {147 let min = 0;148 let max = values.length - 1;149 let iter = 0;150 while (max > min) {151 // eslint-disable-next-line no-bitwise152 const mid = (max + min + 1) >> 1;153 if (values[mid] <= value) {154 min = mid;155 } else {156 max = mid - 1;157 }158 iter += 1;159 }160 return [min, iter];161 };162 const days = Array.from(new Array(100), (x, i) => i * 2 ** 4);163 let avgIters = 0;164 for (let ii = 0; ii < days.length * 2 ** 4; ii += 1) {165 const r = binSearch(days, ii);166 // use linear search to verify167 const expectedIdx = days.findIndex(e => ii - e < 2 ** 4 && ii >= e);168 expect(r[0]).to.eq(expectedIdx);169 avgIters += r[1];170 }171 // eslint-disable-next-line no-console172 console.log(173 `\tAverage searches ${avgIters / (days.length * 2 ** 4)} vs theoretical O(log N) ${Math.log2(174 days.length,175 )}`,176 );177 });178 it("should create 100 daily snapshots with deterministic snapshot id", async () => {179 const day0 = await snapshotTest.snapshotAt.call(await latestTimestamp());180 const simulatedDays = 100; // 365*10;181 for (let ii = 0; ii < simulatedDays; ii += 1) {182 await snapshotTest.setValue(ii * 10 + 1);183 await increaseTime(moment.duration({ days: 1 }));184 }185 const daysMsb = new web3.BigNumber(2).pow(128);186 // make sure all boundaries crossed187 const expectedSnapshotId = day0.add(daysMsb.mul(simulatedDays));188 expect(await snapshotTest.currentSnapshotId()).to.be.bignumber.eq(expectedSnapshotId);189 });190 it("should return value read between non consecutive snapshot ids", async () => {191 const day0 = await snapshotTest.snapshotAt.call((await latestTimestamp()) + 0 * day);192 const day1 = await snapshotTest.snapshotAt.call((await latestTimestamp()) + 1 * day);193 await snapshotTest.setValue(100);194 await increaseTime(moment.duration({ days: 1 }));195 await snapshotTest.setValue(200);196 expect(await snapshotTest.getValueAt.call(day0.add(1), 41)).to.be.bignumber.eq(100);197 expect(198 await snapshotTest.getValueAt.call(day0.add(day1.sub(day0).div(2)), 41),199 ).to.be.bignumber.eq(100);200 expect(await snapshotTest.getValueAt.call(day1.sub(1), 41)).to.be.bignumber.eq(100);201 });202 it("should return value for snapshot ids after last physical entry was created", async () => {203 const day0 = await snapshotTest.snapshotAt.call((await latestTimestamp()) + 0 * day);204 await snapshotTest.setValue(100);205 await snapshotTest.createSnapshot();206 expect(await snapshotTest.getValueAt.call(day0.add(1), 41)).to.be.bignumber.eq(100);207 });208 it("should correctly create snapshots around day boundary", async () => {209 const boundary = Math.floor((await latestTimestamp()) / day + 1) * day;210 // set time to 3s before boundary211 await setTimeTo(boundary - 3);212 // test may fail if block is mined longer than 3 seconds213 const befTx = await snapshotTest.setValue(100);214 // 3 seconds into day boundary215 await increaseTime(3);216 const aftTx = await snapshotTest.setValue(200);217 const befSnapshotId = getSnapshotIdFromEvent(befTx);218 const aftSnapshotId = getSnapshotIdFromEvent(aftTx);219 // should have 1 day difference220 expect(aftSnapshotId.sub(befSnapshotId)).to.be.bignumber.eq(new web3.BigNumber(2).pow(128));221 });222 it("should clone snapshot id", async () => {223 const initialSnapshotId = await snapshotTest.currentSnapshotId.call();224 const snapshotClone = await TestSnapshot.new(initialSnapshotId);225 const cloneInitialSnapshotId = await snapshotClone.currentSnapshotId.call();226 expect(cloneInitialSnapshotId).to.be.bignumber.eq(initialSnapshotId);227 await snapshotTest.createSnapshot();228 const initialSnapshotId2 = await snapshotTest.currentSnapshotId.call();229 const snapshotClone2 = await TestSnapshot.new(initialSnapshotId2);230 const cloneInitialSnapshotId2 = await snapshotClone2.currentSnapshotId.call();231 expect(cloneInitialSnapshotId2).to.be.bignumber.eq(initialSnapshotId2);232 });233 it("should reject clone for earlier day", async () => {234 const timestamp = Math.floor(new Date().getTime() / 1000);235 // remove day below for test to fail236 const prevDaySnapshotId = await snapshotTest.snapshotAt(timestamp - day);237 await expect(TestSnapshot.new(prevDaySnapshotId)).to.be.rejectedWith(EvmError);238 });239 it("should reject clone for future day", async () => {240 const timestamp = Math.floor(new Date().getTime() / 1000);241 // remove day below for test to fail242 const nextDaySnapshotId = await snapshotTest.snapshotAt(timestamp + day);243 await expect(TestSnapshot.new(nextDaySnapshotId)).to.be.rejectedWith(EvmError);244 });...
snapshotTests.js
Source:snapshotTests.js
1/* Component tests generated by react-snapshot-test-generator on 2016-11-14T14:51:37.022Z */2import React from 'react';3import renderer from 'react-test-renderer';4function snapshotTest(element) {5 const tree = renderer.create(element).toJSON();6 expect(tree).toMatchSnapshot();7}8import Container from '../src/common/Container/Container';9import TabsContainer from '../src/common/Container/TabsContainer';10import LoadingContainer from '../src/common/Container/LoadingContainer';11import BashSnippet from '../src/common/BashSnippet/BashSnippet';12import ChartLegend from '../src/common/Billing/ChartLegend';13import Header from '../src/common/ColumnList/Header';14import ItemColumn from '../src/common/ColumnList/ItemColumn';15import ColumnHeader from '../src/common/ColumnList/Column/ColumnHeader';16import Desc from '../src/common/ColumnList/Column/Desc';17import ID from '../src/common/ColumnList/Column/ID';18import Name from '../src/common/ColumnList/Column/Name';19import Text from '../src/common/ColumnList/Column/Text';20import DialogContent from '../src/common/Dialog/DialogContent';21import DialogContentSection from '../src/common/Dialog/DialogContentSection';22import DialogSidebar from '../src/common/Dialog/DialogSidebar';23import DialogSidebarBox from '../src/common/Dialog/DialogSidebarBox';24import DialogSidebarSection from '../src/common/Dialog/DialogSidebarSection';25import RoundIcon from '../src/common/Icon/RoundIcon';26import ListContainer from '../src/common/Lists/ListContainer';27import MobileOnboardingSlide from '../src/common/MobileOnboarding/MobileOnboardingSlide';28import NotificationCloseButton from '../src/common/Notification/NotificationCloseButton';29import Show from '../src/common/Show/Show';30import ListSubheader from '../src/common/Sidebar/ListSubheader';31import SliderSection from '../src/common/Slider/SliderSection';32import TraceResult from '../src/common/TraceResult/TraceResult';33import Truncate from '../src/common/Truncate/Truncate';34describe('<Container />', () => {35 it('renders correctly', () => {36 snapshotTest(<Container />);37 });38});39describe('<TabsContainer />', () => {40 it('renders correctly', () => {41 snapshotTest(<TabsContainer />);42 });43});44describe('<LoadingContainer />', () => {45 it('renders correctly', () => {46 snapshotTest(<LoadingContainer />);47 });48});49describe('<BashSnippet />', () => {50 it('renders correctly', () => {51 snapshotTest(<BashSnippet />);52 });53});54describe('<ChartLegend />', () => {55 it('renders correctly', () => {56 snapshotTest(<ChartLegend />);57 });58});59describe('<Header />', () => {60 it('renders correctly', () => {61 snapshotTest(<Header />);62 });63});64describe('<ItemColumn />', () => {65 it('renders correctly', () => {66 snapshotTest(<ItemColumn />);67 });68});69describe('<ColumnHeader />', () => {70 it('renders correctly', () => {71 snapshotTest(<ColumnHeader />);72 });73});74describe('<Desc />', () => {75 it('renders correctly', () => {76 snapshotTest(<Desc />);77 });78});79describe('<ID />', () => {80 it('renders correctly', () => {81 snapshotTest(<ID />);82 });83});84describe('<Name />', () => {85 it('renders correctly', () => {86 snapshotTest(<Name />);87 });88});89describe('<Text />', () => {90 it('renders correctly', () => {91 snapshotTest(<Text />);92 });93});94describe('<DialogContent />', () => {95 it('renders correctly', () => {96 snapshotTest(<DialogContent />);97 });98});99describe('<DialogContentSection />', () => {100 it('renders correctly', () => {101 snapshotTest(<DialogContentSection />);102 });103});104describe('<DialogSidebar />', () => {105 it('renders correctly', () => {106 snapshotTest(<DialogSidebar />);107 });108});109describe('<DialogSidebarBox />', () => {110 it('renders correctly', () => {111 snapshotTest(<DialogSidebarBox />);112 });113});114describe('<DialogSidebarSection />', () => {115 it('renders correctly', () => {116 snapshotTest(<DialogSidebarSection />);117 });118});119describe('<RoundIcon />', () => {120 it('renders correctly', () => {121 snapshotTest(<RoundIcon />);122 });123});124describe('<ListContainer />', () => {125 it('renders correctly', () => {126 snapshotTest(<ListContainer />);127 });128});129describe('<MobileOnboardingSlide />', () => {130 it('renders correctly', () => {131 snapshotTest(<MobileOnboardingSlide />);132 });133});134describe('<NotificationCloseButton />', () => {135 it('renders correctly', () => {136 snapshotTest(<NotificationCloseButton />);137 });138});139describe('<Show />', () => {140 it('renders correctly', () => {141 snapshotTest(<Show />);142 });143});144describe('<ListSubheader />', () => {145 it('renders correctly', () => {146 snapshotTest(<ListSubheader />);147 });148});149describe('<SliderSection />', () => {150 it('renders correctly', () => {151 snapshotTest(<SliderSection />);152 });153});154describe('<TraceResult />', () => {155 it('renders correctly', () => {156 snapshotTest(<TraceResult />);157 });158});159describe('<Truncate />', () => {160 it('renders correctly', () => {161 snapshotTest(<Truncate />);162 });...
test.js
Source:test.js
...9 test(name, t => {10 t.snapshot(code, `${name} - before`)11 t.snapshot(transpile(code), `${name} - compiled`)12 })13snapshotTest('No Events', '<a />')14snapshotTest('Ignores spread', '<a {...b} />')15snapshotTest('Ignores attributes', '<a href="#" />')16snapshotTest('Ignores not jsx expressions', '<a onEvent="str" />')17snapshotTest('Plain Event', '<a onEvent={this.action} />')18snapshotTest('Supports Dash', '<a on-event={this.action} />')19snapshotTest('Combine Events', '<a onEvent={this.action1} onEvent={this.action2} />')20snapshotTest('Simple :capture', '<a onEvent:capture={this.action1} />')21snapshotTest('Simple :once', '<a onEvent:once={this.action1} />')22snapshotTest(':capture-once', '<a onEvent:capture-once={this.action1} />')23snapshotTest('Simple stopPropagation :stop', '<a onEvent:stop={this.action1} />')24snapshotTest('Simple preventDefault :prevent', '<a onEvent:prevent={this.action1} />')25snapshotTest('Simple :self', '<a onEvent:self={this.action1} />')26snapshotTest('Simple no-key-modifier :bare', '<a onEvent:bare={this.action1} />')27snapshotTest('Simple key-modifier :shift', '<a onEvent:shift={this.action1} />')28snapshotTest(29 'No key modifier but alt and shift and must be both alt and shift :bare-alt-shift',30 '<a onEvent:bare-alt-shift={this.action1} />',31)32snapshotTest('Simple alias :enter', '<a onEvent:enter={this.action1} />')33snapshotTest('Simple double alias :delete', '<a onEvent:delete={this.action1} />')...
Using AI Code Generation
1import initStoryshots from '@storybook/addon-storyshots';2import { snapshotTest } from 'storybook-root-snapshot';3initStoryshots({4 test: snapshotTest({5 storyKindRegex: /^((?!.*?Skip).)*$/,6 }),7});8{9 "scripts": {10 },11 "devDependencies": {12 }13}
Using AI Code Generation
1import { snapshotTest } from 'storybook-root-snapshot';2import { storiesOf } from '@storybook/react';3import { withInfo } from '@storybook/addon-info';4import { withKnobs } from '@storybook/addon-knobs';5storiesOf('MyComponent', module)6 .addDecorator(withKnobs)7 .addDecorator(withInfo)8 .add('with some emoji', () => <MyComponent />, {9 info: {10 },11 })12 .add('with some emoji and snapshotTest', () => snapshotTest(<MyComponent />));13import { configure } from '@storybook/react';14import { setOptions } from '@storybook/addon-options';15import { setDefaults } from '@storybook/addon-info';16setDefaults({17});18setOptions({
Using AI Code Generation
1import initStoryshots from '@storybook/addon-storyshots';2import { snapshotTest } from './storybook-root-snapshot';3initStoryshots({4});5import { shallow } from 'enzyme';6import React from 'react';7import renderer from 'react-test-renderer';8export const snapshotTest = ({ story, context }) => {9 const shallowComponent = shallow(story(context));10 const tree = renderer.create(shallowComponent).toJSON();11 expect(tree).toMatchSnapshot();12};13const tree = renderer.create(mount(story(context)).get(0)).toJSON();
Using AI Code Generation
1import initStoryshots from '@storybook/addon-storyshots';2import { snapshotTest } from 'storybook-root-screenshot';3initStoryshots({4 test: snapshotTest({5 }),6});
Using AI Code Generation
1import { snapshotTest } from "storybook-root-snapshot";2import stories from "./stories";3snapshotTest(stories);4import { storiesOf } from "@storybook/react";5const stories = storiesOf("HelloWorld", module).add("HelloWorld", () => (6));7export default stories;8"jest": {9 }10"mocha": {11 }
Using AI Code Generation
1import { snapshotTest } from 'storybook-root'2import React from 'react'3import { storiesOf } from '@storybook/react'4import { Button } from 'antd'5import 'antd/dist/antd.css'6const stories = storiesOf('Button', module)7stories.add('Test button', () => {8 return snapshotTest(<Button>Test</Button>)9})10import React from 'react'11import { mount } from 'enzyme'12import { Button } from 'antd'13import 'antd/dist/antd.css'14import { snapshotTest } from 'storybook-root'15describe('Test button', () => {16 it('should render correctly', () => {17 const wrapper = mount(<Button>Test</Button>)18 expect(wrapper).toMatchSnapshot()19 })20})21import { configure, addDecorator } from '@storybook/react'22import { withInfo } from '@storybook/addon-info'23import { withKnobs } from '@storybook/addon-knobs'24import { withTests } from '@storybook/addon-jest'25import results from '../test.test'26import { snapshotTest } from 'storybook-root'27addDecorator(withInfo)28addDecorator(withKnobs)29addDecorator(withTests({ results }))30addDecorator(snapshotTest)31const req = require.context('../src', true, /\.stories\.js$/)32function loadStories() {33 req.keys().forEach(filename => req(filename))34}35configure(loadStories, module)36import '@storybook/addon-actions/register'37import '@storybook/addon-links/register'38import '@storybook/addon-knobs/register'39import '@storybook/addon-info/register'40import '@storybook/addon-jest/register'41import 'storybook-root/register'42const path = require('path')43module.exports = async ({ config, mode }) => {44 config.module.rules.push({45 {46 },47 {48 },49 include: path.resolve(__dirname, '../'),50 })51}52module.exports = {53 moduleNameMapper: {
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!!