Best JavaScript code snippet using storybook-root
Form.spec.js
Source:Form.spec.js
1/* eslint react/no-multi-comp:0 */2import React, { Component } from 'react'3import { createSpy } from 'expect'4import { Provider } from 'react-redux'5import { combineReducers as plainCombineReducers, createStore } from 'redux'6import { combineReducers as immutableCombineReducers } from 'redux-immutablejs'7import TestUtils from 'react-dom/test-utils'8import createReduxForm from '../createReduxForm'9import createReducer from '../createReducer'10import createField from '../createField'11import Form from '../Form'12import plain from '../structure/plain'13import plainExpectations from '../structure/plain/expectations'14import immutable from '../structure/immutable'15import immutableExpectations from '../structure/immutable/expectations'16import addExpectations from './addExpectations'17import SubmissionError from '../SubmissionError'18import actions from '../actions'19const {20 change,21 clearSubmit,22 setSubmitFailed,23 setSubmitSucceeded,24 submit,25 touch,26 updateSyncErrors27} = actions28const propsAtNthRender = (componentSpy, callNumber) =>29 componentSpy.calls[callNumber].arguments[0]30const describeForm = (name, structure, combineReducers, expect) => {31 const reduxForm = createReduxForm(structure)32 const Field = createField(structure)33 const reducer = createReducer(structure)34 const { fromJS, getIn } = structure35 const makeStore = (initial = {}, logger) => {36 const reducers = { form: reducer }37 if (logger) {38 reducers.logger = logger39 }40 return createStore(combineReducers(reducers), fromJS({ form: initial }))41 }42 describe(name, () => {43 it('should throw an error if not in ReduxForm', () => {44 expect(() => {45 TestUtils.renderIntoDocument(46 <div>47 <Form onSubmit={() => {}} />48 </div>49 )50 }).toThrow(/must be inside a component decorated with reduxForm/)51 })52 it('should output a <form> element with all props mapped', () => {53 const store = makeStore({54 testForm: {55 values: {56 foo: 4257 }58 }59 })60 const onSubmit = createSpy()61 class TestForm extends Component {62 render() {63 return (64 <Form65 onSubmit={onSubmit}66 action="/save"67 method="post"68 target="_blank"69 rel="noopener noreferrer"70 >71 <Field name="foo" component="input" />72 </Form>73 )74 }75 }76 const DecoratedTestForm = reduxForm({ form: 'testForm' })(TestForm)77 const dom = TestUtils.renderIntoDocument(78 <Provider store={store}>79 <DecoratedTestForm />80 </Provider>81 )82 expect(onSubmit).toNotHaveBeenCalled()83 const tag = TestUtils.findRenderedDOMComponentWithTag(dom, 'form')84 // 𤢠This line is DISGUSTING!! Is there a better way to get the props on the <form> ??85 const props = tag[Object.keys(tag)[0]]._currentElement.props86 expect(props.onSubmit).toBe(onSubmit)87 expect(props.action).toBe('/save')88 expect(props.method).toBe('post')89 expect(props.target).toBe('_blank')90 })91 it('should call the onSubmit given to <Form> when instance API submit() is called', () => {92 const store = makeStore({93 testForm: {94 values: {95 foo: 4296 }97 }98 })99 const onSubmit = createSpy().andReturn(7)100 class TestForm extends Component {101 render() {102 return (103 <Form onSubmit={this.props.handleSubmit(onSubmit)}>104 <Field name="foo" component="input" />105 </Form>106 )107 }108 }109 const DecoratedTestForm = reduxForm({ form: 'testForm' })(TestForm)110 const dom = TestUtils.renderIntoDocument(111 <Provider store={store}>112 <DecoratedTestForm />113 </Provider>114 )115 const decoratedForm = TestUtils.findRenderedComponentWithType(116 dom,117 DecoratedTestForm118 )119 expect(onSubmit).toNotHaveBeenCalled()120 const result = decoratedForm.submit()121 expect(result).toBe(7)122 expect(onSubmit).toHaveBeenCalled()123 expect(onSubmit.calls.length).toBe(1)124 expect(onSubmit.calls[0].arguments[0]).toEqualMap({ foo: 42 })125 expect(onSubmit.calls[0].arguments[1]).toBeA('function')126 expect(onSubmit.calls[0].arguments[2].values).toEqualMap({ foo: 42 })127 })128 it('should call the onSubmit given to <Form> when SUBMIT action is dispatched', () => {129 const store = makeStore({130 testForm: {131 values: {132 foo: 42133 }134 }135 })136 const onSubmit = createSpy()137 class TestForm extends Component {138 render() {139 return (140 <Form onSubmit={this.props.handleSubmit(onSubmit)}>141 <Field name="foo" component="input" />142 </Form>143 )144 }145 }146 const DecoratedTestForm = reduxForm({ form: 'testForm' })(TestForm)147 TestUtils.renderIntoDocument(148 <Provider store={store}>149 <DecoratedTestForm />150 </Provider>151 )152 expect(onSubmit).toNotHaveBeenCalled()153 store.dispatch(submit('testForm'))154 expect(onSubmit).toHaveBeenCalled()155 expect(onSubmit.calls.length).toBe(1)156 expect(onSubmit.calls[0].arguments[0]).toEqualMap({ foo: 42 })157 expect(onSubmit.calls[0].arguments[1]).toBeA('function')158 expect(onSubmit.calls[0].arguments[2].values).toEqualMap({ foo: 42 })159 })160 it('should properly handle submission errors', () => {161 const store = makeStore({162 testForm: {163 values: {164 foo: 42165 }166 }167 })168 const onSubmit = createSpy().andThrow(169 new SubmissionError({ _error: 'Invalid' })170 )171 const formRender = createSpy()172 class TestForm extends Component {173 render() {174 formRender(this.props)175 return (176 <Form onSubmit={this.props.handleSubmit(onSubmit)}>177 <Field name="foo" component="input" />178 </Form>179 )180 }181 }182 const DecoratedTestForm = reduxForm({ form: 'testForm' })(TestForm)183 const dom = TestUtils.renderIntoDocument(184 <Provider store={store}>185 <DecoratedTestForm />186 </Provider>187 )188 expect(formRender).toHaveBeenCalled()189 expect(formRender.calls.length).toBe(1)190 const decoratedForm = TestUtils.findRenderedComponentWithType(191 dom,192 DecoratedTestForm193 )194 expect(onSubmit).toNotHaveBeenCalled()195 decoratedForm.submit()196 expect(onSubmit).toHaveBeenCalled()197 expect(onSubmit.calls.length).toBe(1)198 expect(onSubmit.calls[0].arguments[0]).toEqualMap({ foo: 42 })199 expect(onSubmit.calls[0].arguments[1]).toBeA('function')200 expect(onSubmit.calls[0].arguments[2].values).toEqualMap({ foo: 42 })201 expect(formRender.calls.length).toBe(3)202 expect(formRender.calls[2].arguments[0].error).toBe('Invalid')203 })204 it('should NOT submit a form with sync validation errors', () => {205 const logger = createSpy((state = {}) => state).andCallThrough()206 const store = makeStore({}, logger)207 const inputRender = createSpy(props =>208 <input {...props.input} />209 ).andCallThrough()210 const onSubmit = createSpy()211 const formRender = createSpy()212 const validate = values => {213 const errors = {}214 if (!getIn(values, 'foo')) {215 errors.foo = 'Required'216 }217 return errors218 }219 class TestForm extends Component {220 render() {221 formRender(this.props)222 return (223 <Form onSubmit={this.props.handleSubmit(onSubmit)}>224 <Field name="foo" component={inputRender} />225 </Form>226 )227 }228 }229 const DecoratedTestForm = reduxForm({230 form: 'testForm',231 validate232 })(TestForm)233 TestUtils.renderIntoDocument(234 <Provider store={store}>235 <DecoratedTestForm />236 </Provider>237 )238 let callIndex = logger.calls.length239 // form renders before sync validation and then again with invalid flag240 expect(formRender.calls.length).toBe(2)241 expect(propsAtNthRender(formRender, 0).invalid).toBe(false)242 expect(propsAtNthRender(formRender, 1).invalid).toBe(true)243 expect(propsAtNthRender(formRender, 1).submitFailed).toBe(false)244 // try to submit invalid form via dispatching submit action245 store.dispatch(submit('testForm'))246 // check that submit action was dispatched247 expect(logger.calls[callIndex++].arguments[1]).toEqual(submit('testForm'))248 // check that clear submit action was dispatched249 expect(logger.calls[callIndex++].arguments[1]).toEqual(250 clearSubmit('testForm')251 )252 // check that touch action was dispatched253 expect(logger.calls[callIndex++].arguments[1]).toEqual(254 touch('testForm', 'foo')255 )256 // check that setSubmitFailed action was dispatched257 expect(logger.calls[callIndex++].arguments[1]).toEqual(258 setSubmitFailed('testForm', 'foo')259 )260 // form rerendered twice, once with submit trigger, and then after submit failure261 expect(formRender.calls.length).toBe(4)262 expect(propsAtNthRender(formRender, 3).invalid).toBe(true)263 expect(propsAtNthRender(formRender, 3).submitFailed).toBe(true)264 // update input265 inputRender.calls[0].arguments[0].input.onChange('hello')266 // check that change action was dispatched267 expect(logger.calls[callIndex++].arguments[1]).toEqual(268 change('testForm', 'foo', 'hello', false, false)269 )270 // check that updateSyncErrors action was dispatched271 expect(logger.calls[callIndex++].arguments[1]).toEqual(272 updateSyncErrors('testForm', {})273 )274 // rerendered once to flip dirty flag, and again to flip invalid flag275 expect(formRender.calls.length).toBe(6)276 expect(propsAtNthRender(formRender, 3).dirty).toBe(false)277 expect(propsAtNthRender(formRender, 4).dirty).toBe(true)278 expect(propsAtNthRender(formRender, 4).invalid).toBe(true)279 expect(propsAtNthRender(formRender, 5).invalid).toBe(false)280 expect(propsAtNthRender(formRender, 5).submitFailed).toBe(true)281 // dispatch submit action on now valid form282 store.dispatch(submit('testForm'))283 // check that submit action was dispatched284 expect(logger.calls[callIndex++].arguments[1]).toEqual(submit('testForm'))285 // check that clear submit action was dispatched286 expect(logger.calls[callIndex++].arguments[1]).toEqual(287 clearSubmit('testForm')288 )289 // check that touch action was dispatched290 expect(logger.calls[callIndex++].arguments[1]).toEqual(291 touch('testForm', 'foo')292 )293 // check that submit succeeded action was dispatched294 expect(logger.calls[callIndex++].arguments[1]).toEqual(295 setSubmitSucceeded('testForm')296 )297 // check no additional actions dispatched298 expect(logger.calls.length).toBe(callIndex)299 expect(onSubmit).toHaveBeenCalled()300 expect(onSubmit.calls.length).toBe(1)301 expect(onSubmit.calls[0].arguments[0]).toEqualMap({ foo: 'hello' })302 expect(onSubmit.calls[0].arguments[1]).toBeA('function')303 expect(onSubmit.calls[0].arguments[2].values).toEqualMap({ foo: 'hello' })304 })305 })306}307describeForm(308 'Form.plain',309 plain,310 plainCombineReducers,311 addExpectations(plainExpectations)312)313describeForm(314 'Form.immutable',315 immutable,316 immutableCombineReducers,317 addExpectations(immutableExpectations)...
SolidInput.test.js
Source:SolidInput.test.js
1import React from 'react';2import 'jest-dom/extend-expect';3import {render, fireEvent, cleanup} from '@testing-library/react';4import SolidInput from '../index'5afterEach(cleanup);6// SolidInput.handleInputChange uses a setTimeout to avoid onSubmit calls before typing is finished7// Use fake timers to allow us to skip the wait and fetch output immediately.8jest.useFakeTimers();9let defaultProps = {10 inputKey: 'test-key',11 onSubmit: () => {},12 onDuplicate: () => {},13 onRemove: () => {},14 onNext: () => {},15 isDataValid: () => {},16 removeMayBeDisabled: true,17};18describe('<SolidInput/>', () => {19 it('handles input change events correctly', () => {20 const onSubmit = jest.fn();21 const {getByLabelText} = render(<SolidInput22 {...defaultProps}23 onSubmit={onSubmit}24 />);25 const emptySolid = {26 width: null,27 length: null,28 height: null29 };30 const input = getByLabelText('Solid input');31 fireEvent.change(input, {target: {value: 'a'}});32 expect(onSubmit).not.toBeCalled();33 jest.runAllTimers();34 expect(onSubmit).toBeCalled();35 expect(onSubmit.mock.calls[0][0]).toBe('test-key', null);36 expect(onSubmit.mock.calls[0][1]).toEqual(emptySolid);37 const expectedOnSubmitArgs = [38 ['1,1,', emptySolid],39 ['1,1,description', emptySolid],40 ['1,+1,1', emptySolid],41 ['1,"1",1', emptySolid],42 ['1,1,1', {width: 1, length: 1, height: 1, description: undefined}],43 ['1 , 1, 1', {width: 1, length: 1, height: 1, description: undefined}],44 ['1, 1, 1,', {width: 1, length: 1, height: 1, description: undefined}],45 ['2.1, 1, 0,', {width: 2.1, length: 1, height: 0, description: undefined}],46 ['1, 1, 1, description', {width: 1, length: 1, height: 1, description: 'description'}],47 ['1, 1, 1, description, 1', {width: 1, length: 1, height: 1, description: 'description, 1'}],48 ];49 for( let i=0, len = expectedOnSubmitArgs.length; i < len; i++){50 fireEvent.change(input, {target: {value: expectedOnSubmitArgs[i][0]}});51 jest.runAllTimers();52 expect(onSubmit.mock.calls[i+1][1]).toEqual(expectedOnSubmitArgs[i][1]);53 }54 });55 it('handles non-enter keypress correctly', () => {56 const onSubmit = jest.fn(),57 onNext = jest.fn();58 const {getByLabelText} = render(<SolidInput59 {...defaultProps}60 onSubmit={onSubmit}61 onNext={onNext}62 />);63 const input = getByLabelText('Solid input');64 // The typing timeout shouldn't be affected by non-enter key-presses65 fireEvent.change(input, {target: {value: '1,1,1'}});66 fireEvent.keyPress(input, { key: 'a', code: 1, charCode: 1 });67 expect(onSubmit).not.toBeCalled();68 jest.runAllTimers();69 expect(onSubmit).toBeCalled();70 expect(onNext).not.toBeCalled();71 });72 it('handles enter keypress correctly', () => {73 const onSubmit = jest.fn(),74 onNext = jest.fn();75 const {getByLabelText} = render(<SolidInput76 {...defaultProps}77 onSubmit={onSubmit}78 onNext={onNext}79 />);80 const input = getByLabelText('Solid input');81 fireEvent.change(input, {target: {value: '1,1,1'}});82 fireEvent.keyPress(input, { key: 'Enter', code: 13, charCode: 13 });83 expect(onSubmit).toBeCalled();84 expect(onNext).toBeCalled();85 expect(onSubmit.mock.calls[0][1]).toEqual({width: 1, length: 1, height: 1, description: undefined});86 });87 it('handles remove correctly', () => {88 const onSubmit = jest.fn(),89 onRemove = jest.fn();90 const {getByLabelText} = render(<SolidInput91 {...defaultProps}92 onSubmit={onSubmit}93 onRemove={onRemove}94 />);95 const input = getByLabelText('Solid input');96 const removeButton = getByLabelText('Delete item');97 fireEvent.change(input, {target: {value: '1,1,1'}});98 fireEvent.click(removeButton);99 expect(onSubmit).not.toBeCalled();100 expect(onRemove).toBeCalled();101 expect(input).toBeEmpty();102 });103 it('handles duplicate button click correctly', () => {104 const onDuplicate = jest.fn();105 const {getByLabelText} = render(<SolidInput106 {...defaultProps}107 onDuplicate={onDuplicate}108 />);109 const input = getByLabelText('Solid input');110 const duplicateButton = getByLabelText('Duplicate item');111 fireEvent.change(input, {target: {value: '1,1,1'}});112 fireEvent.click(duplicateButton);113 expect(input).toBeEmpty();114 });115 it('handles remove button state correctly', () => {116 const {getByLabelText} = render(<SolidInput117 {...defaultProps}118 removeMayBeDisabled={false}119 />);120 expect(getByLabelText('Delete item')).toBeEnabled();121 cleanup();122 render(<SolidInput123 {...defaultProps}124 removeMayBeDisabled={true}125 />);126 expect(getByLabelText('Delete item')).toBeDisabled();127 fireEvent.change(getByLabelText('Solid input'), {target:{value:'test'}});128 expect(getByLabelText('Delete item')).toBeEnabled();129 });...
Piano.js
Source:Piano.js
1import React, { Component } from 'react'2import PianoKey from './PianoKey'3import './../css/piano.css'4export class Piano extends Component {5 render() {6 //piano layout7 const piano = [8 <PianoKey parent={this.props.parent} onSubmit={this.props.onSubmit} note='C/B#' className='white'/>,9 <PianoKey parent={this.props.parent} onSubmit={this.props.onSubmit} note='C#/Db' className='black'/>,10 <PianoKey parent={this.props.parent} onSubmit={this.props.onSubmit} note='D' className='white'/>,11 <PianoKey parent={this.props.parent} onSubmit={this.props.onSubmit} note='D#/Eb' className='black'/>,12 <PianoKey parent={this.props.parent} onSubmit={this.props.onSubmit} note='E/Fb' className='white'/>,13 <PianoKey parent={this.props.parent} onSubmit={this.props.onSubmit} note='F/E#' className='white'/>,14 <PianoKey parent={this.props.parent} onSubmit={this.props.onSubmit} note='F#/Gb' className='black'/>,15 <PianoKey parent={this.props.parent} onSubmit={this.props.onSubmit} note='G' className='white'/>,16 <PianoKey parent={this.props.parent} onSubmit={this.props.onSubmit} note='G#/Ab' className='black'/>,17 <PianoKey parent={this.props.parent} onSubmit={this.props.onSubmit} note='A' className='white'/>,18 <PianoKey parent={this.props.parent} onSubmit={this.props.onSubmit} note='A#/Bb' className='black'/>,19 <PianoKey parent={this.props.parent} onSubmit={this.props.onSubmit} note='B/Cb' className='white'/>20 ]21 return (22 <div className='piano'>23 {piano}24 </div>25 )26 }27}...
Using AI Code Generation
1window.storybookRoot.onSubmit = function() {2 console.log("onSubmit called");3 return true;4};5window.storybookRoot.onReset = function() {6 console.log("onReset called");7 return true;8};9window.storybookRoot.onSubmit = function() {10 console.log("onSubmit called");11 return true;12};13window.storybookRoot.onReset = function() {14 console.log("onReset called");15 return true;16};17window.storybookRoot.onSubmit = function() {18 console.log("onSubmit called");19 return true;20};21window.storybookRoot.onReset = function() {22 console.log("onReset called");23 return true;24};25window.storybookRoot.onSubmit = function() {26 console.log("onSubmit called");27 return true;28};29window.storybookRoot.onReset = function() {30 console.log("onReset called");31 return true;32};33window.storybookRoot.onSubmit = function() {34 console.log("onSubmit called");35 return true;36};37window.storybookRoot.onReset = function() {38 console.log("onReset called");39 return true;40};41window.storybookRoot.onSubmit = function() {42 console.log("onSubmit called");43 return true;44};45window.storybookRoot.onReset = function() {46 console.log("onReset called");47 return true;48};49window.storybookRoot.onSubmit = function() {50 console.log("onSubmit called");51 return true;52};53window.storybookRoot.onReset = function() {54 console.log("onReset called");55 return true;56};
Using AI Code Generation
1import { onSubmit } from 'storybook-root'2onSubmit('some data')3import { onSubmit } from 'test'4onSubmit('some data')5import * as test from 'test'6test.onSubmit('some data')7import * as test from 'test.js'8test.onSubmit('some data')9import * as test from './test'10test.onSubmit('some data')11import * as test from './test.js'12test.onSubmit('some data')13import * as test from '../test'14test.onSubmit('some data')15import * as test from '../test.js'16test.onSubmit('some data')17import * as test from './src/test'18test.onSubmit('some data')
Using AI Code Generation
1 const handleSubmit = (e) => {2 e.preventDefault();3 console.log('submit');4 };5 return <form onSubmit={handleSubmit}>test</form>;6};7export const Default = Template.bind({});8Default.args = {9};10export const Disabled = Template.bind({});11Disabled.args = {12};13export const Loading = Template.bind({});14Loading.args = {15};16export const LoadingDisabled = Template.bind({});17LoadingDisabled.args = {18};19export const DefaultWithLabel = Template.bind({});20DefaultWithLabel.args = {21};22export const DisabledWithLabel = Template.bind({});23DisabledWithLabel.args = {24};25export const LoadingWithLabel = Template.bind({});26LoadingWithLabel.args = {27};28export const LoadingDisabledWithLabel = Template.bind({});29LoadingDisabledWithLabel.args = {30};31export const DefaultWithLabelAndDescription = Template.bind({});32DefaultWithLabelAndDescription.args = {33};34export const DisabledWithLabelAndDescription = Template.bind({});35DisabledWithLabelAndDescription.args = {36};37export const LoadingWithLabelAndDescription = Template.bind({});38LoadingWithLabelAndDescription.args = {39};40export const LoadingDisabledWithLabelAndDescription = Template.bind({});41LoadingDisabledWithLabelAndDescription.args = {42};43export const DefaultWithLabelAndDescriptionAndError = Template.bind({});44DefaultWithLabelAndDescriptionAndError.args = {45};46export const DisabledWithLabelAndDescriptionAndError = Template.bind({});
Using AI Code Generation
1const root = document.getElementById('storybook-root');2const form = root.querySelector('form');3form.submit();4const root = document.getElementById('storybook-root');5const form = root.querySelector('form');6form.submit();7const root = document.getElementById('storybook-root');8const form = root.querySelector('form');9form.submit();10const root = document.getElementById('storybook-root');11const form = root.querySelector('form');12form.submit();13const root = document.getElementById('storybook-root');14const form = root.querySelector('form');15form.submit();16const root = document.getElementById('storybook-root');17const form = root.querySelector('form');18form.submit();19const root = document.getElementById('storybook-root');20const form = root.querySelector('form');21form.submit();22const root = document.getElementById('storybook-root');23const form = root.querySelector('form');24form.submit();25const root = document.getElementById('storybook-root');26const form = root.querySelector('form');27form.submit();28const root = document.getElementById('storybook-root');29const form = root.querySelector('form');30form.submit();
Using AI Code Generation
1import React from 'react';2import { storiesOf } from '@storybook/react';3import { action } from '@storybook/addon-actions';4import { withInfo } from '@storybook/addon-info';5import { withKnobs, text, boolean, number } from '@storybook/addon-knobs';6import { withA11y } from '@storybook/addon-a11y';7import { withTests } from '@storybook/addon-jest';8import results from '../../../../.jest-test-results.json';9import Form from './Form';10import FormReadme from './Form.md';11import FormNotes from './Form.md';12storiesOf('forms/Form', module)13 .addDecorator(withKnobs)14 .addDecorator(15 withTests({16 })17 .add(18 withInfo({19 })(() => {20 const formSubmit = e => {21 e.preventDefault();22 action('formSubmit')(e);23 };24 return (25 <form onSubmit={formSubmit}>26 className={text('className', '')}27 formId={text('formId', 'storybook-form')}28 formName={text('formName', 'storybook-form')}29 formTitle={text('formTitle', 'Form Title')}30 formDescription={text('formDescription', 'Form Description')}31 formFields={text('formFields', 'Form Fields')}32 formSubmitBtnText={text('formSubmitBtnText', 'Submit')}33 formCancelBtnText={text('formCancelBtnText', 'Cancel')}34 formSubmit={formSubmit}35 formCancel={action('formCancel')}36 formStatus={text('formStatus', 'ready')}37 formStatusText={text('formStatusText', 'Form Status Text')}38 formStatusTextClassName={text(39 )}40 formSubmitBtnClassName={text(41 )}42 formCancelBtnClassName={
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!!