How to use callSpy method in storybook-root

Best JavaScript code snippet using storybook-root

for-each-test.js

Source:for-each-test.js Github

copy

Full Screen

1/*!2 * ENDER - The open module JavaScript framework3 *4 * Copyright (c) 2011-2012 @ded, @fat, @rvagg and other contributors5 *6 * Permission is hereby granted, free of charge, to any person obtaining a copy7 * of this software and associated documentation files (the "Software"), to deal8 * in the Software without restriction, including without limitation the rights9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell10 * copies of the Software, and to permit persons to whom the Software is furnished11 * to do so, subject to the following conditions:12 *13 * The above copyright notice and this permission notice shall be included in all14 * copies or substantial portions of the Software.15 *16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE22 * SOFTWARE.23 */24var buster = require('bustermove')25 , assert = require('referee').assert26 , refute = require('referee').refute27 , DependencyGraph = require('../lib/dependency-graph')28buster.testCase('forEach', {29 'no dependencies': {30 'setUp': function () {31 this.originalGraph = DependencyGraph({}, {32 'pkg1': {33 dependencies: {}34 , packageJSON: { name: 'pkg1' }35 , parents: [ 'foo' ]36 }37 , 'some/path/to/pkg2': {38 dependencies: {}39 , packageJSON: { name: 'pkg2' }40 , parents: [ 'foo', 'bar' ]41 }42 })43 this.callSpy = this.spy()44 this.verifySpy = function () {45 assert.equals(this.callSpy.callCount, 2)46 assert.equals(this.callSpy.getCall(0).args[0], 'pkg1')47 assert.equals(this.callSpy.getCall(0).args[1], [ 'foo' ])48 assert.equals(this.callSpy.getCall(0).args[2], this.originalGraph.graphData['pkg1'])49 assert.equals(this.callSpy.getCall(1).args[0], 'some/path/to/pkg2')50 assert.equals(this.callSpy.getCall(1).args[1], [ 'foo' , 'bar' ])51 assert.equals(this.callSpy.getCall(1).args[2], this.originalGraph.graphData['some/path/to/pkg2'])52 }53 }54 , 'test forEachUniqueOrderedDependency': function () {55 this.originalGraph.forEachUniqueOrderedDependency(this.originalGraph.allRootPackages(), this.callSpy)56 this.verifySpy()57 }58 , 'test forEachOrderedDependency': function () {59 // should do the same thing60 this.originalGraph.forEachOrderedDependency(this.originalGraph.allRootPackages(), this.callSpy)61 this.verifySpy()62 }63 }64 , 'simple dependencies': {65 'setUp': function () {66 this.originalGraph = DependencyGraph({}, {67 'apkg-2': {68 parents: []69 , packageJSON: { name: 'apkg-2', dependencies: { 'mypkg-1': '*' } }70 , dependencies: {71 'mypkg-1': {72 parents: [ 'apkg-2' ]73 , packageJSON: { name: 'mypkg-1' }74 , dependencies: {}75 }76 }77 }78 , 'somepkg-5': {79 parents: []80 , packageJSON: { name: 'somepkg-5', dependencies: { 'foo-4': '*' } }81 , dependencies: {82 'foo-4': {83 parents: [ 'somepkg-5' ]84 , packageJSON: { name: 'foo-4', dependencies: { 'bar-3': '*' } }85 , dependencies: {86 'bar-3': {87 parents: [ 'somepkg-5', 'foo-4' ]88 , packageJSON: { name: 'bar-3' }89 , dependencies: {}90 }91 }92 }93 }94 }95 , 'apkg-7': {96 parents: []97 , packageJSON: { name: 'apkg-7', dependencies: { 'mypkg-6': '*' } }98 , dependencies: {99 'mypkg-6': {100 parents: [ 'apkg-7' ]101 , packageJSON: { name: 'mypkg-6' }102 , dependencies: {}103 }104 }105 }106 })107 this.callSpy = this.spy()108 this.verifySpy = function () {109 assert.equals(this.callSpy.args.length, 7)110 this.callSpy.args.forEach(function (c, i) {111 assert.equals(c[3], i)112 refute.isNull(c[2])113 refute.isNull(c[2].dependencies) // should be the packageJSON, 'dependencies' is a proxy for this114 assert.same(c[1], c[2].parents)115 assert.match(c[0], new RegExp('-' + (++i) + '$'))116 })117 }118 }119 , 'test forEachUniqueOrderedDependency': function () {120 this.originalGraph.forEachUniqueOrderedDependency(this.originalGraph.allRootPackages(), this.callSpy)121 this.verifySpy()122 }123 , 'test forEachOrderedDependency': function () {124 // should do the same thing125 this.originalGraph.forEachOrderedDependency(this.originalGraph.allRootPackages(), this.callSpy)126 this.verifySpy()127 }128 }129 , 'ender-js at front': {130 'setUp': function () {131 this.originalGraph = DependencyGraph({}, {132 'apkg-3': {133 parents: []134 , packageJSON: { name: 'apkg-3', dependencies: { 'mypkg-2': '*' } }135 , dependencies: {136 'mypkg-2': {137 parents: [ 'apkg-3' ]138 , packageJSON: { name: 'mypkg-2' }139 , dependencies: {}140 }141 }142 }143 , 'somepkg-4': {144 parents: []145 , packageJSON: { name: 'somepkg-4' }146 , dependencies: {}147 }148 , 'ender-js': {149 parents: []150 , packageJSON: { name: 'ender-js' }151 , dependencies: {}152 } // it should spit this out first153 , 'apkg-6': {154 parents: []155 , packageJSON: { name: 'apkg-6', dependencies: { 'mypkg-5': '*' } }156 , dependencies: {157 'mypkg-5': {158 parents: [ 'apkg-6' ]159 , packageJSON: { name: 'mypkg-5' }160 , dependencies: {}161 }162 }163 }164 })165 this.callSpy = this.spy()166 this.verifySpy = function () {167 assert.equals(this.callSpy.args.length, 6)168 this.callSpy.args.forEach(function (c, i) {169 assert.equals(c[3], i)170 refute.isNull(c[2])171 refute.isNull(c[2].dependencies) // should be the packageJSON, 'dependencies' is a proxy for this172 assert.same(c[1], c[2].parents)173 if (!i) {174 assert.equals(c[0], 'ender-js')175 assert.same(c[2], this.originalGraph.graphData['ender-js'])176 } else177 assert.match(c[0], new RegExp('-' + (++i) + '$'))178 }.bind(this))179 }180 }181 , 'test forEachUniqueOrderedDependency': function () {182 this.originalGraph.forEachUniqueOrderedDependency(this.originalGraph.allRootPackages(), this.callSpy)183 this.verifySpy()184 }185 , 'test forEachOrderedDependency': function () {186 // should do the same thing187 this.originalGraph.forEachOrderedDependency(this.originalGraph.allRootPackages(), this.callSpy)188 this.verifySpy()189 }190 }191 , 'duplicate dependencies': {192 'setUp': function () {193 this.originalGraph = DependencyGraph({}, {194 'apkg-6': {195 parents: []196 , packageJSON: { name: 'apkg-6', dependencies: { 'mypkg-5': '*' } }197 , dependencies: {198 'mypkg-5': {199 parents: [ 'apkg-6' ]200 , packageJSON: { name: 'mypkg-5', dependencies: { 'apkg-2': '*', 'apkg-4': '*' } }201 , dependencies: {202 'apkg-2': {203 parents: [ 'apkg-6', 'mypkg-5' ]204 , packageJSON: { name: 'apkg-2', dependencies: { 'mypkg-1': '*' } }205 , dependencies: {206 'mypkg-1': {207 parents: [ 'apkg-6', 'mypkg-5', 'apkg-2' ]208 , packageJSON: { name: 'mypkg-1' }209 , dependencies: {}210 }211 }212 }213 , 'apkg-4': {214 parents: [ 'apkg-6', 'mypkg-5' ]215 , packageJSON: { name: 'apkg-4', dependencies: { 'mypkg-3': '*' } }216 , dependencies: {217 'mypkg-3': {218 parents: [ 'apkg-6', 'mypkg-5', 'apkg-4' ]219 , packageJSON: { name: 'mypkg-3' }220 , dependencies: {}221 }222 }223 }224 }225 }226 }227 }228 , 'somepkg-9': {229 parents: []230 , packageJSON: { name: 'somepkg-9', dependencies: { 'foo-8': '*', 'mypkg-3': '*' } }231 , dependencies: {232 'foo-8': {233 parents: [ 'somepkg-9' ]234 , packageJSON: { name: 'foo-8', dependencies: { 'bar-7': '*' } }235 , dependencies: {236 'bar-7': {237 parents: [ 'somepkg-9', 'foo-8' ]238 , packageJSON: { name: 'bar-7' }239 , dependencies: {}240 }241 }242 }243 , 'mypkg-3': {244 parents: [ 'somepkg-9' ]245 , packageJSON: { name: 'mypkg-3' }246 , dependencies: {}247 }248 }249 }250 , 'apkg-2': {251 parents: []252 , packageJSON: { name: 'apkg-2', dependencies: { 'mypkg-1': '*' } }253 , dependencies: {254 'mypkg-1': {255 parents: [ 'apkg-2' ]256 , packageJSON: { name: 'mypkg-1' }257 , dependencies: {}258 }259 }260 }261 , 'lastpkg-10': {262 parents: []263 , packageJSON: { name: 'lastpkg-10' }264 , dependencies: {}265 }266 })267 this.callSpy = this.spy()268 }269 // we should only see unique packages here, they have numbers in their names so we can match them270 // easily271 , 'test forEachUniqueOrderedDependency': function () {272 this.originalGraph.forEachUniqueOrderedDependency(this.originalGraph.allRootPackages(), this.callSpy)273 // expect only uniques274 assert.equals(this.callSpy.args.length, 10)275 this.callSpy.args.forEach(function (c, i) {276 assert.equals(c[3], i)277 refute.isNull(c[2])278 refute.isNull(c[2].dependencies) // should be the packageJSON, 'dependencies' is a proxy for this279 assert.same(c[1], c[2].parents)280 assert.match(c[0], new RegExp('-' + (++i) + '$'))281 })282 }283 // in this case we should see all packages in order, not just uniques, but we should get an argument284 // for uniqueness285 , 'test forEachOrderedDependency': function () {286 var expectedPackages =287 'mypkg-1 apkg-2 mypkg-3 apkg-4 mypkg-5 apkg-6 bar-7 foo-8 mypkg-3 somepkg-9 mypkg-1 apkg-2 lastpkg-10'288 .split(' ')289 , orderedIndex = 1290 this.originalGraph.forEachOrderedDependency(this.originalGraph.allRootPackages(), this.callSpy)291 assert.equals(this.callSpy.args.length, expectedPackages.length)292 this.callSpy.args.forEach(function (c, i) {293 // use 'orderedIndex' to check if the current package is a dupe or not according to the294 // package name295 var expectedIsUnique = new RegExp('-' + orderedIndex + '$').test(c[0])296 if (expectedIsUnique)297 orderedIndex++298 assert.equals(c[3], i)299 refute.isNull(c[2])300 refute.isNull(c[2].dependencies) // should be the packageJSON, 'dependencies' is a proxy for this301 assert.same(c[1], c[2].parents)302 assert.equals(c[0], expectedPackages[i])303 assert.equals(c[4], expectedIsUnique, 'index ' + i + ' ' + c[0])304 })305 }306 }307 , 'additional unnecessary dependencies': {308 'setUp': function () {309 this.originalGraph = DependencyGraph({}, {310 'apkg-2': {311 parents: []312 , packageJSON: { name: 'apkg-2', dependencies: { 'mypkg-1': '*' } }313 , dependencies: {314 'mypkg-1': {315 parents: [ 'apkg-2' ]316 , packageJSON: { name: 'mypkg-1' }317 , dependencies: {}318 }319 }320 }321 , 'somepkg-5': {322 parents: []323 , packageJSON: { name: 'somepkg-5', dependencies: { 'foo-4': '*' } }324 , dependencies: {325 'foo-4': {326 parents: [ 'somepkg-5' ]327 , packageJSON: { name: 'foo-4', dependencies: { 'bar-3': '*' } }328 , dependencies: {329 'bar-3': {330 parents: [ 'somepkg-5', 'foo-4' ]331 , packageJSON: { name: 'bar-3' }332 , dependencies: {}333 }334 }335 }336 }337 }338 , 'apkg-7': {339 parents: []340 , packageJSON: { name: 'apkg-7', dependencies: { 'mypkg-6': '*' } }341 , dependencies: {342 'mypkg-6': {343 parents: [ 'apkg-7' ]344 , packageJSON: { name: 'mypkg-6' }345 , dependencies: {}346 }347 }348 }349 })350 this.callSpy = this.spy()351 this.verifySpy = function () {352 assert.equals(this.callSpy.args.length, 5)353 this.callSpy.args.forEach(function (c, i) {354 assert.equals(c[3], i)355 refute.isNull(c[2])356 refute.isNull(c[2].dependencies) // should be the packageJSON, 'dependencies' is a proxy for this357 assert.same(c[1], c[2].parents)358 assert.match(c[0], new RegExp('-' + (++i) + '$'))359 })360 }361 }362 , 'test forEachUniqueOrderedDependency': function () {363 this.originalGraph.forEachUniqueOrderedDependency([ 'apkg-2', 'somepkg-5' ], this.callSpy)364 this.verifySpy()365 }366 , 'test forEachOrderedDependency': function () {367 // should do the same thing368 this.originalGraph.forEachOrderedDependency([ 'apkg-2', 'somepkg-5' ], this.callSpy)369 this.verifySpy()370 }371 }...

Full Screen

Full Screen

instrumenter.test.ts

Source:instrumenter.test.ts Github

copy

Full Screen

1/* eslint-disable no-underscore-dangle */2import { addons, mockChannel } from '@storybook/addons';3import {4 FORCE_REMOUNT,5 SET_CURRENT_STORY,6 STORY_RENDER_PHASE_CHANGED,7} from '@storybook/core-events';8import global from 'global';9import { EVENTS, Instrumenter } from './instrumenter';10import { Options } from './types';11const callSpy = jest.fn();12const syncSpy = jest.fn();13const forceRemountSpy = jest.fn();14addons.setChannel(mockChannel());15addons.getChannel().on(EVENTS.CALL, callSpy);16addons.getChannel().on(EVENTS.SYNC, syncSpy);17addons.getChannel().on(FORCE_REMOUNT, forceRemountSpy);18class HTMLElement {19 constructor(props: any) {20 Object.assign(this, props);21 }22}23delete global.window.location;24global.window.location = { reload: jest.fn() };25global.window.HTMLElement = HTMLElement;26const storyId = 'kind--story';27global.window.__STORYBOOK_PREVIEW__ = { urlStore: { selection: { storyId } } };28const setRenderPhase = (newPhase: string) =>29 addons.getChannel().emit(STORY_RENDER_PHASE_CHANGED, { newPhase, storyId });30let instrumenter: Instrumenter;31const instrument = <TObj extends Record<string, any>>(obj: TObj, options: Options = {}) =>32 instrumenter.instrument(obj, options);33beforeEach(() => {34 jest.useRealTimers();35 callSpy.mockClear();36 syncSpy.mockClear();37 forceRemountSpy.mockClear();38 instrumenter = new Instrumenter();39 setRenderPhase('loading');40});41afterEach(() => {42 addons.getChannel().emit(SET_CURRENT_STORY); // trigger a cleanup43});44describe('Instrumenter', () => {45 it('patches object methods', () => {46 const fn = () => {};47 const result = instrument({ fn });48 expect(result).toStrictEqual({ fn: expect.any(Function) });49 expect(result.fn.name).toBe('fn');50 expect(result.fn.__originalFn__).toBe(fn);51 });52 it('patches nested methods', () => {53 const fn1: any = () => {};54 const fn2: any = () => {};55 const result = instrument({ foo: { fn1, bar: { fn2 } } });56 expect(result).toStrictEqual({57 foo: {58 fn1: expect.any(Function),59 bar: { fn2: expect.any(Function) },60 },61 });62 expect(result.foo.fn1.__originalFn__).toBe(fn1);63 expect(result.foo.bar.fn2.__originalFn__).toBe(fn2);64 });65 it('does not patch already patched functions', () => {66 const fn: any = () => {};67 const result = instrument(instrument({ fn }));68 expect(result.fn.__originalFn__).toBe(fn);69 expect(result.fn.__originalFn__.__originalFn__).not.toBeDefined();70 });71 it('does not traverse into arrays', () => {72 const fn1: any = () => {};73 const fn2: any = () => {};74 const result = instrument({ arr: [fn1, { fn2 }] });75 expect(result).toStrictEqual({ arr: [fn1, { fn2 }] });76 expect(result.arr[0].__originalFn__).not.toBeDefined();77 expect(result.arr[1].fn2.__originalFn__).not.toBeDefined();78 });79 it('patches function properties on functions', () => {80 const fn1: any = () => {};81 fn1.fn2 = () => {};82 const result = instrument({ fn1 });83 expect(result.fn1).toEqual(expect.any(Function));84 expect(result.fn1.fn2).toEqual(expect.any(Function));85 expect(result.fn1.__originalFn__).toBe(fn1);86 expect(result.fn1.fn2.__originalFn__).toBe(fn1.fn2);87 });88 it('patched functions call the original function when invoked', () => {89 const { fn } = instrument({ fn: jest.fn() });90 const obj = {};91 fn('foo', obj);92 expect(fn.__originalFn__).toHaveBeenCalledWith('foo', obj);93 });94 it('emits a "call" event every time a patched function is invoked', () => {95 const { fn } = instrument({ fn: (...args: any) => {} });96 fn('foo', 'bar');97 fn('baz');98 expect(callSpy).toHaveBeenCalledWith(99 expect.objectContaining({100 id: 'kind--story [0] fn',101 args: ['foo', 'bar'],102 })103 );104 expect(callSpy).toHaveBeenCalledWith(105 expect.objectContaining({106 id: 'kind--story [1] fn',107 args: ['baz'],108 })109 );110 });111 it('provides metadata about the call in the event', () => {112 const { obj } = instrument({ obj: { fn: () => {} } });113 obj.fn();114 expect(callSpy).toHaveBeenCalledWith(115 expect.objectContaining({116 path: ['obj'],117 method: 'fn',118 interceptable: false,119 status: 'done',120 parentId: undefined,121 })122 );123 });124 it('maps event args which originate from an earlier call to a call ref', () => {125 const { fn1, fn2 } = instrument({126 fn1: (arg: any) => arg,127 fn2: (arg: any) => {},128 });129 fn2(fn1({}));130 expect(callSpy).toHaveBeenLastCalledWith(131 expect.objectContaining({132 method: 'fn2',133 args: [{ __callId__: callSpy.mock.calls[0][0].id, retain: false }],134 })135 );136 });137 it('does not map primitive event args which originate from an earlier call', () => {138 const { fn1, fn2 } = instrument({139 fn1: (...args: any) => args[0],140 fn2: (...args: any) => {},141 });142 fn2(143 fn1(undefined),144 fn1(null),145 fn1(true),146 fn1('foo'),147 fn1(1),148 fn1(BigInt(1)), // eslint-disable-line no-undef149 fn1({}),150 fn1([]),151 fn1(() => {}),152 fn1(Symbol('hi')),153 fn1(new Error('Oops'))154 );155 expect(callSpy).toHaveBeenLastCalledWith(156 expect.objectContaining({157 method: 'fn2',158 args: [159 /* call 0 */ undefined,160 /* call 1 */ null,161 /* call 2 */ true,162 /* call 3 */ 'foo',163 /* call 4 */ 1,164 /* call 5 */ BigInt(1), // eslint-disable-line no-undef165 { __callId__: callSpy.mock.calls[6][0].id, retain: false },166 { __callId__: callSpy.mock.calls[7][0].id, retain: false },167 { __callId__: callSpy.mock.calls[8][0].id, retain: false },168 { __callId__: callSpy.mock.calls[9][0].id, retain: false },169 { __callId__: callSpy.mock.calls[10][0].id, retain: false },170 ],171 })172 );173 });174 it('maps HTML Elements in event args to an element ref', () => {175 const { fn } = instrument({ fn: (...args: any) => {} });176 fn(new HTMLElement({ prefix: '', localName: 'div', id: 'root', classList: [] }));177 expect(callSpy).toHaveBeenLastCalledWith(178 expect.objectContaining({179 args: [{ __element__: { prefix: '', localName: 'div', id: 'root', classNames: [] } }],180 })181 );182 });183 it('tracks the parent call id for calls inside callbacks', () => {184 const fn = (callback?: Function) => callback && callback();185 const { fn1, fn2, fn3, fn4, fn5 } = instrument({ fn1: fn, fn2: fn, fn3: fn, fn4: fn, fn5: fn });186 fn1(() => {187 fn2(() => fn3());188 fn4();189 });190 fn5();191 expect(callSpy).toHaveBeenCalledWith(192 expect.objectContaining({ id: 'kind--story [0] fn1', parentId: undefined })193 );194 expect(callSpy).toHaveBeenCalledWith(195 expect.objectContaining({196 id: 'kind--story [0] fn1 [0] fn2',197 parentId: 'kind--story [0] fn1',198 })199 );200 expect(callSpy).toHaveBeenCalledWith(201 expect.objectContaining({202 id: 'kind--story [0] fn1 [0] fn2 [0] fn3',203 parentId: 'kind--story [0] fn1 [0] fn2',204 })205 );206 expect(callSpy).toHaveBeenCalledWith(207 expect.objectContaining({208 id: 'kind--story [0] fn1 [1] fn4',209 parentId: 'kind--story [0] fn1',210 })211 );212 expect(callSpy).toHaveBeenCalledWith(213 expect.objectContaining({ id: 'kind--story [1] fn5', parentId: undefined })214 );215 });216 it('tracks the parent call id for async callbacks', async () => {217 const fn = (callback?: Function) => Promise.resolve(callback && callback());218 const { fn1, fn2, fn3 } = instrument({ fn1: fn, fn2: fn, fn3: fn });219 await fn1(() => fn2());220 await fn3();221 expect(callSpy).toHaveBeenCalledWith(222 expect.objectContaining({ id: 'kind--story [0] fn1', parentId: undefined })223 );224 expect(callSpy).toHaveBeenCalledWith(225 expect.objectContaining({226 id: 'kind--story [0] fn1 [0] fn2',227 parentId: 'kind--story [0] fn1',228 })229 );230 expect(callSpy).toHaveBeenCalledWith(231 expect.objectContaining({ id: 'kind--story [1] fn3', parentId: undefined })232 );233 });234 it('instruments the call result to support chaining', () => {235 const { fn1 } = instrument({236 fn1: () => ({237 fn2: () => {},238 }),239 });240 fn1().fn2();241 expect(callSpy).toHaveBeenLastCalledWith(242 expect.objectContaining({243 method: 'fn2',244 path: [{ __callId__: callSpy.mock.calls[0][0].id }],245 })246 );247 });248 it('emits a "sync" event with debounce after a patched function is invoked', () => {249 const { fn } = instrument({ fn: (...args: any) => {} }, { intercept: true });250 jest.useFakeTimers();251 syncSpy.mockClear();252 fn('foo');253 fn('bar');254 jest.runAllTimers();255 expect(syncSpy).toHaveBeenCalledTimes(1);256 });257 it('sends a folded log with the "sync" event', () => {258 const { fn } = instrument({ fn: (...args: any) => ({ fn2: () => {} }) }, { intercept: true });259 jest.useFakeTimers();260 fn('foo', fn('bar')).fn2();261 fn('baz');262 jest.runAllTimers();263 expect(syncSpy).toHaveBeenCalledWith(264 expect.objectContaining({265 logItems: [266 { callId: 'kind--story [2] fn2', status: 'done' },267 { callId: 'kind--story [3] fn', status: 'done' },268 ],269 })270 );271 });272 it('catches thrown errors and returns the error', () => {273 const { fn } = instrument({274 fn: () => {275 throw new Error('Boom!');276 },277 });278 expect(fn()).toEqual(new Error('Boom!'));279 expect(() => setRenderPhase('played')).toThrow(new Error('Boom!'));280 });281 it('forwards nested exceptions', () => {282 const { fn1, fn2 } = instrument({283 fn1: (...args: any) => {}, // doesn't forward args284 fn2: () => {285 throw new Error('Boom!');286 },287 });288 expect(fn1(fn2())).toEqual(new Error('Boom!'));289 expect(() => setRenderPhase('played')).toThrow(new Error('Boom!'));290 });291 it("re-throws anything that isn't an error", () => {292 const { fn } = instrument({293 fn: () => {294 throw 'Boom!'; // eslint-disable-line no-throw-literal295 },296 });297 expect(fn).toThrow('Boom!');298 expect(callSpy).not.toHaveBeenCalled();299 });300 it('does not affect intercepted methods', () => {301 const { fn } = instrument({ fn: jest.fn() }, { intercept: true });302 fn('foo');303 expect(fn.__originalFn__).toHaveBeenCalledWith('foo');304 });305 it('clears state when switching stories', () => {306 addons.getChannel().emit(SET_CURRENT_STORY); // initialization307 instrumenter.state = {308 'kind--story': {309 isDebugging: false,310 cursor: 123,311 calls: [{ id: 'kind--story [0] fn' }],312 shadowCalls: [{ id: 'kind--story [0] fn' }, { id: 'kind--story [1] fn' }],313 callRefsByResult: new Map([[{}, 'ref']]),314 chainedCallIds: new Set(['kind--story [0] fn']),315 parentCall: { id: 'kind--story [0] fn' },316 playUntil: 'kind--story [1] fn',317 resolvers: { ref: () => {} },318 syncTimeout: 123,319 forwardedException: new Error('Oops'),320 },321 } as any;322 addons.getChannel().emit(SET_CURRENT_STORY);323 expect(instrumenter.state).toStrictEqual({});324 });325 describe('with intercept: true', () => {326 const options = { intercept: true };327 it('emits a call event with error data when the function throws', () => {328 const { fn } = instrument(329 {330 fn: () => {331 throw new Error('Boom!');332 },333 },334 options335 );336 expect(fn).toThrow();337 expect(callSpy).toHaveBeenCalledWith(338 expect.objectContaining({339 id: 'kind--story [0] fn',340 exception: {341 name: 'Error',342 message: 'Boom!',343 stack: expect.stringContaining('Error: Boom!'),344 },345 })346 );347 });348 it('catches thrown errors and throws an ignoredException instead', () => {349 const { fn } = instrument(350 {351 fn: () => {352 throw new Error('Boom!');353 },354 },355 options356 );357 expect(fn).toThrow('ignoredException');358 });359 it('catches forwarded exceptions and throws an ignoredException instead', () => {360 const { fn1, fn2 } = instrument(361 {362 fn1: (_: any) => {},363 fn2: () => {364 throw new Error('Boom!');365 },366 },367 options368 );369 expect(() => fn1(fn2())).toThrow('ignoredException');370 });371 });372 describe('while debugging', () => {373 afterEach(() => {374 addons.getChannel().emit(EVENTS.END, { storyId });375 });376 it('remounts on the "start" event', async () => {377 addons.getChannel().emit(EVENTS.START, { storyId });378 expect(forceRemountSpy).toHaveBeenCalled();379 });380 it('defers calls to intercepted functions', () => {381 const { fn } = instrument({ fn: jest.fn() }, { intercept: true });382 addons.getChannel().emit(EVENTS.START, { storyId });383 expect(fn()).toEqual(expect.any(Promise));384 expect(fn.__originalFn__).not.toHaveBeenCalled();385 });386 it('does not defer calls to non-intercepted functions', () => {387 const { fn } = instrument({ fn: jest.fn(() => 'ok') });388 addons.getChannel().emit(EVENTS.START, { storyId });389 expect(fn()).toBe('ok');390 expect(fn.__originalFn__).toHaveBeenCalled();391 });392 it('does not defer calls to intercepted functions that are chained upon', () => {393 const { fn1 } = instrument(394 { fn1: jest.fn(() => ({ fn2: jest.fn() as any })) },395 { intercept: true }396 );397 fn1().fn2();398 addons.getChannel().emit(EVENTS.START, { storyId });399 const res1 = fn1();400 expect(res1.fn2()).toEqual(expect.any(Promise));401 expect(fn1.__originalFn__).toHaveBeenCalledTimes(2);402 expect(res1.fn2.__originalFn__).not.toHaveBeenCalled();403 });404 it.skip('starts debugging at the first non-nested interceptable call', () => {405 const { fn } = instrument({ fn: jest.fn((...args: any) => args) }, { intercept: true });406 fn(fn(), fn()); // setup the dependencies407 addons.getChannel().emit(EVENTS.START, { storyId });408 const a = fn('a');409 const b = fn('b');410 const c = fn(a, b);411 expect(a).toEqual(['a']);412 expect(b).toEqual(['b']);413 expect(c).toEqual(expect.any(Promise));414 });415 it('steps through each interceptable function on "next"', async () => {416 const fn = jest.fn();417 const { fn: instrumentedFn } = instrument({ fn }, { intercept: true });418 const mockedInstrumentedFn = jest.fn(instrumentedFn);419 const play = async () => {420 await mockedInstrumentedFn();421 await mockedInstrumentedFn();422 await mockedInstrumentedFn();423 };424 await play();425 fn.mockClear();426 mockedInstrumentedFn.mockClear();427 addons.getChannel().emit(EVENTS.START, { storyId });428 const p = play();429 expect(mockedInstrumentedFn).toHaveBeenCalledTimes(1);430 expect(fn).toHaveBeenCalledTimes(0);431 addons.getChannel().emit(EVENTS.NEXT, { storyId });432 await new Promise((resolve) => setTimeout(resolve, 0));433 expect(mockedInstrumentedFn).toHaveBeenCalledTimes(2);434 expect(fn).toHaveBeenCalledTimes(1);435 addons.getChannel().emit(EVENTS.END, { storyId });436 await new Promise((resolve) => setTimeout(resolve, 0));437 expect(mockedInstrumentedFn).toHaveBeenCalledTimes(3);438 expect(fn).toHaveBeenCalledTimes(3);439 await p;440 });441 });...

Full Screen

Full Screen

functional.mocha.ts

Source:functional.mocha.ts Github

copy

Full Screen

1/*2 * Copyright 2017-2018 Allegro.pl3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16import { expect } from "chai";17import * as sinon from "sinon";18import { SinonSpy } from "sinon";19import { sleep } from "../../../client/utils/test-utils/sleep";20import { complement, concatTruthy, cons, debounceWithPromise, flatMap, mapTruthy, thread, threadConditionally, threadNullable } from "./functional";21const inc = (x: number) => x + 1;22const double = (x: number) => x * 2;23const nil = (): void => null;24const wrap = (...numbers: number[]) => numbers;25describe("Functional utilities", () => {26 describe("cons", () => {27 it("should append to empty array", () => {28 expect(cons([], 1)).to.deep.eq([1]);29 });30 it("should keep nested arrays", () => {31 expect(cons([], [1])).to.deep.eq([[1]]);32 });33 });34 describe("flatMap", () => {35 it("should flatten", () => {36 const result = flatMap([1, 3], (i: number) => wrap(i, inc(i)));37 expect(result).to.deep.eq([1, 2, 3, 4]);38 });39 it("should omit empty arrays as values", () => {40 const result = flatMap([1, 2, 3, 4], () => []);41 expect(result).to.deep.eq([]);42 });43 });44 describe("concatTruthy", () => {45 it("should omit falsy values", () => {46 const result = concatTruthy<any>(0, 1, false, 2, 3, null, 4, undefined, 5);47 expect(result).to.deep.eq([0, 1, 2, 3, 4, 5]);48 });49 });50 describe("mapTruthy", () => {51 it("should omit falsy values from mapper", () => {52 const result = mapTruthy<any, any>([1, 2, 3, 4, 5], (i: number) => i % 2 ? i : null);53 expect(result).to.deep.eq([1, 3, 5]);54 });55 });56 describe("thread", () => {57 it("should thread value through all functions", () => {58 const result = thread(1, inc, double, inc);59 expect(result).to.eq(5);60 });61 });62 describe("threadNullable", () => {63 it("should thread value through all function as long all return values are truthy", () => {64 const result = threadNullable(1, inc, double, inc);65 expect(result).to.eq(5);66 });67 it("should return falsy value if some function in thread returns falsy value", () => {68 const result = threadNullable(1, inc, nil, inc, inc);69 expect(result).to.eq(null);70 });71 });72 describe("threadConditionally", () => {73 it("should thread value through all function as long all functions are callable", () => {74 const result = threadConditionally(1, inc, double, inc);75 expect(result).to.eq(5);76 });77 it("should omit falsy values in call chain", () => {78 const result = threadConditionally(1, inc, undefined, double, null, inc);79 expect(result).to.eq(5);80 });81 });82 describe("complement", () => {83 it("should produce complement predicate", () => {84 const moreThanTen = (x: number) => x > 10;85 expect(moreThanTen(5)).to.be.not.equal(complement(moreThanTen)(5));86 expect(moreThanTen(15)).to.be.not.equal(complement(moreThanTen)(15));87 });88 });89 describe("debounceWithPromise", () => {90 let callSpy: SinonSpy;91 beforeEach(() => {92 callSpy = sinon.spy();93 });94 it("should call function once", async () => {95 const debounced = debounceWithPromise(callSpy, 10);96 debounced();97 debounced();98 debounced();99 expect(callSpy.callCount).to.eq(0);100 await sleep(10);101 expect(callSpy.callCount).to.eq(1);102 });103 it("should call function with argument of last invocation", async () => {104 const debounced = debounceWithPromise(callSpy, 10);105 debounced(1);106 debounced(2);107 debounced(3);108 await sleep(10);109 expect(callSpy.calledWith(3)).to.be.true;110 });111 it("should call function again after if time passes", async () => {112 const debounced = debounceWithPromise(callSpy, 10);113 debounced();114 debounced();115 debounced();116 expect(callSpy.callCount).to.eq(0);117 await sleep(10);118 expect(callSpy.callCount).to.eq(1);119 debounced();120 await sleep(10);121 expect(callSpy.callCount).to.eq(2);122 });123 it("should not call function after cancelation", async () => {124 const debounced = debounceWithPromise(callSpy, 10);125 debounced();126 debounced();127 debounced.cancel();128 await sleep(10);129 expect(callSpy.callCount).to.eq(0);130 });131 it("should return promise with value", async () => {132 const returnVal = 5;133 const debounced = debounceWithPromise(() => returnVal, 10);134 const x = await debounced();135 expect(x).to.be.eq(returnVal);136 });137 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { callSpy } from 'storybook-root-decorator';2import { callSpy } from 'storybook-root-decorator';3import { callSpy } from 'storybook-root-decorator';4import { callSpy } from 'storybook-root-decorator';5import { callSpy } from 'storybook-root-decorator';6import { callSpy } from 'storybook-root-decorator';7import { callSpy } from 'storybook-root-decorator';8import { callSpy } from 'storybook-root-decorator';9import { callSpy } from 'storybook-root-decorator';10import { callSpy } from 'storybook-root-decorator';11import { callSpy } from 'storybook-root-decorator';12import { callSpy } from 'storybook-root-decorator';13import { callSpy } from 'storybook-root-decorator';14import { callSpy } from 'storybook-root-decorator';15import { callSpy } from 'storybook-root-decorator';16import { callSpy } from 'storybook-root-decorator';17import { callSpy } from 'storybook-root-decorator';18import { callSpy } from 'storybook-root-decorator';

Full Screen

Using AI Code Generation

copy

Full Screen

1import { callSpy } from 'storybook-root';2export function test() {3 const spy = jest.fn();4 callSpy(spy, 1, 2, 3);5 expect(spy).toHaveBeenCalledWith(1, 2, 3);6}7import { configure } from '@storybook/react';8import 'storybook-root';9configure(() => {}, module);10module.exports = (baseConfig, env, defaultConfig) => {11 defaultConfig.module.rules.push({12 test: /\.(js|jsx)$/,13 loader: require.resolve('babel-loader'),14 include: [path.resolve(__dirname, '../'), path.resolve(__dirname, 'storybook-root')],15 });16 return defaultConfig;17};18import 'storybook-root';19module.exports = (baseConfig, env, defaultConfig) => {20 defaultConfig.module.rules.push({21 test: /\.(js|jsx)$/,22 loader: require.resolve('babel-loader'),23 include: [path.resolve(__dirname, '../'), path.resolve(__dirname, 'storybook-root')],24 });25 return defaultConfig;26};27import 'storybook-root';28module.exports = (baseConfig, env, defaultConfig) => {29 defaultConfig.module.rules.push({30 test: /\.(js|jsx)$/,31 loader: require.resolve('babel-loader'),32 include: [path.resolve(__dirname, '../'), path.resolve(__dirname, 'storybook-root')],33 });34 return defaultConfig;35};36import 'storybook-root';37module.exports = (baseConfig, env, defaultConfig) => {38 defaultConfig.module.rules.push({39 test: /\.(js|jsx)$/,40 loader: require.resolve('babel-loader'),41 include: [path.resolve(__dirname, '../'), path.resolve(__dirname, 'storybook-root')],

Full Screen

Using AI Code Generation

copy

Full Screen

1import { callSpy } from 'storybook-root-spy';2import { storiesOf } from '@storybook/react';3storiesOf('Test', module)4 .add('Test', () => {5 callSpy('Test');6 return null;7 })8import { createStorybookRootSpy } from 'storybook-root-spy';9import { mount } from 'enzyme';10import Test from './test';11describe('Test', () => {12 const spy = createStorybookRootSpy();13 const wrapper = mount(<Test />);14 it('should call the spy', () => {15 expect(spy).toHaveBeenCalled();16 });17});18import { callSpy } from 'storybook-root-spy';19import { storiesOf } from '@storybook/react-native';20storiesOf('Test', module)21 .add('Test', () => {22 callSpy('Test');23 return null;24 })25import { createStorybookRootSpy } from 'storybook-root-spy';26import { mount } from 'enzyme';27import Test from './test';28describe('Test', () => {29 const spy = createStorybookRootSpy();30 const wrapper = mount(<Test />);31 it('should call the spy', () => {32 expect(spy).toHaveBeenCalled();33 });34});35import { storiesOf } from '@storybook/vue';36import { callSpy } from 'storybook-root-spy';37storiesOf('Test', module)38 .add('Test', () => {39 callSpy('Test');40 return null;41 })42import { createStorybookRootSpy } from 'storybook-root-spy';43import { mount } from 'enzyme';44import Test from './test';45describe('Test', () => {46 const spy = createStorybookRootSpy();47 const wrapper = mount(<Test />);48 it('should call the spy', () => {49 expect(spy

Full Screen

Using AI Code Generation

copy

Full Screen

1import { callSpy } from 'storybook-root-scope';2export default {3};4export const Story = () => {5 const handleClick = () => {6 callSpy('Example/Story', 'handleClick', 'clicked');7 };8 return <button onClick={handleClick}>Click me</button>;9};10export const Story2 = () => {11 const handleClick = () => {12 callSpy('Example/Story2', 'handleClick', 'clicked');13 };14 return <button onClick={handleClick}>Click me</button>;15};16Story.storyName = 'Story';17Story2.storyName = 'Story2';18Story.parameters = {19};20Story2.parameters = {21};22import { callSpy, getSpy } from 'storybook-root-scope';23describe('Story', () => {24 it('should call spy', () => {25 callSpy('Example/Story', 'handleClick', 'clicked');26 expect(getSpy('Example/Story', 'handleClick')).toBeCalledWith('clicked');27 });28});29describe('Story2', () => {30 it('should call spy', () => {31 callSpy('Example/Story2', 'handleClick', 'clicked');32 expect(getSpy('Example/Story2', 'handleClick')).toBeCalledWith('clicked');33 });34});35import React from 'react';36import { addDecorator } from '@storybook/react';37import { withRootScope } from 'storybook-root-scope';38addDecorator(withRootScope);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { callSpy } from 'storybook-root/utils/test-utils';2import { getStorybookRoot } from 'storybook-root/utils/test-utils';3import { getStorybook } from '@storybook/react';4import { render } from '@testing-library/react';5import { StorybookRoot } from 'storybook-root';6import { storiesOf } from '@storybook/react';7storiesOf('test', module).add('test', () => {8 return <div>test</div>;9});10describe('test', () => {11 it('should pass', () => {12 const { container } = render(<StorybookRoot />);13 const storybookRoot = getStorybookRoot(container);14 const storybook = getStorybook();15 const story = storybook[0].stories[0];16 callSpy(storybookRoot, story.id, 'onClick');17 });18});19export const callSpy = (storybookRoot, storyId, spyName) => {20 const story = storybookRoot.find(storyId);21 const spy = story.props()[spyName];22 spy();23};24export const getStorybookRoot = (container) => {25 return container.querySelector('#storybook-root');26};27export const getStorybook = () => {28 return storiesOf('test', module);29};30import React from 'react';31import { storiesOf } from '@storybook/react';32import { StorybookRoot } from 'storybook-root';33storiesOf('storybook-root', module).add('storybook-root', () => {34 return <StorybookRoot />;35});36import React from 'react';37import { storiesOf } from '@storybook/react';38import { StorybookRoot } from 'storybook-root';39storiesOf('storybook-root', module).add('storybook-root', () => {40 return <StorybookRoot />;41});

Full Screen

Using AI Code Generation

copy

Full Screen

1import callSpy from 'storybook-root-spy';2const spy = callSpy('mySpy');3import { addRootSpy } from 'storybook-root-spy';4import { addRootSpy } from 'storybook-root-spy';5import { addRootSpy } from 'storybook-root-spy';6import { addRootSpy } from 'storybook-root-spy';7import { addRootSpy } from 'storybook-root-spy';8import { addRootSpy } from 'storybook-root-spy';9import { addRootSpy } from 'storybook-root-spy';10import { addRootSpy } from 'storybook-root-spy';

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