How to use nextCreate method in storybook-root

Best JavaScript code snippet using storybook-root

hooks.test.js

Source:hooks.test.js Github

copy

Full Screen

1import {2 FORCE_RE_RENDER,3 STORY_RENDERED,4 UPDATE_STORY_ARGS,5 RESET_STORY_ARGS,6 UPDATE_GLOBALS,7} from '@storybook/core-events';8import { addons } from '@storybook/addons';9import { defaultDecorateStory } from './decorators';10import {11 applyHooks,12 useEffect,13 useMemo,14 useCallback,15 useRef,16 useState,17 useReducer,18 useChannel,19 useParameter,20 useStoryContext,21 HooksContext,22 useArgs,23 useGlobals,24} from './hooks';25jest.mock('@storybook/client-logger', () => ({26 logger: { warn: jest.fn(), log: jest.fn() },27}));28const SOME_EVENT = 'someEvent';29let mockChannel;30let hooks;31let onSomeEvent;32let removeSomeEventListener;33beforeEach(() => {34 onSomeEvent = jest.fn();35 removeSomeEventListener = jest.fn();36 mockChannel = {37 emit: jest.fn(),38 on(event, callback) {39 switch (event) {40 case STORY_RENDERED:41 callback();42 break;43 case SOME_EVENT:44 onSomeEvent(event, callback);45 break;46 default:47 }48 },49 removeListener(event, callback) {50 if (event === SOME_EVENT) {51 removeSomeEventListener(event, callback);52 }53 },54 };55 hooks = new HooksContext();56 addons.setChannel(mockChannel);57});58const decorateStory = applyHooks(defaultDecorateStory);59const run = (storyFn, decorators = [], context) =>60 decorateStory(storyFn, decorators)({ ...context, hooks });61describe('Preview hooks', () => {62 describe('useEffect', () => {63 it('triggers the effect from story function', () => {64 const effect = jest.fn();65 run(() => {66 useEffect(effect);67 });68 expect(effect).toHaveBeenCalledTimes(1);69 });70 it('triggers the effect from decorator', () => {71 const effect = jest.fn();72 run(() => {}, [73 (storyFn) => {74 useEffect(effect);75 return storyFn();76 },77 ]);78 expect(effect).toHaveBeenCalledTimes(1);79 });80 it('triggers the effect from decorator if story call comes before useEffect', () => {81 const effect = jest.fn();82 run(() => {}, [83 (storyFn) => {84 const story = storyFn();85 useEffect(effect);86 return story;87 },88 ]);89 expect(effect).toHaveBeenCalledTimes(1);90 });91 it('retriggers the effect if no deps array is provided', () => {92 const effect = jest.fn();93 const storyFn = () => {94 useEffect(effect);95 };96 run(storyFn);97 run(storyFn);98 expect(effect).toHaveBeenCalledTimes(2);99 });100 it("doesn't retrigger the effect if empty deps array is provided", () => {101 const effect = jest.fn();102 const storyFn = () => {103 useEffect(effect, []);104 };105 run(storyFn);106 run(storyFn);107 expect(effect).toHaveBeenCalledTimes(1);108 });109 it("doesn't retrigger the effect from decorator if story has changed", () => {110 const effect = jest.fn();111 const decorator = (storyFn) => {112 useEffect(effect, []);113 return storyFn();114 };115 run(() => {}, [decorator]);116 run(() => {}, [decorator]);117 expect(effect).toHaveBeenCalledTimes(1);118 });119 it("doesn't retrigger the effect from decorator if story has changed and story call comes before useEffect", () => {120 const effect = jest.fn();121 const decorator = (storyFn) => {122 const story = storyFn();123 useEffect(effect, []);124 return story;125 };126 run(() => {}, [decorator]);127 run(() => {}, [decorator]);128 expect(effect).toHaveBeenCalledTimes(1);129 });130 it("doesn't retrigger the effect from if decorator calls story twice", () => {131 const effect = jest.fn();132 const story = () => {133 useEffect(effect, []);134 };135 const decorator = (storyFn) => {136 storyFn();137 return storyFn();138 };139 run(story, [decorator]);140 expect(effect).toHaveBeenCalledTimes(1);141 });142 it('retriggers the effect if some of the deps are changed', () => {143 const effect = jest.fn();144 let counter = 0;145 const storyFn = () => {146 useEffect(effect, [counter]);147 counter += 1;148 };149 run(storyFn);150 run(storyFn);151 expect(effect).toHaveBeenCalledTimes(2);152 });153 it("doesn't retrigger the effect if none of the deps are changed", () => {154 const effect = jest.fn();155 const storyFn = () => {156 useEffect(effect, [0]);157 };158 run(storyFn);159 run(storyFn);160 expect(effect).toHaveBeenCalledTimes(1);161 });162 it('performs cleanup when retriggering', () => {163 const destroy = jest.fn();164 const storyFn = () => {165 useEffect(() => destroy);166 };167 run(storyFn);168 run(storyFn);169 expect(destroy).toHaveBeenCalledTimes(1);170 });171 it("doesn't perform cleanup when keeping the current effect", () => {172 const destroy = jest.fn();173 const storyFn = () => {174 useEffect(() => destroy, []);175 };176 run(storyFn);177 run(storyFn);178 expect(destroy).not.toHaveBeenCalled();179 });180 it('performs cleanup when removing the decorator', () => {181 const destroy = jest.fn();182 run(() => {}, [183 (storyFn) => {184 useEffect(() => destroy);185 return storyFn();186 },187 ]);188 run(() => {});189 expect(destroy).toHaveBeenCalledTimes(1);190 });191 });192 describe('useChannel', () => {193 it('calls .on when rendering the decorator', () => {194 const handler = () => {};195 run(() => {}, [196 (storyFn) => {197 useChannel({198 [SOME_EVENT]: handler,199 });200 return storyFn();201 },202 ]);203 expect(onSomeEvent).toHaveBeenCalledTimes(1);204 expect(removeSomeEventListener).toHaveBeenCalledTimes(0);205 });206 it('calls .removeListener when removing the decorator', () => {207 const handler = () => {};208 run(() => {}, [209 (storyFn) => {210 useChannel({211 [SOME_EVENT]: handler,212 });213 return storyFn();214 },215 ]);216 expect(onSomeEvent).toHaveBeenCalledTimes(1);217 expect(removeSomeEventListener).toHaveBeenCalledTimes(0);218 run(() => {});219 expect(removeSomeEventListener).toHaveBeenCalledTimes(1);220 });221 });222 describe('useStoryContext', () => {223 it('returns current context', () => {224 const context = {};225 run(226 () => {227 expect(useStoryContext()).toEqual({ ...context, hooks });228 },229 [],230 context231 );232 });233 });234 describe('useParameter', () => {235 it('will pull value from storyStore', () => {236 run(237 () => {},238 [239 (storyFn) => {240 expect(useParameter('foo', 4)).toEqual(42);241 return storyFn();242 },243 ],244 { parameters: { foo: 42 } }245 );246 });247 it('will return default value', () => {248 run(249 () => {},250 [251 (storyFn) => {252 expect(useParameter('bar', 4)).toEqual(4);253 return storyFn();254 },255 ],256 { parameters: {} }257 );258 });259 it('will return undefined when no value is found', () => {260 run(261 () => {},262 [263 (storyFn) => {264 expect(useParameter('bar')).toBe(undefined);265 return storyFn();266 },267 ],268 { parameters: {} }269 );270 });271 });272 describe('useMemo', () => {273 it('performs the calculation', () => {274 let result;275 const nextCreate = jest.fn(() => 'foo');276 const storyFn = () => {277 result = useMemo(nextCreate, []);278 };279 run(storyFn);280 expect(nextCreate).toHaveBeenCalledTimes(1);281 expect(result).toBe('foo');282 });283 it('performs the calculation once if deps are unchanged', () => {284 let result;285 const nextCreate = jest.fn(() => 'foo');286 const storyFn = () => {287 result = useMemo(nextCreate, []);288 };289 run(storyFn);290 run(storyFn);291 expect(nextCreate).toHaveBeenCalledTimes(1);292 expect(result).toBe('foo');293 });294 it('performs the calculation again if deps are changed', () => {295 let result;296 let counter = 0;297 const nextCreate = jest.fn(() => counter);298 const storyFn = () => {299 counter += 1;300 result = useMemo(nextCreate, [counter]);301 };302 run(storyFn);303 run(storyFn);304 expect(nextCreate).toHaveBeenCalledTimes(2);305 expect(result).toBe(counter);306 });307 });308 describe('useCallback', () => {309 it('returns the callback', () => {310 let result;311 const callback = () => {};312 const storyFn = () => {313 result = useCallback(callback, []);314 };315 run(storyFn);316 expect(result).toBe(callback);317 });318 it('returns the previous callback reference if deps are unchanged', () => {319 const callbacks = [];320 const storyFn = () => {321 const callback = useCallback(() => {}, []);322 callbacks.push(callback);323 };324 run(storyFn);325 run(storyFn);326 expect(callbacks[0]).toBe(callbacks[1]);327 });328 it('creates new callback reference if deps are changed', () => {329 const callbacks = [];330 let counter = 0;331 const storyFn = () => {332 counter += 1;333 const callback = useCallback(() => {}, [counter]);334 callbacks.push(callback);335 };336 run(storyFn);337 run(storyFn);338 expect(callbacks[0]).not.toBe(callbacks[1]);339 });340 });341 describe('useRef', () => {342 it('attaches initial value', () => {343 let ref;344 const storyFn = () => {345 ref = useRef('foo');346 };347 run(storyFn);348 expect(ref.current).toBe('foo');349 });350 it('stores mutations', () => {351 let refValueFromSecondRender;352 let counter = 0;353 const storyFn = () => {354 counter += 1;355 const ref = useRef('foo');356 if (counter === 1) {357 ref.current = 'bar';358 } else {359 refValueFromSecondRender = ref.current;360 }361 };362 run(storyFn);363 run(storyFn);364 expect(refValueFromSecondRender).toBe('bar');365 });366 });367 describe('useState', () => {368 it('sets initial state', () => {369 let state;370 const storyFn = () => {371 [state] = useState('foo');372 };373 run(storyFn);374 expect(state).toBe('foo');375 });376 it('calculates initial state', () => {377 let state;378 const storyFn = () => {379 [state] = useState(() => 'foo');380 };381 run(storyFn);382 expect(state).toBe('foo');383 });384 it('performs synchronous state updates', () => {385 let state;386 let setState;387 const storyFn = jest.fn(() => {388 [state, setState] = useState('foo');389 if (state === 'foo') {390 setState('bar');391 }392 });393 run(storyFn);394 expect(storyFn).toHaveBeenCalledTimes(2);395 expect(state).toBe('bar');396 });397 it('triggers only the last effect when updating state synchronously', () => {398 const effects = [jest.fn(), jest.fn()];399 const storyFn = jest.fn(() => {400 const [effectIndex, setEffectIndex] = useState(0);401 useEffect(effects[effectIndex], [effectIndex]);402 if (effectIndex === 0) {403 setEffectIndex(1);404 }405 });406 run(storyFn);407 expect(effects[0]).not.toHaveBeenCalled();408 expect(effects[1]).toHaveBeenCalledTimes(1);409 });410 it('performs synchronous state updates with updater function', () => {411 let state;412 let setState;413 const storyFn = jest.fn(() => {414 [state, setState] = useState(0);415 if (state < 3) {416 setState((prevState) => prevState + 1);417 }418 });419 run(storyFn);420 expect(storyFn).toHaveBeenCalledTimes(4);421 expect(state).toBe(3);422 });423 it('performs asynchronous state updates', () => {424 let state;425 let setState;426 const storyFn = jest.fn(() => {427 [state, setState] = useState('foo');428 });429 run(storyFn);430 setState('bar');431 expect(mockChannel.emit).toHaveBeenCalledWith(FORCE_RE_RENDER);432 run(storyFn);433 expect(state).toBe('bar');434 });435 });436 describe('useReducer', () => {437 it('sets initial state', () => {438 let state;439 const storyFn = () => {440 [state] = useReducer(() => 'bar', 'foo');441 };442 run(storyFn);443 expect(state).toBe('foo');444 });445 it('calculates initial state', () => {446 let state;447 const storyFn = () => {448 [state] = useReducer(449 () => 'bar',450 'foo',451 (arg) => arg452 );453 };454 run(storyFn);455 expect(state).toBe('foo');456 });457 it('performs synchronous state updates', () => {458 let state;459 let dispatch;460 const storyFn = jest.fn(() => {461 [state, dispatch] = useReducer((prevState, action) => {462 switch (action) {463 case 'INCREMENT':464 return prevState + 1;465 default:466 return prevState;467 }468 }, 0);469 if (state < 3) {470 dispatch('INCREMENT');471 }472 });473 run(storyFn);474 expect(storyFn).toHaveBeenCalledTimes(4);475 expect(state).toBe(3);476 });477 it('performs asynchronous state updates', () => {478 let state;479 let dispatch;480 const storyFn = jest.fn(() => {481 [state, dispatch] = useReducer((prevState, action) => {482 switch (action) {483 case 'INCREMENT':484 return prevState + 1;485 default:486 return prevState;487 }488 }, 0);489 });490 run(storyFn);491 dispatch('INCREMENT');492 expect(mockChannel.emit).toHaveBeenCalledWith(FORCE_RE_RENDER);493 run(storyFn);494 expect(state).toBe(1);495 });496 });497 describe('useArgs', () => {498 it('will pull args from context', () => {499 run(500 () => {},501 [502 (storyFn) => {503 expect(useArgs()[0]).toEqual({ a: 'b' });504 return storyFn();505 },506 ],507 { args: { a: 'b' } }508 );509 });510 it('will emit UPDATE_STORY_ARGS when called', () => {511 run(512 () => {},513 [514 (storyFn) => {515 useArgs()[1]({ a: 'b' });516 expect(mockChannel.emit).toHaveBeenCalledWith(UPDATE_STORY_ARGS, {517 storyId: '1',518 updatedArgs: { a: 'b' },519 });520 return storyFn();521 },522 ],523 { id: '1', args: {} }524 );525 });526 it('will emit RESET_STORY_ARGS when called', () => {527 run(528 () => {},529 [530 (storyFn) => {531 useArgs()[2](['a']);532 expect(mockChannel.emit).toHaveBeenCalledWith(RESET_STORY_ARGS, {533 storyId: '1',534 argNames: ['a'],535 });536 useArgs()[2]();537 expect(mockChannel.emit).toHaveBeenCalledWith(RESET_STORY_ARGS, {538 storyId: '1',539 });540 return storyFn();541 },542 ],543 { id: '1', args: {} }544 );545 });546 });547 describe('useGlobals', () => {548 it('will pull globals from context', () => {549 run(550 () => {},551 [552 (storyFn) => {553 expect(useGlobals()[0]).toEqual({ a: 'b' });554 return storyFn();555 },556 ],557 { globals: { a: 'b' } }558 );559 });560 it('will emit UPDATE_GLOBALS when called', () => {561 run(562 () => {},563 [564 (storyFn) => {565 useGlobals()[1]({ a: 'b' });566 expect(mockChannel.emit).toHaveBeenCalledWith(UPDATE_GLOBALS, { globals: { a: 'b' } });567 return storyFn();568 },569 ],570 { globals: {} }571 );572 });573 });...

Full Screen

Full Screen

main.js

Source:main.js Github

copy

Full Screen

1const HEIGHT = 600, WIDTH = 400;2const OBSTACLE_WIDTH = 100;3let STOP = false;4const GRAVITY = 900.0;5const COINS = document.createElement('img');COINS.src='src/gfx/coins.png';6const EGGS = document.createElement('img');EGGS.src='src/gfx/eggs.png';7const MOAI = document.createElement('img');MOAI.src='src/gfx/moai.png';8const DRAGON = document.createElement('img');DRAGON.src='src/gfx/dragon.png';9class Observer {10 constructor(){11 this.callbacks = {};12 }13 observe(key, fn) {14 if(!(key in this.callbacks))15 this.callbacks[key] = [];16 this.callbacks[key].push(fn);17 }18 notify(key, value) {19 if(key in this.callbacks)20 for(let fn of this.callbacks[key])21 fn(key, value);22 }23}24const SCALE = 4;25class Dragon {26 constructor() {27 this.x = 0;28 this.y = 300;29 this.speed = 100;30 this.vy = 200.0;31 this.hasPhysic = false;32 this.kind = Math.floor(5*Math.random());33 }34 flap() {35 this.vy = 400.0;36 }37 update(elapsed) {38 this.x += 0.001 * elapsed * this.speed;39 if(this.hasPhysic) {40 this.y -= 0.001 * elapsed * this.vy;41 this.vy -= 0.001 * elapsed * GRAVITY;42 }43 }44 draw(ctx, offset, timestamp) {45 let frame = Math.floor(4*timestamp/1000) % 2;46 ctx.drawImage(DRAGON, 350*this.kind, frame*240, 350, 240, this.x - offset - 175/SCALE, this.y - 120/SCALE, 350/SCALE, 240/SCALE);47 }48}49class Obstacle {50 constructor(x, h, orientation) {51 this.x = x;52 this.h = h;53 this.orientation = orientation;54 }55 draw(ctx, offset) {56 if(-OBSTACLE_WIDTH < this.x - offset && this.x - offset < WIDTH+OBSTACLE_WIDTH) {57 if(this.orientation == 'top') {58 ctx.fillStyle = 'black';59 ctx.fillRect(this.x - OBSTACLE_WIDTH/2 - offset, 0, OBSTACLE_WIDTH, this.h);60 } else if(this.orientation == 'down') {61 ctx.fillStyle = 'black';62 ctx.fillRect(this.x - OBSTACLE_WIDTH/2 - offset, HEIGHT - this.h, OBSTACLE_WIDTH, this.h);63 }64 }65 }66 hasCollision(x, y) {67 if(this.x - OBSTACLE_WIDTH / 2 <= x && x <= this.x + OBSTACLE_WIDTH / 2 ) {68 if(this.orientation == 'top')69 return y <= this.h;70 return y >= HEIGHT - this.h;71 }72 return false;73 }74 doCollision(world) {75 world.dragon.dead = true;76 world.o.notify('dead', true);77 }78}79class Coin {80 constructor(x, y) {81 this.x = x;82 this.y = y;83 this.collected = false;84 }85 draw(ctx, offset, timestamp) {86 if(!this.collected) {87 let frame = Math.floor(6.0 * timestamp / 1000.0) % 6;88 ctx.drawImage(COINS, 0, frame * 41, 40, 41, this.x - offset - 20, this.y - 21, 40, 41);89 }90 }91 hasCollision(x, y){92 return Math.pow(this.x-x, 2.0)+Math.pow(this.y-y, 2.0)<Math.pow(30, 2.0);93 }94 doCollision(world) {95 if(!this.collected) {96 this.collected = true;97 world.score += 5;98 world.o.notify('score', world.score);99 }100 }101}102class Egg {103 constructor(x, y) {104 this.x = x;105 this.y = y;106 this.collected = false;107 this.type = Math.floor(9 * Math.random());108 }109 draw(ctx, offset, timestamp) {110 if(!this.collected) {111 let frame = Math.floor(6.0 * timestamp / 1000.0) % 6;112 ctx.drawImage(EGGS, 96*this.type, 0, 96, 96, this.x - offset - 48, this.y - 48, 96, 96);113 }114 }115 hasCollision(x, y){116 return Math.pow(this.x-x, 2.0)+Math.pow(this.y-y, 2.0)<Math.pow(40, 2.0);117 }118 doCollision(world) {119 if(!this.collected) {120 this.collected = true;121 world.eggs += 1122 world.score += 50;123 world.o.notify('eggs', world.eggs);124 world.o.notify('score', world.score);125 }126 }127}128class Moai {129 constructor(x) {130 this.x = x;131 }132 draw(ctx, offset, timestamp) {133 ctx.drawImage(MOAI, 0, 0, 487, 600, this.x - offset - 244, 40, 487, 600);134 }135 hasCollision() {136 return false;137 }138 doCollision(){}139}140class World {141 constructor() {142 this.items = [];143 this.score = 0; 144 this.eggs = 3; // number of lives145 this.level = 1;146 this.nextCreate = -90;147 this.prices = [];148 this.createdObstacles = 0;149 let canvas = document.querySelector('canvas');150 this.ctx = canvas.getContext('2d');151 canvas.addEventListener('click', (event) => this.dragon.flap());152 document.addEventListener('keypress', (event) => this.dragon.flap());153 this.last_timestamp = 0;154 this.dragon = new Dragon();155 this.o = new Observer();156 this.o.observe('score', (key, value) => {157 document.querySelector('#score').innerText = (''+value).padStart(4, '0');158 });159 this.o.observe('eggs', (key, value) => {160 document.querySelector('#eggs').innerText = value;161 })162 this.o.observe('level', (key, value) => {163 document.querySelector('#level').innerText = 'Level ' + value;164 });165 this.o.notify('score', this.score);166 this.o.notify('eggs', this.eggs);167 this.o.notify('level', this.level);168 this.o.observe('dead', (key, value) => {169 if(this.eggs > 0) {170 this.eggs -= 1;171 this.o.notify('eggs', this.eggs);172 alert("You have died, but you can respawn from colorfull egg :)")173 this.reset();174 } else {175 STOP = true;176 alert("You have completely died before finding rabbit :'(")177 }178 })179 }180 createObstacle(height, hasItem, hasBonus) {181 let x = this.nextCreate + WIDTH + World.SPACING / 2;182 if(this.createdObstacles < 2*this.level) {183 this.createdObstacles += 1;184 let h = Math.floor(Math.random() * (HEIGHT - 100 - height));185 console.log('Create new at:', x, h);186 this.items.push(new Obstacle(x, h, 'top'));187 this.items.push(new Obstacle(x, HEIGHT - height - h, 'down'));188 if(hasBonus)189 this.items.push(new Egg(x, height + h - 30))190 if(hasItem)191 this.items.push(new Coin(x + World.SPACING / 2, Math.floor(Math.random()*(HEIGHT - 80)) + 40));192 this.prices.push(x + OBSTACLE_WIDTH / 2);193 this.nextCreate += World.SPACING;194 } else {195 this.items.push(new Moai(x + World.SPACING));196 this.nextCreate += 100000;197 }198 }199 reset(partial) {200 this.items = [];201 this.nextCreate = 0;202 this.dragon.x = 0;203 if(!partial) {204 this.dragon.died = false;205 this.dragon.y = 300;206 this.dragon.vy = 200.0;207 this.dragon.hasPhysic = false;208 }209 this.prices = [];210 this.createdObstacles = 0;211 }212 nextLevel() {213 this.level += 1;214 this.reset(true);215 this.o.notify('level', this.level);216 }217 update(timestamp) {218 let elapsed = timestamp - this.last_timestamp, offsetX = 0;219 if(elapsed > 15) {220 this.last_timestamp = timestamp;221 this.dragon.update(elapsed);222 // Dragon fly bellow sea level223 if(this.dragon.y > HEIGHT) {224 this.dragon.dead = true;225 this.o.notify('dead', true);226 return true;227 }228 this.ctx.clearRect(0, 0, WIDTH, HEIGHT);229 offsetX = this.dragon.x - 90;230 if(this.prices[0] && this.dragon.x >= this.prices[0]) {231 this.prices.shift();232 this.score += 10;233 this.o.notify('score', this.score);234 }235 if(offsetX > 100)236 this.dragon.hasPhysic = true;237 // Draw all obstacles238 for(let item of this.items) {239 item.draw(this.ctx, offsetX, timestamp);240 if(item.hasCollision(this.dragon.x, this.dragon.y)) {241 item.doCollision(this);242 }243 }244 this.dragon.draw(this.ctx, offsetX, timestamp);245 // Create new obstacles246 let timeToSpawn = this.items[0] && this.items[this.items.length-1].x - offsetX < WIDTH + World.SPACING;247 if(this.nextCreate < offsetX) {248 if(offsetX < 300)249 this.createObstacle(150, Math.random() < 0.5, Math.random() < 0.5);250 else251 this.createObstacle(150, Math.random() < 0.25, Math.random() < 0.1);252 }253 // Remove old obstacles254 while(this.items[0] && this.items[0].x - offsetX + World.SPACING < 0) {255 console.log('Removing:', this.items[0]);256 let item = this.items.shift();257 if(item instanceof Moai) {258 this.nextLevel();259 }260 }261 262 }263 return true;264 }265}266World.SPACING = 400;267function oninit() {268 console.log('oninit');269 let w = new World();270 // w.items.push(new Obstacle(500, 200, 'top'));271 // w.items.push(new Obstacle(500, 200, 'down'));272 // w.items.push(new Coin(200, 300));273 let callback = (timestamp) => {274 if(!STOP && w.update(timestamp))275 window.requestAnimationFrame(callback);276 }277 window.requestAnimationFrame(callback);...

Full Screen

Full Screen

useCallback&useMemo.js

Source:useCallback&useMemo.js Github

copy

Full Screen

...13 // 和其他hook相同,首先找到正在执行的hook。14 const hook = mountWorkInProgressHook();15 const nextDeps = deps === undefined ? null : deps;16 // 把我们的依赖项保存在hook中并返回的callback,并执行。17 const nextValue = nextCreate();18 hook.memoizedState = [nextValue, nextDeps];19 return nextValue;20}21function updateCallback(callback, deps) {22 const hook = updateWorkInProgressHook();23 const nextDeps = deps === undefined ? null : deps;24 const prevState = hook.memoizedState;25 if (prevState !== null) {26 if (nextDeps !== null) {27 const prevDeps = prevState[1];28 // 对于两个依赖项进行比较,这里的实质上是一个浅比较。Object.is()29 if (areHookInputsEqual(nextDeps, prevDeps)) {30 return prevState[0];31 }32 }33 }34 // 和updateMemo()的唯一区别就是是否会对传入的函数进行调用。35 hook.memoizedState = [callback, nextDeps];36 return callback;37}38function updateMemo(nextCreate, deps) {39 const hook = updateWorkInProgressHook();40 const nextDeps = deps === undefined ? null : deps;41 const prevState = hook.memoizedState;42 if (prevState !== null) {43 if (nextDeps !== null) {44 const prevDeps = prevState[1];45 if (areHookInputsEqual(nextDeps, prevDeps)) {46 return prevState[0];47 }48 }49 }50 const nextValue = nextCreate();51 hook.memoizedState = [nextValue, nextDeps];52 return nextValue;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { storiesOf } from '@storybook/react';3import { action } from '@storybook/addon-actions';4import { linkTo } from '@storybook/addon-links';5import Button from './Button';6import Welcome from './Welcome';7storiesOf('Welcome', module).add('to Storybook', () => <Welcome showApp={linkTo('Button')} />);8storiesOf('Button', module)9 .add('with text', () => (10 <Button onClick={action('clicked')}>Hello Button</Button>11 .add('with some emoji', () => (12 <Button onClick={action('clicked')}>😀 😎 👍 💯</Button>13 ));14import { configure } from '@storybook/react';15const req = require.context('../src', true, /.stories.js$/);16function loadStories() {17 req.keys().forEach(filename => req(filename));18}19configure(loadStories, module);20import '@storybook/addon-actions/register';21import '@storybook/addon-links/register';22const path = require('path');23module.exports = async ({ config, mode }) => {24 config.module.rules.push({25 loaders: [require.resolve('@storybook/source-loader')],26 });27 config.module.rules.push({28 include: path.resolve(__dirname, '../'),29 });30 return config;31};32ERROR in ./src/stories/index.stories.js Module build failed: Error: ENOENT: no such file or directory, open '/Users/rahul/Projects/React/react-storybook-sample/src/stories/index.stories.js' at Error (native) @ multi ./src/stories/index.stories.js

Full Screen

Using AI Code Generation

copy

Full Screen

1import { nextCreate } from 'storybook-root-decorator';2import { storiesOf } from '@storybook/react';3import { withInfo } from '@storybook/addon-info';4storiesOf('Button', module)5 .addDecorator(withInfo)6 .add('with text', () => nextCreate('Button', { label: 'Hello Button' }));7![storybook](./storybook.png)8import { storiesOf } from '@storybook/react';9import { withInfo } from '@storybook/addon-info';10storiesOf('Button', module)11 .addDecorator(withInfo)12 .add('with text', () => <Button label="Hello Button" />);13![storybook](./storybook.png)14MIT © [Tae Hong Park](

Full Screen

Using AI Code Generation

copy

Full Screen

1import { nextCreate } from 'storybook-root';2describe('test', () => {3 it('test', () => {4 const { getByText } = nextCreate(<TestComponent />);5 expect(getByText('test')).toBeTruthy();6 });7});8import { nextCreate } from 'storybook-root';9export default function TestComponent() {10 return <div>test</div>;11}12import { nextCreate } from 'storybook-root';13export default {14};15export const Test = () => <TestComponent />;

Full Screen

Using AI Code Generation

copy

Full Screen

1import { nextCreate } from '@storybook/addon-storyshots-puppeteer';2const storybookRootProvider = {3 async nextCreate(options) {4 const { page } = options;5 await page.waitForSelector('#root');6 },7};8export default storybookRootProvider;9import { configure } from '@storybook/react';10import storybookRootProvider from '../test.js';11configure(() => {12 require('./stories');13}, module);14export const parameters = {15};16import { addDecorator } from '@storybook/react';17import { withNextRouter } from 'storybook-addon-next-router';18addDecorator(withNextRouter());19module.exports = {20 stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'],21};22const path = require('path');23const webpack = require('webpack');24module.exports = async ({ config }) => {25 config.plugins.push(new webpack.EnvironmentPlugin(process.env));26 config.resolve.alias['~'] = path.resolve(__dirname, '../');27 return config;28};29const withBundleAnalyzer = require('@next/bundle-analyzer')({30});31const withPWA = require('next-pwa');32const prod = process.env.NODE_ENV === 'production';33module.exports = withBundleAnalyzer(34 withPWA({35 pwa: {36 },37 webpack(config) {38 config.module.rules.push({39 });40 return config;41 },42 })43);44{45 "compilerOptions": {46 "paths": {47 }48 },49 "include": ["../src/**/*.stories.@(js|jsx|ts|tsx)"]50}

Full Screen

Using AI Code Generation

copy

Full Screen

1import { nextCreate } from 'storybook-root';2const story = nextCreate({3 props: {4 }5});6export default story;7import 'storybook-root/register';8import 'storybook-root/preview';9import 'storybook-roo

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful