level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
199
0
petrpan-code/storybookjs/storybook/code/frameworks/nextjs/src/font
petrpan-code/storybookjs/storybook/code/frameworks/nextjs/src/font/babel/index.test.ts
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { transform } from '@babel/core'; import TransformFontImports from '.'; const example = ` import { Inter, Lora as FontLora, Roboto } from 'next/font/google' import localFont from 'next/font/local' const myFont = localFont({ src: './my-font.woff2' }) const roboto = Roboto({ weight: '400', }) const lora = FontLora({ weight: '400', }) const inter = Inter({ subsets: ['latin'], }); const randomObj = {} `; const exampleLegacy = ` import { Inter, Lora as FontLora, Roboto } from '@next/font/google' import localFont from '@next/font/local' const myFont = localFont({ src: './my-font.woff2' }) const roboto = Roboto({ weight: '400', }) const lora = FontLora({ weight: '400', }) const inter = Inter({ subsets: ['latin'], }); const randomObj = {} `; it('should transform next/font AST properly', () => { const { code } = transform(example, { plugins: [TransformFontImports] })!; expect(code).toMatchInlineSnapshot(` "import inter from \\"storybook-nextjs-font-loader?{\\\\\\"source\\\\\\":\\\\\\"next/font/google\\\\\\",\\\\\\"props\\\\\\":{\\\\\\"subsets\\\\\\":[\\\\\\"latin\\\\\\"]},\\\\\\"fontFamily\\\\\\":\\\\\\"Inter\\\\\\",\\\\\\"filename\\\\\\":\\\\\\"\\\\\\"}!next/font/google\\"; import lora from \\"storybook-nextjs-font-loader?{\\\\\\"source\\\\\\":\\\\\\"next/font/google\\\\\\",\\\\\\"props\\\\\\":{\\\\\\"weight\\\\\\":\\\\\\"400\\\\\\"},\\\\\\"fontFamily\\\\\\":\\\\\\"Lora\\\\\\",\\\\\\"filename\\\\\\":\\\\\\"\\\\\\"}!next/font/google\\"; import roboto from \\"storybook-nextjs-font-loader?{\\\\\\"source\\\\\\":\\\\\\"next/font/google\\\\\\",\\\\\\"props\\\\\\":{\\\\\\"weight\\\\\\":\\\\\\"400\\\\\\"},\\\\\\"fontFamily\\\\\\":\\\\\\"Roboto\\\\\\",\\\\\\"filename\\\\\\":\\\\\\"\\\\\\"}!next/font/google\\"; import myFont from \\"storybook-nextjs-font-loader?{\\\\\\"source\\\\\\":\\\\\\"next/font/local\\\\\\",\\\\\\"props\\\\\\":{\\\\\\"src\\\\\\":\\\\\\"./my-font.woff2\\\\\\"},\\\\\\"fontFamily\\\\\\":\\\\\\"localFont\\\\\\",\\\\\\"filename\\\\\\":\\\\\\"\\\\\\"}!next/font/local\\"; const randomObj = {};" `); }); it('should transform @next/font AST properly', () => { const { code } = transform(exampleLegacy, { plugins: [TransformFontImports] })!; expect(code).toMatchInlineSnapshot(` "import inter from \\"storybook-nextjs-font-loader?{\\\\\\"source\\\\\\":\\\\\\"@next/font/google\\\\\\",\\\\\\"props\\\\\\":{\\\\\\"subsets\\\\\\":[\\\\\\"latin\\\\\\"]},\\\\\\"fontFamily\\\\\\":\\\\\\"Inter\\\\\\",\\\\\\"filename\\\\\\":\\\\\\"\\\\\\"}!@next/font/google\\"; import lora from \\"storybook-nextjs-font-loader?{\\\\\\"source\\\\\\":\\\\\\"@next/font/google\\\\\\",\\\\\\"props\\\\\\":{\\\\\\"weight\\\\\\":\\\\\\"400\\\\\\"},\\\\\\"fontFamily\\\\\\":\\\\\\"Lora\\\\\\",\\\\\\"filename\\\\\\":\\\\\\"\\\\\\"}!@next/font/google\\"; import roboto from \\"storybook-nextjs-font-loader?{\\\\\\"source\\\\\\":\\\\\\"@next/font/google\\\\\\",\\\\\\"props\\\\\\":{\\\\\\"weight\\\\\\":\\\\\\"400\\\\\\"},\\\\\\"fontFamily\\\\\\":\\\\\\"Roboto\\\\\\",\\\\\\"filename\\\\\\":\\\\\\"\\\\\\"}!@next/font/google\\"; import myFont from \\"storybook-nextjs-font-loader?{\\\\\\"source\\\\\\":\\\\\\"@next/font/local\\\\\\",\\\\\\"props\\\\\\":{\\\\\\"src\\\\\\":\\\\\\"./my-font.woff2\\\\\\"},\\\\\\"fontFamily\\\\\\":\\\\\\"localFont\\\\\\",\\\\\\"filename\\\\\\":\\\\\\"\\\\\\"}!@next/font/local\\"; const randomObj = {};" `); });
443
0
petrpan-code/storybookjs/storybook/code/lib/channels
petrpan-code/storybookjs/storybook/code/lib/channels/src/index.test.ts
import type { ChannelTransport, Listener } from '.'; import { Channel } from '.'; jest.useFakeTimers(); describe('Channel', () => { let transport: ChannelTransport; let channel: Channel; beforeEach(() => { transport = { setHandler: jest.fn(), send: jest.fn() }; channel = new Channel({ transport }); }); describe('constructor', () => { it('should set the handler if handler is preset', () => { channel = new Channel({ transport }); expect(transport.setHandler).toHaveBeenCalled(); }); it('should not set transport if not passed as an argument', () => { channel = new Channel({}); expect(channel.hasTransport).toBeFalsy(); }); it('should set transport if passed as an argument', () => { channel = new Channel({ transport }); expect(channel.hasTransport).toBeTruthy(); }); it('should set isAsync to false as default value', () => { channel = new Channel({}); expect(channel.isAsync).toBeFalsy(); }); it('should set isAsync to true if passed as an argument', () => { channel = new Channel({ async: true }); expect(channel.isAsync).toBeTruthy(); }); }); describe('method:addListener', () => { it('should create one listener', () => { const eventName = 'event1'; channel.addListener(eventName, jest.fn()); expect(channel.listeners(eventName)?.length).toBe(1); }); }); describe('method:on', () => { it('should do the same as addListener', () => { const eventName = 'event1'; channel.on(eventName, jest.fn()); expect(channel.listeners(eventName)?.length).toBe(1); }); }); describe('method:off', () => { it('should remove listeners', () => { const eventName = 'event1'; const fn = jest.fn(); channel.on(eventName, fn); expect(channel.listeners(eventName)?.length).toBe(1); channel.off(eventName, fn); expect(channel.listeners(eventName)?.length).toBe(0); }); }); describe('method:emit', () => { it('should execute the callback fn of a listener', () => { const eventName = 'event1'; const listenerInputData = ['string1', 'string2', 'string3']; let listenerOutputData: string[] | null = null; const mockListener: Listener = (data) => { listenerOutputData = data; }; channel.addListener(eventName, mockListener); channel.emit(eventName, listenerInputData); expect(listenerOutputData).toBe(listenerInputData); }); it('should be callable with a spread operator as event arguments', () => { const eventName = 'event1'; const listenerInputData = ['string1', 'string2', 'string3']; let listenerOutputData: string[] | null = null; channel.addListener(eventName, (...data) => { listenerOutputData = data; }); channel.emit(eventName, ...listenerInputData); expect(listenerOutputData).toEqual(listenerInputData); }); it('should be callable with options on the event', () => { const eventName = 'event1'; const listenerInputData = [{ event: {}, options: { depth: 1 } }]; let listenerOutputData: any = null; channel.addListener(eventName, (...data) => { listenerOutputData = data; }); const sendSpy = jest.fn(); // @ts-expect-error (access private property for testing purposes) channel.transports.forEach((t) => { // eslint-disable-next-line no-param-reassign t.send = sendSpy; }); channel.emit(eventName, ...listenerInputData); expect(listenerOutputData).toEqual(listenerInputData); expect(sendSpy.mock.calls[0][1]).toEqual({ depth: 1 }); }); it('should use setImmediate if async is true', () => { channel = new Channel({ async: true, transport }); channel.addListener('event1', jest.fn()); }); }); describe('method:eventNames', () => { it('should return a list of all registered events', () => { const eventNames = ['event1', 'event2', 'event3']; eventNames.forEach((eventName) => channel.addListener(eventName, jest.fn())); expect(channel.eventNames()).toEqual(eventNames); }); }); describe('method:listenerCount', () => { it('should return a list of all registered events', () => { const events = [ { eventName: 'event1', listeners: [jest.fn(), jest.fn(), jest.fn()], listenerCount: 0 }, { eventName: 'event2', listeners: [jest.fn()], listenerCount: 0 }, ]; events.forEach((event) => { event.listeners.forEach((listener) => { channel.addListener(event.eventName, listener); // eslint-disable-next-line no-plusplus, no-param-reassign event.listenerCount++; }); }); events.forEach((event) => { expect(channel.listenerCount(event.eventName)).toBe(event.listenerCount); }); }); }); describe('method:once', () => { it('should execute a listener once and remove it afterwards', () => { const eventName = 'event1'; channel.once(eventName, jest.fn()); channel.emit(eventName); expect(channel.listenerCount(eventName)).toBe(0); }); it('should pass all event arguments correctly to the listener', () => { const eventName = 'event1'; const listenerInputData = ['string1', 'string2', 'string3']; let listenerOutputData = null; const mockListener: Listener = (data: string[]) => { listenerOutputData = data; }; channel.once(eventName, (args) => mockListener(args)); channel.emit(eventName, listenerInputData); expect(listenerOutputData).toEqual(listenerInputData); }); it('should be removable', () => { const eventName = 'event1'; const listenerToBeRemoved = jest.fn(); channel.once(eventName, listenerToBeRemoved); channel.removeListener(eventName, listenerToBeRemoved); }); }); describe('method:removeAllListeners', () => { it('should remove all listeners', () => { const eventName1 = 'event1'; const eventName2 = 'event2'; const listeners1 = [jest.fn(), jest.fn(), jest.fn()]; const listeners2 = [jest.fn()]; listeners1.forEach((fn) => channel.addListener(eventName1, fn)); listeners2.forEach((fn) => channel.addListener(eventName2, fn)); channel.removeAllListeners(); expect(channel.listenerCount(eventName1)).toBe(0); expect(channel.listenerCount(eventName2)).toBe(0); }); it('should remove all listeners of a certain event', () => { const eventName = 'event1'; const listeners = [jest.fn(), jest.fn(), jest.fn()]; listeners.forEach((fn) => channel.addListener(eventName, fn)); expect(channel.listenerCount(eventName)).toBe(listeners.length); channel.removeAllListeners(eventName); expect(channel.listenerCount(eventName)).toBe(0); }); }); describe('method:removeListener', () => { it('should remove one listener', () => { const eventName = 'event1'; const listenerToBeRemoved = jest.fn(); const listeners = [jest.fn(), jest.fn()]; const findListener = (listener: Listener) => channel.listeners(eventName)?.find((_listener) => _listener === listener); listeners.forEach((fn) => channel.addListener(eventName, fn)); channel.addListener(eventName, listenerToBeRemoved); expect(findListener(listenerToBeRemoved)).toBe(listenerToBeRemoved); channel.removeListener(eventName, listenerToBeRemoved); expect(findListener(listenerToBeRemoved)).toBeUndefined(); }); }); });
485
0
petrpan-code/storybookjs/storybook/code/lib/cli
petrpan-code/storybookjs/storybook/code/lib/cli/src/detect.test.ts
import * as fs from 'fs'; import { logger } from '@storybook/node-logger'; import { detect, detectFrameworkPreset, detectLanguage } from './detect'; import { ProjectType, SupportedLanguage } from './project_types'; import type { JsPackageManager, PackageJsonWithMaybeDeps } from './js-package-manager'; jest.mock('./helpers', () => ({ isNxProject: jest.fn(), })); jest.mock('fs', () => ({ existsSync: jest.fn(), stat: jest.fn(), lstat: jest.fn(), access: jest.fn(), })); jest.mock('fs-extra', () => ({ pathExistsSync: jest.fn(() => true), })); jest.mock('path', () => ({ // make it return just the second path, for easier testing join: jest.fn((_, p) => p), })); jest.mock('@storybook/node-logger'); const MOCK_FRAMEWORK_FILES: { name: string; files: Record<'package.json', PackageJsonWithMaybeDeps> | Record<string, string>; }[] = [ { name: ProjectType.SFC_VUE, files: { 'package.json': { dependencies: { vuetify: '1.0.0', }, devDependencies: { 'vue-loader': '1.0.0', }, }, }, }, { name: ProjectType.VUE, files: { 'package.json': { dependencies: { vue: '1.0.0', }, }, }, }, { name: ProjectType.VUE3, files: { 'package.json': { dependencies: { vue: '^3.0.0', }, }, }, }, { name: ProjectType.VUE3, files: { 'package.json': { dependencies: { // Testing the `next` tag too vue: 'next', }, }, }, }, { name: ProjectType.EMBER, files: { 'package.json': { devDependencies: { 'ember-cli': '1.0.0', }, }, }, }, { name: ProjectType.REACT_PROJECT, files: { 'package.json': { peerDependencies: { react: '1.0.0', }, }, }, }, { name: ProjectType.QWIK, files: { 'package.json': { devDependencies: { '@builder.io/qwik': '1.0.0', }, }, }, }, { name: ProjectType.REACT_NATIVE, files: { 'package.json': { dependencies: { 'react-native': '1.0.0', }, devDependencies: { 'react-native-scripts': '1.0.0', }, }, }, }, { name: ProjectType.REACT_SCRIPTS, files: { 'package.json': { devDependencies: { 'react-scripts': '1.0.0', }, }, }, }, { name: ProjectType.WEBPACK_REACT, files: { 'package.json': { dependencies: { react: '1.0.0', }, devDependencies: { webpack: '1.0.0', }, }, }, }, { name: ProjectType.REACT, files: { 'package.json': { dependencies: { react: '1.0.0', }, }, }, }, { name: ProjectType.NEXTJS, files: { 'package.json': { dependencies: { next: '^9.0.0', }, }, }, }, { name: ProjectType.ANGULAR, files: { 'package.json': { dependencies: { '@angular/core': '1.0.0', }, }, }, }, { name: ProjectType.WEB_COMPONENTS, files: { 'package.json': { dependencies: { 'lit-element': '1.0.0', }, }, }, }, { name: ProjectType.WEB_COMPONENTS, files: { 'package.json': { dependencies: { 'lit-html': '1.4.1', }, }, }, }, { name: ProjectType.WEB_COMPONENTS, files: { 'package.json': { dependencies: { 'lit-html': '2.0.0-rc.3', }, }, }, }, { name: ProjectType.WEB_COMPONENTS, files: { 'package.json': { dependencies: { lit: '2.0.0-rc.2', }, }, }, }, { name: ProjectType.PREACT, files: { 'package.json': { dependencies: { preact: '1.0.0', }, }, }, }, { name: ProjectType.SVELTE, files: { 'package.json': { dependencies: { svelte: '1.0.0', }, }, }, }, ]; describe('Detect', () => { it(`should return type HTML if html option is passed`, async () => { const packageManager = { retrievePackageJson: () => Promise.resolve({ dependencies: {}, devDependencies: {} }), getAllDependencies: () => Promise.resolve({}), getPackageVersion: () => Promise.resolve(null), } as Partial<JsPackageManager>; await expect(detect(packageManager as any, { html: true })).resolves.toBe(ProjectType.HTML); }); it(`should return language javascript if the TS dependency is present but less than minimum supported`, async () => { (logger.warn as jest.MockedFunction<typeof logger.warn>).mockClear(); const packageManager = { retrievePackageJson: () => Promise.resolve({ dependencies: {}, devDependencies: { typescript: '1.0.0', }, }), getAllDependencies: () => Promise.resolve({ typescript: '1.0.0', }), getPackageVersion: (packageName) => { switch (packageName) { case 'typescript': return Promise.resolve('1.0.0'); default: return Promise.resolve(null); } }, } as Partial<JsPackageManager>; await expect(detectLanguage(packageManager as any)).resolves.toBe(SupportedLanguage.JAVASCRIPT); expect(logger.warn).toHaveBeenCalledWith( 'Detected TypeScript < 3.8, populating with JavaScript examples' ); }); it(`should return language typescript-3-8 if the TS dependency is >=3.8 and <4.9`, async () => { await expect( detectLanguage({ retrievePackageJson: () => Promise.resolve({ dependencies: {}, devDependencies: { typescript: '3.8.0', }, }), getAllDependencies: () => Promise.resolve({ typescript: '3.8.0', }), getPackageVersion: (packageName: string) => { switch (packageName) { case 'typescript': return Promise.resolve('3.8.0'); default: return Promise.resolve(null); } }, } as Partial<JsPackageManager> as JsPackageManager) ).resolves.toBe(SupportedLanguage.TYPESCRIPT_3_8); await expect( detectLanguage({ retrievePackageJson: () => Promise.resolve({ dependencies: {}, devDependencies: { typescript: '4.8.0', }, }), getAllDependencies: () => Promise.resolve({ typescript: '4.8.0', }), getPackageVersion: (packageName: string) => { switch (packageName) { case 'typescript': return Promise.resolve('4.8.0'); default: return Promise.resolve(null); } }, } as Partial<JsPackageManager> as JsPackageManager) ).resolves.toBe(SupportedLanguage.TYPESCRIPT_3_8); }); it(`should return language typescript-4-9 if the dependency is >TS4.9`, async () => { await expect( detectLanguage({ retrievePackageJson: () => Promise.resolve({ dependencies: {}, devDependencies: { typescript: '4.9.1', }, }), getAllDependencies: () => Promise.resolve({ typescript: '4.9.1', }), getPackageVersion: (packageName: string) => { switch (packageName) { case 'typescript': return Promise.resolve('4.9.1'); default: return Promise.resolve(null); } }, } as Partial<JsPackageManager> as JsPackageManager) ).resolves.toBe(SupportedLanguage.TYPESCRIPT_4_9); }); it(`should return language typescript if the dependency is =TS4.9`, async () => { await expect( detectLanguage({ retrievePackageJson: () => Promise.resolve({ dependencies: {}, devDependencies: { typescript: '4.9.0', }, }), getAllDependencies: () => Promise.resolve({ typescript: '4.9.0', }), getPackageVersion: (packageName: string) => { switch (packageName) { case 'typescript': return Promise.resolve('4.9.0'); default: return Promise.resolve(null); } }, } as Partial<JsPackageManager> as JsPackageManager) ).resolves.toBe(SupportedLanguage.TYPESCRIPT_4_9); }); it(`should return language typescript if the dependency is =TS4.9beta`, async () => { await expect( detectLanguage({ retrievePackageJson: () => Promise.resolve({ dependencies: {}, devDependencies: { typescript: '4.9.0-beta', }, }), getAllDependencies: () => Promise.resolve({ typescript: '4.9.0-beta', }), getPackageVersion: (packageName: string) => { switch (packageName) { case 'typescript': return Promise.resolve('4.9.0-beta'); default: return Promise.resolve(null); } }, } as Partial<JsPackageManager> as JsPackageManager) ).resolves.toBe(SupportedLanguage.TYPESCRIPT_3_8); }); it(`should return language javascript by default`, async () => { await expect( detectLanguage({ retrievePackageJson: () => Promise.resolve({ dependencies: {}, devDependencies: {} }), getAllDependencies: () => Promise.resolve({}), getPackageVersion: () => { return Promise.resolve(null); }, } as Partial<JsPackageManager> as JsPackageManager) ).resolves.toBe(SupportedLanguage.JAVASCRIPT); }); it(`should return language Javascript even when Typescript is detected in the node_modules but not listed as a direct dependency`, async () => { await expect( detectLanguage({ retrievePackageJson: () => Promise.resolve({ dependencies: {}, devDependencies: {} }), getAllDependencies: () => Promise.resolve({}), getPackageVersion: (packageName) => { switch (packageName) { case 'typescript': return Promise.resolve('4.9.0'); default: return Promise.resolve(null); } }, } as Partial<JsPackageManager> as JsPackageManager) ).resolves.toBe(SupportedLanguage.JAVASCRIPT); }); describe('detectFrameworkPreset should return', () => { afterEach(() => { jest.clearAllMocks(); }); MOCK_FRAMEWORK_FILES.forEach((structure) => { it(`${structure.name}`, () => { (fs.existsSync as jest.Mock).mockImplementation((filePath) => { return Object.keys(structure.files).includes(filePath); }); const result = detectFrameworkPreset( structure.files['package.json'] as PackageJsonWithMaybeDeps ); expect(result).toBe(structure.name); }); }); it(`UNDETECTED for unknown frameworks`, () => { const result = detectFrameworkPreset(); expect(result).toBe(ProjectType.UNDETECTED); }); // TODO(blaine): Remove once Nuxt3 is supported it(`UNSUPPORTED for Nuxt framework above version 3.0.0`, () => { const result = detectFrameworkPreset({ dependencies: { nuxt: '3.0.0', }, }); expect(result).toBe(ProjectType.UNSUPPORTED); }); // TODO: The mocking in this test causes tests after it to fail it('REACT_SCRIPTS for custom react scripts config', () => { const forkedReactScriptsConfig = { '/node_modules/.bin/react-scripts': 'file content', }; (fs.existsSync as jest.Mock).mockImplementation((filePath) => { return Object.keys(forkedReactScriptsConfig).includes(filePath); }); const result = detectFrameworkPreset(); expect(result).toBe(ProjectType.REACT_SCRIPTS); }); }); });
491
0
petrpan-code/storybookjs/storybook/code/lib/cli
petrpan-code/storybookjs/storybook/code/lib/cli/src/helpers.test.ts
import fs from 'fs'; import fse from 'fs-extra'; import * as helpers from './helpers'; import type { JsPackageManager } from './js-package-manager'; import type { SupportedRenderers } from './project_types'; import { SupportedLanguage } from './project_types'; jest.mock('fs', () => ({ existsSync: jest.fn(), })); jest.mock('./dirs', () => ({ getRendererDir: (_: JsPackageManager, renderer: string) => `@storybook/${renderer}`, getCliDir: () => '@storybook/cli', })); jest.mock('fs-extra', () => ({ copySync: jest.fn(() => ({})), copy: jest.fn(() => ({})), ensureDir: jest.fn(() => {}), existsSync: jest.fn(), pathExists: jest.fn(), readFile: jest.fn(() => ''), writeFile: jest.fn(), })); jest.mock('find-up', () => ({ sync: jest.fn(), })); jest.mock('path', () => { const path = jest.requireActual('path'); return { // make it return just the second path, for easier testing resolve: jest.fn((_, p) => p), dirname: path.dirname, join: path.join, }; }); const packageManagerMock = { retrievePackageJson: async () => ({ dependencies: {}, devDependencies: {} }), } as JsPackageManager; describe('Helpers', () => { beforeEach(() => { jest.clearAllMocks(); }); describe('copyTemplate', () => { it(`should copy template files when directory is present`, () => { const csfDirectory = `template-csf/`; (fs.existsSync as jest.Mock).mockImplementation((filePath) => { return true; }); helpers.copyTemplate(''); const copySyncSpy = jest.spyOn(fse, 'copySync'); expect(copySyncSpy).toHaveBeenCalledWith(csfDirectory, expect.anything(), expect.anything()); }); it(`should throw an error if template directory cannot be found`, () => { (fs.existsSync as jest.Mock).mockImplementation((filePath) => { return false; }); expect(() => { helpers.copyTemplate(''); }).toThrowError("Couldn't find template dir"); }); }); it.each` language | exists | expected ${'javascript'} | ${['js', 'ts-4-9']} | ${'/js'} ${'typescript-4-9'} | ${['js', 'ts-4-9']} | ${'/ts-4-9'} ${'typescript-4-9'} | ${['js', 'ts-3-8']} | ${'/ts-3-8'} ${'typescript-3-8'} | ${['js', 'ts-3-8', 'ts-4-9']} | ${'/ts-3-8'} ${'typescript-3-8'} | ${['js', 'ts-4-9']} | ${'/js'} ${'typescript-4-9'} | ${['js']} | ${'/js'} ${'javascript'} | ${[]} | ${''} ${'typescript-4-9'} | ${[]} | ${''} `( `should copy $expected when folder $exists exists for language $language`, async ({ language, exists, expected }) => { const componentsDirectory = exists.map( (folder: string) => `@storybook/react/template/cli/${folder}` ); (fse.pathExists as jest.Mock).mockImplementation( (filePath) => componentsDirectory.includes(filePath) || filePath === '@storybook/react/template/cli' ); await helpers.copyTemplateFiles({ renderer: 'react', language, packageManager: packageManagerMock, }); const copySpy = jest.spyOn(fse, 'copy'); expect(copySpy).toHaveBeenNthCalledWith( 1, '@storybook/cli/rendererAssets/common', './stories', expect.anything() ); const expectedDirectory = `@storybook/react/template/cli${expected}`; expect(copySpy).toHaveBeenNthCalledWith(2, expectedDirectory, './stories', expect.anything()); } ); it(`should copy to src folder when exists`, async () => { (fse.pathExists as jest.Mock).mockImplementation((filePath) => { return filePath === '@storybook/react/template/cli' || filePath === './src'; }); await helpers.copyTemplateFiles({ renderer: 'react', language: SupportedLanguage.JAVASCRIPT, packageManager: packageManagerMock, }); expect(fse.copy).toHaveBeenCalledWith(expect.anything(), './src/stories', expect.anything()); }); it(`should copy to root folder when src doesn't exist`, async () => { (fse.pathExists as jest.Mock).mockImplementation((filePath) => { return filePath === '@storybook/react/template/cli'; }); await helpers.copyTemplateFiles({ renderer: 'react', language: SupportedLanguage.JAVASCRIPT, packageManager: packageManagerMock, }); expect(fse.copy).toHaveBeenCalledWith(expect.anything(), './stories', expect.anything()); }); it(`should throw an error for unsupported renderer`, async () => { const renderer = 'unknown renderer' as SupportedRenderers; const expectedMessage = `Unsupported renderer: ${renderer}`; await expect( helpers.copyTemplateFiles({ renderer, language: SupportedLanguage.JAVASCRIPT, packageManager: packageManagerMock, }) ).rejects.toThrowError(expectedMessage); }); describe('getStorybookVersionSpecifier', () => { it(`should return the specifier if storybook lib exists in package.json`, () => { expect( helpers.getStorybookVersionSpecifier({ dependencies: {}, devDependencies: { '@storybook/react': '^x.x.x', }, }) ).toEqual('^x.x.x'); }); it(`should throw an error if no package is found`, () => { expect(() => { helpers.getStorybookVersionSpecifier({ dependencies: {}, devDependencies: { 'something-else': '^x.x.x', }, }); }).toThrowError("Couldn't find any official storybook packages in package.json"); }); }); });
497
0
petrpan-code/storybookjs/storybook/code/lib/cli
petrpan-code/storybookjs/storybook/code/lib/cli/src/project_types.test.ts
import { installableProjectTypes, SUPPORTED_RENDERERS } from './project_types'; describe('installableProjectTypes should have an entry for the supported framework', () => { SUPPORTED_RENDERERS.forEach((framework) => { it(`${framework}`, () => { expect(installableProjectTypes.includes(framework.replace(/-/g, '_'))).toBe(true); }); }); });
502
0
petrpan-code/storybookjs/storybook/code/lib/cli
petrpan-code/storybookjs/storybook/code/lib/cli/src/upgrade.test.ts
import { addExtraFlags, addNxPackagesToReject, getStorybookVersion } from './upgrade'; describe.each([ ['│ │ │ ├── @babel/code-frame@7.10.3 deduped', null], [ '│ ├── @storybook/theming@6.0.0-beta.37 extraneous', { package: '@storybook/theming', version: '6.0.0-beta.37' }, ], [ '├─┬ @storybook/preset-create-react-app@3.1.2', { package: '@storybook/preset-create-react-app', version: '3.1.2' }, ], ['│ ├─┬ @storybook/node-logger@5.3.19', { package: '@storybook/node-logger', version: '5.3.19' }], [ 'npm ERR! peer dep missing: @storybook/react@>=5.2, required by @storybook/preset-create-react-app@3.1.2', null, ], ])('getStorybookVersion', (input, output) => { it(`${input}`, () => { expect(getStorybookVersion(input)).toEqual(output); }); }); describe('extra flags', () => { const extraFlags = { 'react-scripts@<5': ['--foo'], }; const devDependencies = {}; it('package matches constraints', () => { expect( addExtraFlags(extraFlags, [], { dependencies: { 'react-scripts': '4' }, devDependencies }) ).toEqual(['--foo']); }); it('package prerelease matches constraints', () => { expect( addExtraFlags(extraFlags, [], { dependencies: { 'react-scripts': '4.0.0-alpha.0' }, devDependencies, }) ).toEqual(['--foo']); }); it('package not matches constraints', () => { expect( addExtraFlags(extraFlags, [], { dependencies: { 'react-scripts': '5.0.0-alpha.0' }, devDependencies, }) ).toEqual([]); }); it('no package not matches constraints', () => { expect( addExtraFlags(extraFlags, [], { dependencies: {}, devDependencies, }) ).toEqual([]); }); }); describe('addNxPackagesToReject', () => { it('reject exists and is in regex pattern', () => { const flags = ['--reject', '/preset-create-react-app/', '--some-flag', 'hello']; expect(addNxPackagesToReject(flags)).toMatchObject([ '--reject', '/(preset-create-react-app|@nrwl/storybook|@nx/storybook)/', '--some-flag', 'hello', ]); }); it('reject exists and is in unknown pattern', () => { const flags = ['--some-flag', 'hello', '--reject', '@storybook/preset-create-react-app']; expect(addNxPackagesToReject(flags)).toMatchObject([ '--some-flag', 'hello', '--reject', '@storybook/preset-create-react-app,@nrwl/storybook,@nx/storybook', ]); }); it('reject does not exist', () => { const flags = ['--some-flag', 'hello']; expect(addNxPackagesToReject(flags)).toMatchObject([ '--some-flag', 'hello', '--reject', '@nrwl/storybook,@nx/storybook', ]); }); });
504
0
petrpan-code/storybookjs/storybook/code/lib/cli
petrpan-code/storybookjs/storybook/code/lib/cli/src/utils.test.ts
import { isCorePackage } from './utils'; describe('UTILS', () => { describe.each([ ['@storybook/react', true], ['@storybook/node-logger', true], ['@storybook/addon-info', true], ['@storybook/something-random', true], ['@storybook/preset-create-react-app', false], ['@storybook/linter-config', false], ['@storybook/design-system', false], ['@storybook/addon-styling', false], ['@storybook/addon-styling-webpack', false], ['@nx/storybook', false], ['@nrwl/storybook', false], ])('isCorePackage', (input, output) => { it(`It should return "${output}" when given "${input}"`, () => { expect(isCorePackage(input)).toEqual(output); }); }); });
507
0
petrpan-code/storybookjs/storybook/code/lib/cli
petrpan-code/storybookjs/storybook/code/lib/cli/src/warn.test.ts
import globby from 'globby'; import { logger } from '@storybook/node-logger'; import { warn } from './warn'; jest.mock('@storybook/node-logger'); jest.mock('globby'); describe('warn', () => { beforeEach(() => { jest.clearAllMocks(); }); describe('when TypeScript is installed as a dependency', () => { it('should not warn', () => { warn({ hasTSDependency: true, }); expect(logger.warn).not.toHaveBeenCalled(); }); }); describe('when TypeScript is not installed as a dependency', () => { it('should not warn if `.tsx?` files are not found', () => { (globby.sync as jest.Mock).mockReturnValueOnce([]); warn({ hasTSDependency: false, }); expect(logger.warn).toHaveBeenCalledTimes(0); }); it('should warn if `.tsx?` files are found', () => { (globby.sync as jest.Mock).mockReturnValueOnce(['a.ts']); warn({ hasTSDependency: false, }); expect(logger.warn).toHaveBeenCalledTimes(2); }); }); });
512
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/add-react.test.ts
import type { StorybookConfig } from '@storybook/types'; import type { JsPackageManager, PackageJson } from '../../js-package-manager'; import { addReact } from './add-react'; const checkAddReact = async (packageJson: PackageJson) => { const packageManager = { retrievePackageJson: async () => ({ dependencies: {}, devDependencies: {}, ...packageJson }), } as JsPackageManager; return addReact.check({ packageManager, mainConfig: {} as StorybookConfig, storybookVersion: '7.0.0', }); }; describe('addReact fix', () => { it('should no-op when not using docs or essentials', async () => { await expect(checkAddReact({ dependencies: {} })).resolves.toBeFalsy(); }); it('should no-op when react/react-dom are already installed', async () => { await expect( checkAddReact({ dependencies: { react: '*' }, devDependencies: { '@storybook/addon-docs': '*', 'react-dom': '*' }, }) ).resolves.toBeFalsy(); }); it('should add react when it is missing', async () => { await expect( checkAddReact({ dependencies: {}, devDependencies: { '@storybook/addon-docs': '*', 'react-dom': '*' }, }) ).resolves.toMatchInlineSnapshot(` Object { "additionalDependencies": Array [ "react", ], "dependents": Array [ "@storybook/addon-docs", ], } `); }); it('should add reac-dom when it is missing', async () => { await expect( checkAddReact({ dependencies: {}, devDependencies: { '@storybook/addon-essentials': '*', react: '*' }, }) ).resolves.toMatchInlineSnapshot(` Object { "additionalDependencies": Array [ "react-dom", ], "dependents": Array [ "@storybook/addon-essentials", ], } `); }); });
514
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/angular-builders-multiproject.test.ts
import type { StorybookConfig } from '@storybook/types'; import type { JsPackageManager } from '../../js-package-manager'; import { angularBuildersMultiproject } from './angular-builders-multiproject'; import * as helpers from '../../helpers'; import * as angularHelpers from '../../generators/ANGULAR/helpers'; const checkAngularBuilders = async ({ packageManager, mainConfig = {}, }: { packageManager: Partial<JsPackageManager>; mainConfig?: Partial<StorybookConfig>; }) => { return angularBuildersMultiproject.check({ packageManager: packageManager as any, mainConfig: mainConfig as any, storybookVersion: '7.0.0', }); }; jest.mock('../../helpers', () => ({ ...jest.requireActual('../../helpers'), isNxProject: jest.fn(), })); jest.mock('../../generators/ANGULAR/helpers', () => ({ ...jest.requireActual('../../generators/ANGULAR/helpers'), AngularJSON: jest.fn(), })); describe('is Nx project', () => { const packageManager = { getPackageVersion: () => { return null; }, } as Partial<JsPackageManager>; beforeEach(() => { (helpers.isNxProject as any as jest.SpyInstance).mockResolvedValue(true); }); it('should return null', async () => { await expect(checkAngularBuilders({ packageManager })).resolves.toBeNull(); }); }); describe('is not Nx project', () => { beforeEach(() => { (helpers.isNxProject as any as jest.SpyInstance).mockResolvedValue(false); }); describe('angular builders', () => { afterEach(jest.restoreAllMocks); describe('Angular not found', () => { const packageManager = { getPackageVersion: jest.fn().mockResolvedValue(null), } as Partial<JsPackageManager>; it('should return null', async () => { await expect( checkAngularBuilders({ packageManager, mainConfig: { framework: '@storybook/angular' } }) ).resolves.toBeNull(); }); }); describe('Angular < 14.0.0', () => { const packageManager = { getPackageVersion: (packageName) => { if (packageName === '@angular/core') { return Promise.resolve('12.0.0'); } return null; }, } as Partial<JsPackageManager>; it('should return null', async () => { await expect( checkAngularBuilders({ packageManager, mainConfig: { framework: '@storybook/angular' } }) ).resolves.toBeNull(); }); }); describe('Angular >= 14.0.0', () => { const packageManager = { getPackageVersion: (packageName) => { if (packageName === '@angular/core') { return Promise.resolve('15.0.0'); } return null; }, } as Partial<JsPackageManager>; describe('has one Storybook builder defined', () => { beforeEach(() => { // Mock AngularJSON.constructor (angularHelpers.AngularJSON as jest.Mock).mockImplementation(() => ({ hasStorybookBuilder: true, })); }); it('should return null', async () => { await expect( checkAngularBuilders({ packageManager, mainConfig: { framework: '@storybook/angular' }, }) ).resolves.toBeNull(); }); }); describe('has one project', () => { beforeEach(() => { // Mock AngularJSON.constructor (angularHelpers.AngularJSON as jest.Mock).mockImplementation(() => ({ hasStorybookBuilder: false, projects: { project1: { root: 'project1', architect: {} }, }, rootProject: 'project1', })); }); it('should return null', async () => { await expect( checkAngularBuilders({ packageManager, mainConfig: { framework: '@storybook/angular' }, }) ).resolves.toBeNull(); }); }); describe('has multiple projects without root project defined', () => { beforeEach(() => { // Mock AngularJSON.constructor (angularHelpers.AngularJSON as jest.Mock).mockImplementation(() => ({ hasStorybookBuilder: false, projects: { project1: { root: 'project1', architect: {} }, project2: { root: 'project2', architect: {} }, }, rootProject: null, })); }); it('should return an empty object', async () => { await expect( checkAngularBuilders({ packageManager, mainConfig: { framework: '@storybook/angular' }, }) ).resolves.toMatchObject({}); }); }); }); }); });
516
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/angular-builders.test.ts
import type { StorybookConfig } from '@storybook/types'; import { angularBuilders } from './angular-builders'; import * as helpers from '../../helpers'; import * as angularHelpers from '../../generators/ANGULAR/helpers'; import type { JsPackageManager } from '../../js-package-manager'; const checkAngularBuilders = async ({ packageManager, mainConfig = {}, storybookVersion = '7.0.0', }: { packageManager: Partial<JsPackageManager>; mainConfig?: Partial<StorybookConfig>; storybookVersion?: string; }) => { return angularBuilders.check({ packageManager: packageManager as any, storybookVersion, mainConfig: mainConfig as any, }); }; jest.mock('../../helpers', () => ({ ...jest.requireActual('../../helpers'), isNxProject: jest.fn(), })); jest.mock('../../generators/ANGULAR/helpers', () => ({ ...jest.requireActual('../../generators/ANGULAR/helpers'), AngularJSON: jest.fn(), })); describe('is Nx project', () => { beforeEach(() => { (helpers.isNxProject as any as jest.SpyInstance).mockResolvedValue(true); }); const packageManager = { getPackageVersion: jest.fn().mockImplementation((packageName) => { if (packageName === '@angular/core') { return '12.0.0'; } return null; }), } as Partial<JsPackageManager>; it('should return null', async () => { await expect(checkAngularBuilders({ packageManager })).resolves.toBeNull(); }); }); describe('is not Nx project', () => { beforeEach(() => { (helpers.isNxProject as any as jest.SpyInstance).mockResolvedValue(false); }); describe('angular builders', () => { afterEach(jest.restoreAllMocks); describe('Angular not found', () => { const packageManager = { getPackageVersion: jest.fn().mockReturnValue(null), } as Partial<JsPackageManager>; it('should return null', async () => { await expect(checkAngularBuilders({ packageManager })).resolves.toBeNull(); }); }); describe('Angular < 14.0.0', () => { const packageManager = { getPackageVersion: (packageName: string) => { if (packageName === '@angular/core') { return Promise.resolve('12.0.0'); } return null; }, } as Partial<JsPackageManager>; it('should throw an Error', async () => { await expect( checkAngularBuilders({ packageManager, mainConfig: { framework: '@storybook/angular' } }) ).rejects.toThrowErrorMatchingSnapshot(); }); }); describe('Angular >= 14.0.0', () => { const packageManager = { getPackageVersion: (packageName) => { if (packageName === '@angular/core') { return Promise.resolve('15.0.0'); } return null; }, } as Partial<JsPackageManager>; describe('has one Storybook builder defined', () => { beforeEach(() => { // Mock AngularJSON.constructor (angularHelpers.AngularJSON as jest.Mock).mockImplementation(() => ({ hasStorybookBuilder: true, })); }); it('should return null', async () => { await expect( checkAngularBuilders({ packageManager, mainConfig: { framework: '@storybook/angular' }, }) ).resolves.toBeNull(); }); }); describe('has multiple projects without root project defined', () => { beforeEach(() => { // Mock AngularJSON.constructor (angularHelpers.AngularJSON as jest.Mock).mockImplementation(() => ({ hasStorybookBuilder: false, projects: { project1: { root: 'project1', architect: {} }, project2: { root: 'project2', architect: {} }, }, rootProject: null, })); }); it('should return null', async () => { await expect( checkAngularBuilders({ packageManager, mainConfig: { framework: '@storybook/angular' }, }) ).resolves.toBeNull(); }); }); describe('has one project', () => { beforeEach(() => { // Mock AngularJSON.constructor (angularHelpers.AngularJSON as jest.Mock).mockImplementation(() => ({ hasStorybookBuilder: false, projects: { project1: { root: 'project1', architect: {} }, }, rootProject: 'project1', })); }); it('should proceed and return data', async () => { await expect( checkAngularBuilders({ packageManager, mainConfig: { framework: '@storybook/angular' }, }) ).resolves.toMatchObject({ mainConfig: {}, packageManager: {}, }); }); }); }); }); });
518
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/autodocs-true.test.ts
import type { StorybookConfig } from '@storybook/types'; import type { PackageJson } from '../../js-package-manager'; import { makePackageManager } from '../helpers/testing-helpers'; import { autodocsTrue } from './autodocs-true'; const checkAutodocs = async ({ packageJson = {}, main: mainConfig, }: { packageJson?: PackageJson; main: Partial<StorybookConfig> & Record<string, unknown>; }) => { return autodocsTrue.check({ packageManager: makePackageManager(packageJson), mainConfig: mainConfig as StorybookConfig, storybookVersion: '7.0.0', }); }; describe('autodocs-true fix', () => { afterEach(jest.restoreAllMocks); it('should skip when docs.autodocs is already defined', async () => { await expect(checkAutodocs({ main: { docs: { autodocs: 'tag' } } })).resolves.toBeFalsy(); }); it('should throw when docs.docsPage contains invalid value', async () => { const main = { docs: { docsPage: 123 } } as any; await expect(checkAutodocs({ main })).rejects.toThrow(); }); it('should prompt when using docs.docsPage legacy property', async () => { const main = { docs: { docsPage: true } } as any; await expect(checkAutodocs({ main })).resolves.toEqual({ value: 'tag', }); }); it('should prompt when not using docs.autodocs', async () => { await expect(checkAutodocs({ main: {} })).resolves.toEqual({ value: true, }); }); });
520
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/bare-mdx-stories-glob.test.ts
/// <reference types="@types/jest" />; import type { StorybookConfig } from '@storybook/types'; import type { PackageJson } from '../../js-package-manager'; import { ansiRegex } from '../helpers/cleanLog'; import { makePackageManager } from '../helpers/testing-helpers'; import type { BareMdxStoriesGlobRunOptions } from './bare-mdx-stories-glob'; import { bareMdxStoriesGlob } from './bare-mdx-stories-glob'; const checkBareMdxStoriesGlob = async ({ packageJson, main: mainConfig, storybookVersion = '7.0.0', }: { packageJson: PackageJson; main?: Partial<StorybookConfig> & Record<string, unknown>; storybookVersion?: string; }) => { return bareMdxStoriesGlob.check({ mainConfig: mainConfig as StorybookConfig, packageManager: makePackageManager(packageJson), storybookVersion, }); }; describe('bare-mdx fix', () => { afterEach(jest.restoreAllMocks); describe('should no-op', () => { it('in SB < v7.0.0', async () => { const packageJson = { dependencies: { '@storybook/react': '^6.2.0' }, }; const main = { stories: ['../**/*.stories.mdx'] }; await expect( checkBareMdxStoriesGlob({ packageJson, main, storybookVersion: '6.5.0' }) ).resolves.toBeFalsy(); }); describe('in SB >= v7.0.0', () => { it('without main', async () => { const packageJson = { dependencies: { '@storybook/react': '^7.0.0' }, }; await expect(checkBareMdxStoriesGlob({ packageJson })).rejects.toThrow(); }); it('without stories field in main', async () => { const packageJson = { dependencies: { '@storybook/react': '^7.0.0' }, }; const main = {}; await expect(checkBareMdxStoriesGlob({ packageJson, main })).rejects.toThrow(); }); it('without .stories.mdx in globs', async () => { const packageJson = { dependencies: { '@storybook/react': '^7.0.0' }, }; const main = { stories: [ '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)', { directory: '../**', files: '*.stories.@(js|jsx|mjs|ts|tsx)' }, { directory: '../**' }, ], }; await expect(checkBareMdxStoriesGlob({ packageJson, main })).resolves.toBeFalsy(); }); }); }); describe('should fix', () => { it.each([ { existingStoriesEntries: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'], expectedStoriesEntries: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'], }, { existingStoriesEntries: ['../src/**/*.stories.*'], expectedStoriesEntries: ['../src/**/*.@(mdx|stories.*)'], }, { existingStoriesEntries: ['../src/**/*.stories.@(mdx|js|jsx|ts|tsx)'], expectedStoriesEntries: ['../src/**/*.@(mdx|stories.@(js|jsx|ts|tsx))'], }, { existingStoriesEntries: ['../src/**/*.stories.@(js|jsx|mdx|ts|tsx)'], expectedStoriesEntries: ['../src/**/*.@(mdx|stories.@(js|jsx|ts|tsx))'], }, { existingStoriesEntries: ['../src/**/*.stories.@(js|jsx|ts|tsx|mdx)'], expectedStoriesEntries: ['../src/**/*.@(mdx|stories.@(js|jsx|ts|tsx))'], }, ])( 'strings: $existingStoriesEntries', async ({ existingStoriesEntries, expectedStoriesEntries }) => { const packageJson = { dependencies: { '@storybook/react': '^7.0.0' }, }; const main = { stories: existingStoriesEntries, }; await expect(checkBareMdxStoriesGlob({ packageJson, main })).resolves.toMatchObject({ existingStoriesEntries, nextStoriesEntries: expectedStoriesEntries, }); } ); it.each([ { existingStoriesEntries: [{ directory: '../src/**', files: '*.stories.mdx' }], expectedStoriesEntries: [{ directory: '../src/**', files: '*.mdx' }], }, { existingStoriesEntries: [{ directory: '../src/**', files: '*.stories.*' }], expectedStoriesEntries: [{ directory: '../src/**', files: '*.@(mdx|stories.*)' }], }, { existingStoriesEntries: [ { directory: '../src/**', files: '*.stories.@(js|jsx|ts|tsx|mdx)' }, ], expectedStoriesEntries: [ { directory: '../src/**', files: '*.@(mdx|stories.@(js|jsx|ts|tsx))' }, ], }, ])( 'specifiers: $existingStoriesEntries.0.files', async ({ existingStoriesEntries, expectedStoriesEntries }) => { const packageJson = { dependencies: { '@storybook/react': '^7.0.0' }, }; const main = { stories: existingStoriesEntries, }; await expect(checkBareMdxStoriesGlob({ packageJson, main })).resolves.toMatchObject({ existingStoriesEntries, nextStoriesEntries: expectedStoriesEntries, }); } ); it('prompts', () => { const result = bareMdxStoriesGlob.prompt({ existingStoriesEntries: [ '../src/**/*.stories.@(js|jsx|mdx|ts|tsx)', { directory: '../src/**', files: '*.stories.mdx' }, ], nextStoriesEntries: [ '../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)', { directory: '../src/**', files: '*.mdx' }, ], } as BareMdxStoriesGlobRunOptions); expect(result.replaceAll(ansiRegex(), '')).toMatchInlineSnapshot(` "We've detected your project has one or more globs in your 'stories' config that matches .stories.mdx files: \\"../src/**/*.stories.@(js|jsx|mdx|ts|tsx)\\" { \\"directory\\": \\"../src/**\\", \\"files\\": \\"*.stories.mdx\\" } In Storybook 7, we have deprecated defining stories in MDX files, and consequently have changed the suffix to simply .mdx. We can automatically migrate your 'stories' config to include any .mdx file instead of just .stories.mdx. That would result in the following 'stories' config: \\"../src/**/*.mdx\\" \\"../src/**/*.stories.@(js|jsx|ts|tsx)\\" { \\"directory\\": \\"../src/**\\", \\"files\\": \\"*.mdx\\" } To learn more about this change, see: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mdx-docs-files" `); }); }); });
522
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/builder-vite.test.ts
import type { StorybookConfig } from '@storybook/types'; import { makePackageManager } from '../helpers/testing-helpers'; import type { PackageJson } from '../../js-package-manager'; import { builderVite } from './builder-vite'; const checkBuilderVite = async ({ packageJson = {}, main: mainConfig, }: { packageJson?: PackageJson; main: Partial<StorybookConfig> & Record<string, unknown>; }) => { return builderVite.check({ mainConfig: mainConfig as StorybookConfig, packageManager: makePackageManager(packageJson), storybookVersion: '7.0.0', }); }; describe('builder-vite fix', () => { afterEach(jest.restoreAllMocks); describe('storybook-builder-vite', () => { it('using storybook-builder-vite', async () => { const main = { core: { builder: 'storybook-builder-vite' } }; await expect(checkBuilderVite({ main })).resolves.toMatchObject({ builder: 'storybook-builder-vite', }); }); it('using storybook-builder-vite with options', async () => { const main = { core: { builder: { name: 'storybook-builder-vite', options: {} } } }; await expect(checkBuilderVite({ main })).resolves.toMatchObject({ builder: { name: 'storybook-builder-vite', options: {}, }, }); }); }); describe('other builders', () => { it('using @storybook/builder-vite', async () => { const main = { core: { builder: { name: '@storybook/builder-vite', options: {} } } }; await expect(checkBuilderVite({ main })).resolves.toBeFalsy(); }); it('using webpack5', async () => { const main = { core: { builder: 'webpack5' } }; await expect(checkBuilderVite({ main })).resolves.toBeFalsy(); }); it('no builder specified', async () => { const main = {}; await expect(checkBuilderVite({ main })).resolves.toBeFalsy(); }); }); });
524
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/cra5.test.ts
import type { StorybookConfig } from '@storybook/types'; import type { JsPackageManager } from '../../js-package-manager'; import { cra5 } from './cra5'; const checkCra5 = async ({ packageManager, main: mainConfig, storybookVersion = '7.0.0', }: { packageManager: any; main?: Partial<StorybookConfig> & Record<string, unknown>; storybookVersion?: string; }) => { return cra5.check({ packageManager, mainConfig: mainConfig as StorybookConfig, storybookVersion, }); }; describe('cra5 fix', () => { afterEach(jest.restoreAllMocks); describe('sb < 6.3', () => { describe('cra5 dependency', () => { const packageManager = { getPackageVersion: jest.fn().mockResolvedValue('5.0.0'), } as Partial<JsPackageManager>; it('should fail', async () => { await expect( checkCra5({ packageManager, storybookVersion: '6.2.0', }) ).rejects.toThrow(); }); }); describe('no cra5 dependency', () => { const packageManager = { getPackageVersion: jest.fn().mockResolvedValue(null), } as Partial<JsPackageManager>; it('should no-op', async () => { await expect( checkCra5({ packageManager, main: {}, }) ).resolves.toBeFalsy(); }); }); }); describe('sb 6.3 - 7.0', () => { describe('cra5 dependency', () => { const packageManager = { getPackageVersion: () => { return Promise.resolve('5.0.0'); }, } as Partial<JsPackageManager>; describe('webpack5 builder', () => { it('should no-op', async () => { await expect( checkCra5({ packageManager, main: { core: { builder: 'webpack5' } }, }) ).resolves.toBeFalsy(); }); }); describe('custom builder', () => { it('should no-op', async () => { await expect( checkCra5({ packageManager, main: { core: { builder: 'storybook-builder-vite' } }, }) ).resolves.toBeFalsy(); }); }); describe('webpack4 builder', () => { it('should add webpack5 builder', async () => { await expect( checkCra5({ packageManager, main: { core: { builder: 'webpack4' } }, storybookVersion: '6.3.0', }) ).resolves.toMatchObject({ craVersion: '5.0.0', storybookVersion: '6.3.0', }); }); }); describe('no builder', () => { it('should add webpack5 builder', async () => { await expect( checkCra5({ packageManager, main: {}, storybookVersion: '6.3.0', }) ).resolves.toMatchObject({ craVersion: '5.0.0', storybookVersion: '6.3.0', }); }); }); }); describe('no cra dependency', () => { const packageManager = { getPackageVersion: () => { return null; }, } as Partial<JsPackageManager>; it('should no-op', async () => { await expect( checkCra5({ packageManager, main: {}, }) ).resolves.toBeFalsy(); }); }); describe('cra4 dependency', () => { const packageManager = { getPackageVersion: () => { return Promise.resolve('4.0.0'); }, } as Partial<JsPackageManager>; it('should no-op', async () => { await expect( checkCra5({ packageManager, main: {}, }) ).resolves.toBeFalsy(); }); }); }); describe('sb 7.0+', () => { describe('cra5 dependency', () => { const packageManager = { getPackageVersion: () => { return Promise.resolve('5.0.0'); }, } as Partial<JsPackageManager>; it('should no-op', async () => { await expect( checkCra5({ packageManager, main: {}, }) ).resolves.toBeFalsy(); }); }); }); });
526
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/eslint-plugin.test.ts
/* eslint-disable no-underscore-dangle */ import { dedent } from 'ts-dedent'; import type { PackageJson } from '../../js-package-manager'; import { eslintPlugin } from './eslint-plugin'; import { makePackageManager } from '../helpers/testing-helpers'; // eslint-disable-next-line global-require, jest/no-mocks-import jest.mock('fs-extra', () => require('../../../../../__mocks__/fs-extra')); const checkEslint = async ({ packageJson, hasEslint = true, eslintExtension = 'js', }: { packageJson: PackageJson; hasEslint?: boolean; eslintExtension?: string; }) => { // eslint-disable-next-line global-require require('fs-extra').__setMockFiles({ [`.eslintrc.${eslintExtension}`]: !hasEslint ? null : dedent(` module.exports = { extends: ['plugin:react/recommended', 'airbnb-typescript', 'plugin:prettier/recommended'], parser: '@typescript-eslint/parser', parserOptions: { ecmaFeatures: { jsx: true, }, ecmaVersion: 12, sourceType: 'module', project: 'tsconfig.eslint.json', }, plugins: ['react', '@typescript-eslint'], rules: { 'some/rule': 'warn', }, } `), }); return eslintPlugin.check({ packageManager: makePackageManager(packageJson), mainConfig: {} as any, storybookVersion: '7.0.0', }); }; describe('eslint-plugin fix', () => { describe('should skip migration when', () => { it('project does not have eslint installed', async () => { const packageJson = { dependencies: {} }; await expect( checkEslint({ packageJson, hasEslint: false, }) ).resolves.toBeFalsy(); }); it('project already contains eslint-plugin-storybook dependency', async () => { const packageJson = { dependencies: { 'eslint-plugin-storybook': '^0.0.0' } }; await expect( checkEslint({ packageJson, }) ).resolves.toBeFalsy(); }); }); describe('when project does not contain eslint-plugin-storybook but has eslint installed', () => { const packageJson = { dependencies: { '@storybook/react': '^6.2.0', eslint: '^7.0.0' } }; describe('should no-op and warn when', () => { it('.eslintrc is not found', async () => { const loggerSpy = jest.spyOn(console, 'warn').mockImplementationOnce(jest.fn); const result = await checkEslint({ packageJson, hasEslint: false, }); expect(loggerSpy).toHaveBeenCalledWith('Unable to find .eslintrc config file, skipping'); await expect(result).toBeFalsy(); }); }); describe('should install eslint plugin', () => { it('when .eslintrc is using a supported extension', async () => { await expect( checkEslint({ packageJson, }) ).resolves.toMatchObject({ unsupportedExtension: undefined, }); }); it('when .eslintrc is using unsupported extension', async () => { await expect( checkEslint({ packageJson, eslintExtension: 'yml', }) ).resolves.toMatchObject({ unsupportedExtension: 'yml' }); }); }); }); });
528
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/incompatible-addons.test.ts
/// <reference types="@types/jest" />; import type { StorybookConfig } from '@storybook/types'; import { incompatibleAddons } from './incompatible-addons'; import type { JsPackageManager } from '../../js-package-manager'; const check = async ({ packageManager, main: mainConfig = {}, storybookVersion = '7.0.0', }: { packageManager: Partial<JsPackageManager>; main?: Partial<StorybookConfig> & Record<string, unknown>; storybookVersion?: string; }) => { return incompatibleAddons.check({ packageManager: packageManager as any, configDir: '', mainConfig: mainConfig as any, storybookVersion, }); }; describe('incompatible-addons fix', () => { afterEach(jest.restoreAllMocks); it('should show incompatible addons registered in main.js', async () => { await expect( check({ packageManager: { getPackageVersion(packageName, basePath) { switch (packageName) { case '@storybook/addon-essentials': return Promise.resolve('7.0.0'); case '@storybook/addon-info': return Promise.resolve('5.3.21'); default: return Promise.resolve(null); } }, getAllDependencies: async () => ({}), }, main: { addons: ['@storybook/essentials', '@storybook/addon-info'] }, }) ).resolves.toEqual({ incompatibleAddonList: [ { name: '@storybook/addon-info', version: '5.3.21', }, ], }); }); it('should show incompatible addons from package.json', async () => { await expect( check({ packageManager: { getPackageVersion(packageName, basePath) { switch (packageName) { case '@storybook/addon-essentials': return Promise.resolve('7.0.0'); case '@storybook/addon-info': return Promise.resolve('5.3.21'); default: return Promise.resolve(null); } }, getAllDependencies: async () => ({ '@storybook/addon-essentials': '7.0.0', '@storybook/addon-info': '5.3.21', }), }, main: { addons: [] }, }) ).resolves.toEqual({ incompatibleAddonList: [ { name: '@storybook/addon-info', version: '5.3.21', }, ], }); }); it('no-op when there are no incompatible addons', async () => { await expect( check({ packageManager: { getPackageVersion(packageName, basePath) { switch (packageName) { case '@storybook/addon-essentials': return Promise.resolve('7.0.0'); default: return Promise.resolve(null); } }, getAllDependencies: async () => ({}), }, main: { addons: ['@storybook/essentials'] }, }) ).resolves.toBeNull(); }); });
531
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/mdx-1-to-2.test.ts
/// <reference types="@types/jest" />; import { dedent } from 'ts-dedent'; import { fixMdxStyleTags, fixMdxComments } from './mdx-1-to-2'; it('fixMdxStyleTags fixes badly-formatted style blocks', () => { expect( fixMdxStyleTags(dedent` <style>{\` .foo {} .bar {} \`}</style> `) ).toEqual(dedent` <style> {\` .foo {} .bar {} \`} </style> `); }); it('fixMdxStyleTags fixes multiple style blocks', () => { expect( fixMdxStyleTags(dedent` <style>{\` .foo {} \`}</style> <style>{\` .bar {} \`}</style> `) ).toMatchInlineSnapshot(` <style> {\` .foo {} \`} </style> <style> {\` .bar {} \`} </style> `); }); it('fixMdxComments fixes all comments', () => { expect( fixMdxComments(dedent` # Hello <!-- This is a comment --> and this is not <!-- This is another comment --> `) ).toMatchInlineSnapshot(` "# Hello {/* This is a comment */} and this is not {/* This is another comment */}" `); }); it('fixMdxComments keeps html comments in codeblocks', () => { expect( fixMdxComments(dedent` # Hello ~~~html <!-- This is a comment --> ~~~ ~~~html <!-- This is a comment --> ~~~ \`\`\`html <!-- This is a comment --> \`\`\` \`\`\`html <!-- This is a comment --> \`\`\` and this is not <!-- This is another comment --> `) ).toMatchInlineSnapshot(` "# Hello ~~~html <!-- This is a comment --> ~~~ ~~~html <!-- This is a comment --> ~~~ \`\`\`html <!-- This is a comment --> \`\`\` \`\`\`html <!-- This is a comment --> \`\`\` and this is not {/* This is another comment */}" `); });
533
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/mdx-gfm.test.ts
import type { StorybookConfig } from '@storybook/types'; import { mdxgfm } from './mdx-gfm'; jest.mock('globby', () => ({ __esModule: true, default: jest.fn().mockResolvedValue(['a/fake/file.mdx']), })); const check = async ({ packageManager, main: mainConfig, storybookVersion = '7.0.0', }: { packageManager: any; main: Partial<StorybookConfig> & Record<string, unknown>; storybookVersion?: string; }) => { return mdxgfm.check({ packageManager, configDir: '', mainConfig: mainConfig as any, storybookVersion, }); }; describe('no-ops', () => { test('sb > 7.0', async () => { await expect( check({ packageManager: {}, main: {}, storybookVersion: '6.2.0', }) ).resolves.toBeFalsy(); }); test('legacyMdx1', async () => { await expect( check({ packageManager: {}, main: { features: { legacyMdx1: true, }, }, }) ).resolves.toBeFalsy(); }); test('with addon docs setup', async () => { await expect( check({ packageManager: {}, main: { addons: [ { name: '@storybook/addon-essentials', options: { docs: false, }, }, { name: '@storybook/addon-docs', options: { mdxPluginOptions: { mdxCompileOptions: { remarkPlugins: [() => {}], }, }, }, }, ], }, }) ).resolves.toBeFalsy(); }); test('with addon migration assistant addon added', async () => { await expect( check({ packageManager: {}, main: { addons: ['@storybook/addon-mdx-gfm'], }, }) ).resolves.toBeFalsy(); }); }); describe('continue', () => { test('nothing configured at all', async () => { await expect( check({ packageManager: {}, main: { stories: ['**/*.stories.mdx'], }, }) ).resolves.toBeTruthy(); }); test('unconfigured addon-docs', async () => { await expect( check({ packageManager: {}, main: { stories: ['**/*.stories.mdx'], addons: [ { name: '@storybook/addon-essentials', options: { docs: false, }, }, { name: '@storybook/addon-docs', options: {}, }, ], }, }) ).resolves.toBeTruthy(); }); test('unconfigured addon-essentials', async () => { await expect( check({ packageManager: {}, main: { stories: ['**/*.stories.mdx'], addons: ['@storybook/addon-essentials'], }, }) ).resolves.toBeTruthy(); }); test('stories object with directory + files', async () => { await expect( check({ packageManager: {}, main: { stories: [{ directory: 'src', titlePrefix: 'src', files: '' }], addons: ['@storybook/addon-essentials'], }, }) ).resolves.toBeTruthy(); }); test('stories object with directory and no files', async () => { await expect( check({ packageManager: {}, main: { stories: [{ directory: 'src', titlePrefix: 'src' }], addons: ['@storybook/addon-essentials'], }, }) ).resolves.toBeTruthy(); }); });
535
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/missing-babelrc.test.ts
/* eslint-disable no-underscore-dangle */ /// <reference types="@types/jest" />; import type { StorybookConfig } from '@storybook/types'; import { missingBabelRc } from './missing-babelrc'; import type { JsPackageManager } from '../../js-package-manager'; // eslint-disable-next-line global-require, jest/no-mocks-import jest.mock('fs-extra', () => require('../../../../../__mocks__/fs-extra')); const babelContent = JSON.stringify({ sourceType: 'unambiguous', presets: [ [ '@babel/preset-env', { targets: { chrome: 100, safari: 15, firefox: 91 }, }, ], '@babel/preset-typescript', '@babel/preset-react', ], plugins: [], }); const check = async ({ packageManager = { retrievePackageJson: () => ({}), }, main: mainConfig = {}, storybookVersion = '7.0.0', extraFiles, }: { packageManager?: any; main?: Partial<StorybookConfig> & Record<string, unknown>; storybookVersion?: string; extraFiles?: Record<string, any>; }) => { if (extraFiles) { // eslint-disable-next-line global-require require('fs-extra').__setMockFiles(extraFiles); } return missingBabelRc.check({ packageManager, mainConfig: mainConfig as any, storybookVersion, }); }; const packageManager = { retrievePackageJson: () => Promise.resolve({ devDependencies: {}, dependencies: {}, }), } as Partial<JsPackageManager>; const packageManagerWithBabelField = { retrievePackageJson: () => Promise.resolve({ devDependencies: {}, dependencies: {}, babel: babelContent, }), } as Partial<JsPackageManager>; describe('missing-babelrc fix', () => { afterEach(jest.restoreAllMocks); it('skips when storybook version < 7.0.0', async () => { await expect(check({ storybookVersion: '6.3.2' })).resolves.toBeNull(); }); it('skips when babelrc config is present', async () => { // different babel extensions await expect( check({ packageManager, extraFiles: { '.babelrc': babelContent }, main: { framework: '@storybook/react' }, }) ).resolves.toBeNull(); await expect( check({ packageManager, extraFiles: { '.babelrc.json': babelContent }, main: { framework: '@storybook/react' }, }) ).resolves.toBeNull(); await expect( check({ packageManager, extraFiles: { 'babel.config.json': babelContent }, main: { framework: '@storybook/react' }, }) ).resolves.toBeNull(); await expect( check({ packageManager: packageManagerWithBabelField, main: { framework: '@storybook/react' }, }) ).resolves.toBeNull(); }); it('skips when using a framework that provides babel config', async () => { await expect( check({ main: { framework: '@storybook/nextjs' }, packageManager }) ).resolves.toBeNull(); }); it('skips when using CRA preset', async () => { await expect( check({ main: { framework: '@storybook/react', addons: ['@storybook/preset-create-react-app'] }, packageManager, }) ).resolves.toBeNull(); }); it('prompts when babelrc file is missing and framework does not provide babel config', async () => { await expect( check({ packageManager, main: { framework: '@storybook/react-webpack5' }, }) ).resolves.toEqual({ needsBabelRc: true, }); }); });
537
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/new-frameworks.test.ts
import type { StorybookConfig } from '@storybook/types'; import * as findUp from 'find-up'; import * as rendererHelpers from '../helpers/detectRenderer'; import { newFrameworks } from './new-frameworks'; import type { JsPackageManager } from '../../js-package-manager'; jest.mock('find-up'); jest.mock('../helpers/detectRenderer', () => ({ detectRenderer: jest.fn(jest.requireActual('../helpers/detectRenderer').detectRenderer), })); const checkNewFrameworks = async ({ packageManager = {}, main: mainConfig, storybookVersion = '7.0.0', rendererPackage, }: { packageManager?: any; main?: Partial<StorybookConfig> & Record<string, unknown>; storybookVersion?: string; rendererPackage?: string; }) => { return newFrameworks.check({ packageManager, mainConfig: mainConfig as any, storybookVersion, rendererPackage, configDir: '', }); }; const getPackageManager = (packages: Record<string, string>) => { return { getPackageVersion(packageName) { return new Promise((resolve) => { Object.entries(packages).forEach(([name, version]) => { if (packageName === name) { resolve(version); } }); resolve(null); }); }, retrievePackageJson: () => Promise.resolve({ dependencies: {}, devDependencies: packages, }), getAllDependencies: () => Promise.resolve(packages), } as Partial<JsPackageManager>; }; describe('new-frameworks fix', () => { describe('should no-op', () => { it('in sb < 7', async () => { const packageManager = getPackageManager({ '@storybook/vue': '6.2.0', }); await expect( checkNewFrameworks({ packageManager, storybookVersion: '6.2.0', }) ).resolves.toBeFalsy(); }); it('in sb 7 with correct structure already', async () => { const packageManager = getPackageManager({ '@storybook/angular': '7.0.0', }); await expect( checkNewFrameworks({ packageManager, main: { framework: '@storybook/angular', }, }) ).resolves.toBeFalsy(); }); }); describe('should throw an error', () => { it('in sb 7 with no main.js', async () => { await expect(() => checkNewFrameworks({ main: undefined, }) ).rejects.toBeTruthy(); }); it('in sb 7 with vite < 3', async () => { const packageManager = getPackageManager({ '@storybook/react': '7.0.0', '@storybook/builder-vite': 'x.y.z', vite: '2.0.0', }); await expect( checkNewFrameworks({ packageManager, rendererPackage: '@storybook/react', main: { framework: '@storybook/react', core: { builder: '@storybook/builder-vite', }, }, }) ).rejects.toBeTruthy(); }); }); describe('generic new-frameworks migration', () => { it('should update to @storybook/react-webpack5', async () => { const packageManager = getPackageManager({ '@storybook/react': '7.0.0-alpha.0', '@storybook/builder-webpack5': '6.5.9', '@storybook/manager-webpack5': '6.5.9', }); await expect( checkNewFrameworks({ packageManager, main: { framework: '@storybook/react', core: { builder: { name: 'webpack5', options: { lazyCompilation: true, }, }, }, reactOptions: { fastRefresh: true, }, }, }) ).resolves.toEqual( expect.objectContaining({ renderer: 'react', frameworkPackage: '@storybook/react-webpack5', dependenciesToAdd: ['@storybook/react-webpack5'], dependenciesToRemove: ['@storybook/builder-webpack5', '@storybook/manager-webpack5'], frameworkOptions: { fastRefresh: true, }, builderConfig: { name: 'webpack5', options: { lazyCompilation: true, }, }, }) ); }); it('should update to @storybook/react-vite', async () => { const packageManager = getPackageManager({ '@storybook/react': '7.0.0-alpha.0', '@storybook/builder-vite': '0.0.2', vite: '3.0.0', }); await expect( checkNewFrameworks({ packageManager, main: { framework: '@storybook/react', core: { builder: '@storybook/builder-vite', }, }, }) ).resolves.toEqual( expect.objectContaining({ frameworkPackage: '@storybook/react-vite', dependenciesToAdd: ['@storybook/react-vite'], dependenciesToRemove: ['@storybook/builder-vite'], }) ); }); it('should update only builders in @storybook/angular', async () => { const packageManager = getPackageManager({ '@storybook/angular': '7.0.0-alpha.0', '@storybook/builder-webpack5': '6.5.9', '@storybook/manager-webpack5': '6.5.9', }); await expect( checkNewFrameworks({ packageManager, main: { framework: '@storybook/angular', core: { builder: { name: 'webpack5', options: { lazyCompilation: true, }, }, }, angularOptions: { enableIvy: true, enableNgcc: true, }, }, }) ).resolves.toEqual( expect.objectContaining({ frameworkPackage: '@storybook/angular', dependenciesToAdd: [], dependenciesToRemove: ['@storybook/builder-webpack5', '@storybook/manager-webpack5'], frameworkOptions: { enableIvy: true, enableNgcc: true, }, builderConfig: { name: 'webpack5', options: { lazyCompilation: true, }, }, }) ); }); it('should update to @storybook/preact-vite', async () => { const packageManager = getPackageManager({ '@storybook/preact': '7.0.0-alpha.0', '@storybook/builder-vite': '0.0.2', vite: '3.0.0', }); await expect( checkNewFrameworks({ packageManager, main: { framework: '@storybook/preact', core: { builder: '@storybook/builder-vite', }, }, }) ).resolves.toEqual( expect.objectContaining({ frameworkPackage: '@storybook/preact-vite', dependenciesToAdd: ['@storybook/preact-vite'], dependenciesToRemove: ['@storybook/builder-vite'], }) ); }); it('should update correctly when there is no builder', async () => { const packageManager = getPackageManager({ '@storybook/vue': '7.0.0', '@storybook/builder-webpack5': '7.0.0', }); await expect( checkNewFrameworks({ packageManager, main: { framework: '@storybook/vue', }, }) ).resolves.toEqual( expect.objectContaining({ frameworkPackage: '@storybook/vue-webpack5', dependenciesToAdd: ['@storybook/vue-webpack5'], dependenciesToRemove: ['@storybook/builder-webpack5'], }) ); }); it('should update when there is no framework field in main', async () => { const packageManager = getPackageManager({ '@storybook/vue': '7.0.0', '@storybook/manager-webpack5': '7.0.0', }); await expect( checkNewFrameworks({ packageManager, main: {}, }) ).resolves.toEqual( expect.objectContaining({ frameworkPackage: '@storybook/vue-webpack5', dependenciesToAdd: ['@storybook/vue-webpack5'], dependenciesToRemove: ['@storybook/manager-webpack5'], hasFrameworkInMainConfig: false, }) ); }); it('should update when the framework field has a legacy value', async () => { const packageManager = getPackageManager({ '@storybook/vue': '7.0.0', '@storybook/manager-webpack5': '7.0.0', }); await expect( checkNewFrameworks({ packageManager, main: { framework: 'vue', }, }) ).resolves.toEqual( expect.objectContaining({ frameworkPackage: '@storybook/vue-webpack5', dependenciesToAdd: ['@storybook/vue-webpack5'], dependenciesToRemove: ['@storybook/manager-webpack5'], hasFrameworkInMainConfig: false, }) ); }); it('should prompt when there are multiple renderer packages', async () => { // there should be a prompt, which we mock the response const detectRendererSpy = jest.spyOn(rendererHelpers, 'detectRenderer'); detectRendererSpy.mockReturnValueOnce(Promise.resolve('@storybook/react')); const packageManager = getPackageManager({ '@storybook/react': '7.0.0', '@storybook/vue': '7.0.0', '@storybook/builder-vite': 'x.y.z', }); await expect( checkNewFrameworks({ packageManager, main: { core: { builder: '@storybook/builder-vite', }, }, }) ).resolves.toEqual( expect.objectContaining({ frameworkPackage: '@storybook/react-vite', dependenciesToRemove: ['@storybook/builder-vite'], }) ); expect(detectRendererSpy).toHaveBeenCalled(); }); it('should add framework field in main.js when everything is properly configured, but framework field in main.js is missing', async () => { const packageManager = getPackageManager({ '@storybook/react': '7.0.0-alpha.0', '@storybook/react-vite': '7.0.0-alpha.0', }); // project contains vite.config.js jest.spyOn(findUp, 'default').mockReturnValueOnce(Promise.resolve('vite.config.js')); await expect( checkNewFrameworks({ packageManager, main: {}, }) ).resolves.toEqual( expect.objectContaining({ hasFrameworkInMainConfig: false, frameworkPackage: '@storybook/react-vite', }) ); }); it('should migrate to @storybook/web-components-webpack5 in a monorepo that contains the vite builder, but main.js has webpack5 in builder field', async () => { jest .spyOn(rendererHelpers, 'detectRenderer') .mockReturnValueOnce(Promise.resolve('@storybook/web-components')); const packageManager = getPackageManager({ '@storybook/addon-essentials': '7.0.0-beta.48', '@storybook/vue': '7.0.0-beta.48', '@storybook/builder-vite': '7.0.0-beta.48', '@storybook/builder-webpack5': '7.0.0-beta.48', '@storybook/core-server': '7.0.0-beta.48', '@storybook/manager-webpack5': '6.5.15', '@storybook/react': '7.0.0-beta.48', '@storybook/web-components': '7.0.0-beta.48', }); await expect( checkNewFrameworks({ packageManager, main: { core: { builder: 'webpack5' }, }, }) ).resolves.toEqual( expect.objectContaining({ hasFrameworkInMainConfig: false, frameworkPackage: '@storybook/web-components-webpack5', }) ); }); }); describe('nextjs migration', () => { it('skips in non-Next.js projects', async () => { const packageManager = getPackageManager({ '@storybook/react': '7.0.0', '@storybook/react-vite': '7.0.0', }); const main = { framework: '@storybook/react-vite', }; await expect(checkNewFrameworks({ packageManager, main })).resolves.toBeFalsy(); }); it('skips if project uses Next.js < 12.0.0', async () => { const packageManager = getPackageManager({ '@storybook/react': '7.0.0', '@storybook/react-webpack5': '7.0.0', next: '11.0.0', }); const main = { framework: '@storybook/react', }; await expect(checkNewFrameworks({ packageManager, main })).resolves.toBeFalsy(); }); it('skips if project already has @storybook/nextjs set up', async () => { jest.spyOn(findUp, 'default').mockReturnValueOnce(Promise.resolve('next.config.js')); const packageManager = getPackageManager({ '@storybook/react': '7.0.0', '@storybook/nextjs': '7.0.0', next: '12.0.0', }); const main = { framework: '@storybook/nextjs', }; await expect(checkNewFrameworks({ packageManager, main })).resolves.toBeFalsy(); }); it('should update from @storybook/react-webpack5 to @storybook/nextjs', async () => { const packageManager = getPackageManager({ '@storybook/react': '7.0.0-alpha.0', '@storybook/react-webpack5': '7.0.0-alpha.0', '@storybook/builder-webpack5': '7.0.0-alpha.0', next: '12.0.0', }); jest.spyOn(findUp, 'default').mockReturnValueOnce(Promise.resolve('next.config.js')); await expect( checkNewFrameworks({ packageManager, main: { framework: { name: '@storybook/react-webpack5', options: {} }, }, }) ).resolves.toEqual( expect.objectContaining({ frameworkPackage: '@storybook/nextjs', dependenciesToAdd: ['@storybook/nextjs'], dependenciesToRemove: ['@storybook/builder-webpack5', '@storybook/react-webpack5'], }) ); }); it('should remove legacy addons', async () => { jest.spyOn(findUp, 'default').mockReturnValueOnce(Promise.resolve('next.config.js')); const packageManager = getPackageManager({ '@storybook/react': '7.0.0-alpha.0', '@storybook/react-webpack5': '7.0.0-alpha.0', next: '12.0.0', 'storybook-addon-next': '1.0.0', 'storybook-addon-next-router': '1.0.0', }); await expect( checkNewFrameworks({ packageManager, main: { framework: '@storybook/react-webpack5', addons: ['storybook-addon-next', 'storybook-addon-next-router'], }, }) ).resolves.toEqual( expect.objectContaining({ addonsToRemove: ['storybook-addon-next', 'storybook-addon-next-router'], dependenciesToRemove: [ '@storybook/react-webpack5', 'storybook-addon-next', 'storybook-addon-next-router', ], }) ); }); it('should move storybook-addon-next options and reactOptions to frameworkOptions', async () => { jest.spyOn(findUp, 'default').mockReturnValueOnce(Promise.resolve('next.config.js')); const packageManager = getPackageManager({ '@storybook/react': '7.0.0-alpha.0', '@storybook/react-webpack5': '7.0.0-alpha.0', next: '12.0.0', 'storybook-addon-next': '1.0.0', }); await expect( checkNewFrameworks({ packageManager, main: { framework: { name: '@storybook/react-webpack5', options: { fastRefresh: true } }, addons: [ { name: 'storybook-addon-next', options: { nextConfigPath: '../next.config.js', }, }, ], core: { builder: { name: '@storybook/builder-webpack5', options: { lazyCompilation: true }, }, }, }, }) ).resolves.toEqual( expect.objectContaining({ frameworkPackage: '@storybook/nextjs', dependenciesToAdd: ['@storybook/nextjs'], dependenciesToRemove: ['@storybook/react-webpack5', 'storybook-addon-next'], addonsToRemove: ['storybook-addon-next'], frameworkOptions: { fastRefresh: true, nextConfigPath: '../next.config.js', }, builderInfo: { name: 'webpack5', options: { lazyCompilation: true }, }, }) ); }); it('should migrate to @storybook/react-vite in Next.js project that uses vite builder', async () => { jest.spyOn(findUp, 'default').mockReturnValueOnce(Promise.resolve('next.config.js')); const packageManager = getPackageManager({ '@storybook/react': '7.0.0-alpha.0', '@storybook/builder-vite': '7.0.0-alpha.0', next: '12.0.0', 'storybook-addon-next': '1.0.0', }); await expect( checkNewFrameworks({ packageManager, main: { core: { builder: '@storybook/builder-vite', }, }, }) ).resolves.toEqual( expect.objectContaining({ addonsToRemove: [], dependenciesToAdd: ['@storybook/react-vite'], dependenciesToRemove: ['@storybook/builder-vite'], frameworkPackage: '@storybook/react-vite', }) ); }); }); describe('SvelteKit migration', () => { it('skips in non-SvelteKit projects', async () => { const packageManager = getPackageManager({ svelte: '3.53.1', '@storybook/svelte': '7.0.0', '@storybook/svelte-vite': '7.0.0', }); const main = { framework: '@storybook/svelte-vite', }; await expect(checkNewFrameworks({ packageManager, main })).resolves.toBeFalsy(); }); it('skips if project uses SvelteKit < 1.0.0', async () => { const packageManager = getPackageManager({ '@storybook/svelte': '7.0.0', '@storybook/svelte-vite': '7.0.0', '@sveltejs/kit': '0.9.0', }); const main = { framework: '@storybook/svelte-vite', }; await expect(checkNewFrameworks({ packageManager, main })).resolves.toBeFalsy(); }); it('skips if project already has @storybook/sveltekit set up', async () => { const packageManager = getPackageManager({ '@storybook/svelte': '7.0.0', '@storybook/sveltekit': '7.0.0', '@sveltejs/kit': '1.0.0', }); const main = { framework: '@storybook/svelte-vite', }; await expect(checkNewFrameworks({ packageManager, main })).resolves.toBeFalsy(); }); it('from @storybook/svelte-vite', async () => { const packageManager = getPackageManager({ '@storybook/svelte': '7.0.0', '@storybook/svelte-vite': '7.0.0', '@sveltejs/kit': '1.0.0', }); const main = { framework: '@storybook/svelte-vite', }; await expect(checkNewFrameworks({ packageManager, main })).resolves.toEqual( expect.objectContaining({ dependenciesToAdd: ['@storybook/sveltekit'], dependenciesToRemove: ['@storybook/svelte-vite'], frameworkPackage: '@storybook/sveltekit', }) ); }); it('from @storybook/svelte framework and @storybook/builder-vite builder', async () => { const packageManager = getPackageManager({ '@storybook/svelte': '7.0.0', '@storybook/builder-vite': '7.0.0', '@sveltejs/kit': '1.0.0', }); const main = { framework: '@storybook/svelte', core: { builder: '@storybook/builder-vite' }, }; await expect(checkNewFrameworks({ packageManager, main })).resolves.toEqual( expect.objectContaining({ dependenciesToAdd: ['@storybook/sveltekit'], dependenciesToRemove: ['@storybook/builder-vite'], frameworkPackage: '@storybook/sveltekit', }) ); }); it('from @storybook/svelte framework and storybook-builder-vite builder', async () => { const packageManager = getPackageManager({ '@storybook/svelte': '7.0.0', 'storybook-builder-vite': '0.2.5', '@sveltejs/kit': '1.0.0', }); const main = { framework: '@storybook/svelte', core: { builder: 'storybook-builder-vite' }, }; await expect(checkNewFrameworks({ packageManager, main })).resolves.toEqual( expect.objectContaining({ dependenciesToAdd: ['@storybook/sveltekit'], dependenciesToRemove: ['storybook-builder-vite'], frameworkPackage: '@storybook/sveltekit', }) ); }); it('should migrate and remove svelteOptions', async () => { const packageManager = getPackageManager({ '@storybook/svelte': '7.0.0', 'storybook-builder-vite': '0.2.5', '@sveltejs/kit': '1.0.0', }); const main = { framework: '@storybook/svelte', core: { builder: 'storybook-builder-vite' }, svelteOptions: { preprocess: 'preprocess' }, }; await expect(checkNewFrameworks({ packageManager, main })).resolves.toEqual( expect.objectContaining({ dependenciesToAdd: ['@storybook/sveltekit'], dependenciesToRemove: ['storybook-builder-vite'], frameworkPackage: '@storybook/sveltekit', rendererOptions: {}, }) ); }); it('should migrate to @storybook/svelte-webpack5 in SvelteKit project that uses Webpack5 builder', async () => { const packageManager = getPackageManager({ '@storybook/svelte': '7.0.0-alpha.0', '@storybook/builder-webpack5': '7.0.0-alpha.0', '@sveltejs/kit': '1.0.0', }); await expect( checkNewFrameworks({ packageManager, main: { core: { builder: '@storybook/builder-webpack5', }, }, }) ).resolves.toEqual( expect.objectContaining({ addonsToRemove: [], dependenciesToAdd: ['@storybook/svelte-webpack5'], dependenciesToRemove: ['@storybook/builder-webpack5'], frameworkPackage: '@storybook/svelte-webpack5', }) ); }); }); });
539
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/nodejs-requirement.test.ts
/// <reference types="@types/jest" />; import { nodeJsRequirement } from './nodejs-requirement'; // eslint-disable-next-line global-require, jest/no-mocks-import jest.mock('fs-extra', () => require('../../../../../__mocks__/fs-extra')); const check = async ({ storybookVersion = '7.0.0' }) => { return nodeJsRequirement.check({ storybookVersion, packageManager: {} as any, mainConfig: {} as any, }); }; const originalNodeVersion = process.version; const mockNodeVersion = (version: string) => { Object.defineProperties(process, { version: { value: version, }, }); }; describe('nodejs-requirement fix', () => { afterAll(() => { mockNodeVersion(originalNodeVersion); jest.restoreAllMocks(); }); it('skips when sb <= 7.0.0', async () => { mockNodeVersion('14.0.0'); await expect(check({ storybookVersion: '6.3.2' })).resolves.toBeNull(); }); it('skips when node >= 16.0.0', async () => { mockNodeVersion('16.0.0'); await expect(check({})).resolves.toBeNull(); }); it('skips when node >= 18.0.0', async () => { mockNodeVersion('18.0.0'); await expect(check({})).resolves.toBeNull(); }); it('prompts when node <= 16.0.0', async () => { mockNodeVersion('14.0.0'); await expect(check({})).resolves.toEqual({ nodeVersion: '14.0.0' }); }); });
541
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/remove-global-client-apis.test.ts
/// <reference types="@types/jest" />; /* eslint-disable no-underscore-dangle */ import path from 'path'; import type { JsPackageManager } from '../../js-package-manager'; import { RemovedAPIs, removedGlobalClientAPIs as migration } from './remove-global-client-apis'; // eslint-disable-next-line global-require, jest/no-mocks-import jest.mock('fs-extra', () => require('../../../../../__mocks__/fs-extra')); const check = async ({ contents, previewConfigPath }: any) => { if (contents) { // eslint-disable-next-line global-require require('fs-extra').__setMockFiles({ [path.join('.storybook', 'preview.js')]: contents, }); } const packageManager = { retrievePackageJson: async () => ({ dependencies: {}, devDependencies: {} }), } as JsPackageManager; return migration.check({ packageManager, mainConfig: {} as any, storybookVersion: '7.0.0', previewConfigPath, }); }; describe('removedGlobalClientAPIs fix', () => { it('file does not exist', async () => { const contents = false; await expect(check({ contents })).resolves.toBeNull(); }); it('uses no removed APIs', async () => { const contents = ` export const parameters = {}; `; await expect( check({ contents, previewConfigPath: path.join('.storybook', 'preview.js') }) ).resolves.toBeNull(); }); it('uses 1 removed API', async () => { const contents = ` import { addParameters } from '@storybook/react'; addParameters({}); `; await expect( check({ contents, previewConfigPath: path.join('.storybook', 'preview.js') }) ).resolves.toEqual( expect.objectContaining({ usedAPIs: [RemovedAPIs.addParameters], }) ); }); it('uses >1 removed APIs', async () => { const contents = ` import { addParameters, addDecorator } from '@storybook/react'; addParameters({}); addDecorator((storyFn) => storyFn()); `; await expect( check({ contents, previewConfigPath: path.join('.storybook', 'preview.js') }) ).resolves.toEqual( expect.objectContaining({ usedAPIs: expect.arrayContaining([RemovedAPIs.addParameters, RemovedAPIs.addDecorator]), }) ); }); });
543
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/sb-binary.test.ts
import type { JsPackageManager } from '../../js-package-manager'; import { sbBinary } from './sb-binary'; const checkStorybookBinary = async ({ packageManager, storybookVersion = '7.0.0', }: { packageManager: Partial<JsPackageManager>; storybookVersion?: string; }) => { return sbBinary.check({ packageManager: packageManager as any, storybookVersion, mainConfig: {} as any, }); }; describe('storybook-binary fix', () => { describe('sb < 7.0', () => { describe('does nothing', () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/react': return Promise.resolve('6.2.0'); default: return null; } }, retrievePackageJson: () => Promise.resolve({}), } as Partial<JsPackageManager>; it('should no-op', async () => { await expect( checkStorybookBinary({ packageManager, storybookVersion: '6.2.0', }) ).resolves.toBeFalsy(); }); }); }); describe('sb >= 7.0', () => { it('should no-op in NX projects', async () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/react': return Promise.resolve('7.0.0'); case '@nrwl/storybook': return Promise.resolve('15.7.1'); default: return null; } }, retrievePackageJson: () => Promise.resolve({}), } as Partial<JsPackageManager>; await expect( checkStorybookBinary({ packageManager, }) ).resolves.toBeFalsy(); }); it('should add storybook dependency if not present', async () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/react': return Promise.resolve('7.0.0-alpha.0'); default: return null; } }, retrievePackageJson: () => Promise.resolve({}), } as Partial<JsPackageManager>; await expect( checkStorybookBinary({ packageManager, }) ).resolves.toEqual( expect.objectContaining({ hasSbBinary: false, hasStorybookBinary: false, }) ); }); it('should remove sb dependency if it is present', async () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/react': return Promise.resolve('7.0.0-alpha.0'); case 'sb': return Promise.resolve('6.5.0'); default: return null; } }, retrievePackageJson: () => Promise.resolve({}), } as Partial<JsPackageManager>; await expect( checkStorybookBinary({ packageManager, }) ).resolves.toEqual( expect.objectContaining({ hasSbBinary: true, hasStorybookBinary: false, }) ); }); it('should no op if storybook is present and sb is not present', async () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/react': return Promise.resolve('7.0.0-alpha.0'); case 'storybook': return Promise.resolve('7.0.0-alpha.0'); default: return null; } }, retrievePackageJson: () => Promise.resolve({}), } as Partial<JsPackageManager>; await expect( checkStorybookBinary({ packageManager, }) ).resolves.toBeNull(); }); }); });
545
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/sb-scripts.test.ts
import type { JsPackageManager } from '../../js-package-manager'; import { getStorybookScripts, sbScripts } from './sb-scripts'; const checkSbScripts = async ({ packageManager, storybookVersion = '7.0.0', }: { packageManager: Partial<JsPackageManager>; storybookVersion?: string; }) => { return sbScripts.check({ packageManager: packageManager as any, storybookVersion, mainConfig: {} as any, }); }; describe('getStorybookScripts', () => { afterEach(jest.restoreAllMocks); it('detects default storybook scripts', () => { expect( getStorybookScripts({ 'sb:upgrade': 'sb upgrade', storybook: 'start-storybook', 'build-storybook': 'build-storybook', }) ).toEqual({ 'build-storybook': { before: 'build-storybook', after: 'storybook build', }, storybook: { before: 'start-storybook', after: 'storybook dev', }, 'sb:upgrade': { before: 'sb upgrade', after: 'storybook upgrade', }, }); }); it('skips non-storybook scripts', () => { expect( getStorybookScripts({ start: 'server start', 'start-storybook': 'MOCKS=true start-storybook -p 9000', 'storybook:start-ci': 'CI=true yarn start-storybook', 'storybook:build-ci': 'CI=true yarn build-storybook', }) ).toEqual({ 'start-storybook': { before: 'MOCKS=true start-storybook -p 9000', after: 'MOCKS=true storybook dev -p 9000', }, }); }); }); describe('sb-scripts fix', () => { describe('sb < 7.0', () => { describe('does nothing', () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/react': return Promise.resolve('6.2.0'); default: return null; } }, retrievePackageJson: () => Promise.resolve({}), } as Partial<JsPackageManager>; it('should no-op', async () => { await expect( checkSbScripts({ packageManager, storybookVersion: '6.2.0', }) ).resolves.toBeFalsy(); }); }); }); describe('sb >= 7.0', () => { describe('with old scripts', () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/react': return Promise.resolve('7.0.0-alpha.0'); default: return null; } }, retrievePackageJson: () => Promise.resolve({ scripts: { storybook: 'start-storybook -p 6006', 'build-storybook': 'build-storybook -o build/storybook', }, dependencies: {}, devDependencies: {}, }), } as Partial<JsPackageManager>; it('should update scripts to new format', async () => { await expect( checkSbScripts({ packageManager, }) ).resolves.toEqual( expect.objectContaining({ storybookScripts: { 'build-storybook': { after: 'storybook build -o build/storybook', before: 'build-storybook -o build/storybook', }, storybook: { after: 'storybook dev -p 6006', before: 'start-storybook -p 6006', }, }, }) ); }); }); describe('with old custom scripts', () => { it('should update scripts to new format', async () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/react': return Promise.resolve('7.0.0-alpha.0'); default: return null; } }, retrievePackageJson: () => Promise.resolve({ scripts: { 'storybook:ci': 'yarn start-storybook --ci', 'storybook:build': 'build-storybook -o build/storybook', 'storybook:build-mocked': 'MOCKS=true yarn storybook:build', 'test-storybook:ci': 'concurrently -k -s first -n "SB,TEST" -c "magenta,blue" "CI=true build-storybook --quiet && npx http-server storybook-static --port 6006 --silent" "wait-on tcp:6006 && yarn test-storybook"', }, dependencies: {}, devDependencies: {}, }), } as Partial<JsPackageManager>; await expect( checkSbScripts({ packageManager, }) ).resolves.toEqual( expect.objectContaining({ storybookScripts: { 'storybook:build': { after: 'storybook build -o build/storybook', before: 'build-storybook -o build/storybook', }, 'test-storybook:ci': { before: 'concurrently -k -s first -n "SB,TEST" -c "magenta,blue" "CI=true build-storybook --quiet && npx http-server storybook-static --port 6006 --silent" "wait-on tcp:6006 && yarn test-storybook"', after: 'concurrently -k -s first -n "SB,TEST" -c "magenta,blue" "CI=true storybook build --quiet && npx http-server storybook-static --port 6006 --silent" "wait-on tcp:6006 && yarn test-storybook"', }, }, }) ); }); }); describe('already containing new scripts', () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/react': return Promise.resolve('7.0.0-alpha.0'); default: return null; } }, retrievePackageJson: () => Promise.resolve({ scripts: { storybook: 'storybook dev -p 6006', 'build-storybook': 'storybook build -o build/storybook', }, dependencies: {}, devDependencies: {}, }), } as Partial<JsPackageManager>; it('should no-op', async () => { await expect( checkSbScripts({ packageManager, }) ).resolves.toBeFalsy(); }); }); }); });
547
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/vue3.test.ts
import type { StorybookConfig } from '@storybook/types'; import type { JsPackageManager } from '../../js-package-manager'; import { vue3 } from './vue3'; const checkVue3 = async ({ main: mainConfig = {}, storybookVersion = '7.0.0', packageManager, }: { main?: Partial<StorybookConfig> & Record<string, unknown>; mainConfig?: Partial<StorybookConfig>; storybookVersion?: string; packageManager?: Partial<JsPackageManager>; }) => { return vue3.check({ packageManager: packageManager as any, storybookVersion, mainConfig: mainConfig as any, }); }; describe('vue3 fix', () => { afterEach(jest.restoreAllMocks); describe('sb < 6.3', () => { describe('vue3 dependency', () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/vue': return Promise.resolve('6.2.0'); case 'vue': return Promise.resolve('3.0.0'); default: return null; } }, } as Partial<JsPackageManager>; it('should fail', async () => { await expect( checkVue3({ packageManager, storybookVersion: '6.2.0', }) ).rejects.toThrow(); }); }); describe('no vue dependency', () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/vue': return Promise.resolve('6.2.0'); default: return null; } }, } as Partial<JsPackageManager>; it('should no-op', async () => { await expect( checkVue3({ packageManager, storybookVersion: '6.2.0', }) ).resolves.toBeFalsy(); }); }); }); describe('sb 6.3 - 7.0', () => { describe('vue3 dependency', () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/vue': return Promise.resolve('6.3.0'); case 'vue': return Promise.resolve('3.0.0'); default: return null; } }, } as Partial<JsPackageManager>; describe('webpack5 builder', () => { it('should no-op', async () => { await expect( checkVue3({ packageManager, main: { core: { builder: 'webpack5' } }, }) ).resolves.toBeFalsy(); }); }); describe('custom builder', () => { it('should no-op', async () => { await expect( checkVue3({ packageManager, main: { core: { builder: 'storybook-builder-vite' } }, }) ).resolves.toBeFalsy(); }); }); describe('webpack4 builder', () => { it('should add webpack5 builder', async () => { await expect( checkVue3({ packageManager, main: { core: { builder: 'webpack4' } }, storybookVersion: '6.3.0', }) ).resolves.toMatchObject({ vueVersion: '3.0.0', storybookVersion: '6.3.0', }); }); }); describe('no builder', () => { it('should add webpack5 builder', async () => { await expect( checkVue3({ packageManager, main: {}, storybookVersion: '6.3.0', }) ).resolves.toMatchObject({ vueVersion: '3.0.0', storybookVersion: '6.3.0', }); }); }); }); describe('no vue dependency', () => { it('should no-op', async () => { const packageManager = { getPackageVersion: (packageName) => { return null; }, } as Partial<JsPackageManager>; await expect( checkVue3({ packageManager, main: {}, }) ).resolves.toBeFalsy(); }); }); describe('vue2 dependency', () => { const packageManager = { getPackageVersion: (packageName) => { if (packageName === 'vue') { return Promise.resolve('2.0.0'); } return null; }, } as Partial<JsPackageManager>; it('should no-op', async () => { await expect( checkVue3({ packageManager, main: {}, }) ).resolves.toBeFalsy(); }); }); }); describe('sb 7.0+', () => { describe('vue3 dependency', () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/vue': return Promise.resolve('7.0.0-alpha.0'); case 'vue': return Promise.resolve('3.0.0'); default: return null; } }, } as Partial<JsPackageManager>; it('should no-op', async () => { await expect( checkVue3({ packageManager, main: {}, }) ).resolves.toBeFalsy(); }); }); }); });
549
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/webpack5.test.ts
import type { StorybookConfig } from '@storybook/types'; import type { JsPackageManager } from '../../js-package-manager'; import { webpack5 } from './webpack5'; const checkWebpack5 = async ({ packageManager, main: mainConfig, storybookVersion = '6.3.0', }: { packageManager: Partial<JsPackageManager>; main?: Partial<StorybookConfig> & Record<string, unknown>; storybookVersion?: string; mainConfig?: Partial<StorybookConfig>; }) => { return webpack5.check({ packageManager: packageManager as any, configDir: '', storybookVersion, mainConfig: mainConfig as any, }); }; describe('webpack5 fix', () => { afterEach(jest.restoreAllMocks); describe('sb < 6.3', () => { describe('webpack5 dependency', () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/react': return Promise.resolve('6.2.0'); case 'webpack': return Promise.resolve('5.0.0'); default: return null; } }, } as Partial<JsPackageManager>; it('should fail', async () => { await expect( checkWebpack5({ packageManager, storybookVersion: '6.2.0', }) ).rejects.toThrow(); }); }); describe('no webpack5 dependency', () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/react': return Promise.resolve('6.2.0'); default: return null; } }, } as Partial<JsPackageManager>; it('should no-op', async () => { await expect( checkWebpack5({ packageManager, storybookVersion: '6.2.0', }) ).resolves.toBeFalsy(); }); }); }); describe('sb 6.3 - 7.0', () => { describe('webpack5 dependency', () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/react': return Promise.resolve('6.3.0'); case 'webpack': return Promise.resolve('5.0.0'); default: return null; } }, } as Partial<JsPackageManager>; describe('webpack5 builder', () => { it('should no-op', async () => { await expect( checkWebpack5({ packageManager, main: { core: { builder: 'webpack5' } }, }) ).resolves.toBeFalsy(); }); }); describe('custom builder', () => { it('should no-op', async () => { await expect( checkWebpack5({ packageManager, main: { core: { builder: 'storybook-builder-vite' } }, }) ).resolves.toBeFalsy(); }); }); describe('webpack4 builder', () => { it('should add webpack5 builder', async () => { await expect( checkWebpack5({ packageManager, main: { core: { builder: 'webpack4' } }, }) ).resolves.toMatchObject({ webpackVersion: '5.0.0', storybookVersion: '6.3.0', }); }); }); describe('no builder', () => { it('should add webpack5 builder', async () => { await expect( checkWebpack5({ packageManager, main: {}, }) ).resolves.toMatchObject({ webpackVersion: '5.0.0', storybookVersion: '6.3.0', }); }); }); }); describe('no webpack dependency', () => { const packageManager = { getPackageVersion: () => { return null; }, } as Partial<JsPackageManager>; it('should no-op', async () => { await expect( checkWebpack5({ packageManager, }) ).resolves.toBeFalsy(); }); }); describe('webpack4 dependency', () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case 'webpack': return Promise.resolve('4.0.0'); default: return null; } }, } as Partial<JsPackageManager>; it('should no-op', async () => { await expect( checkWebpack5({ packageManager, }) ).resolves.toBeFalsy(); }); }); }); describe('sb 7.0+', () => { describe('webpack5 dependency', () => { const packageManager = { getPackageVersion: (packageName) => { switch (packageName) { case '@storybook/react': return Promise.resolve('7.0.0-alpha.0'); case 'webpack': return Promise.resolve('5.0.0'); default: return null; } }, } as Partial<JsPackageManager>; it('should no-op', async () => { await expect( checkWebpack5({ packageManager, main: {}, storybookVersion: '7.0.0', }) ).resolves.toBeFalsy(); }); }); }); });
552
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/wrap-require.test.ts
import { wrapRequire } from './wrap-require'; import * as detect from '../../detect'; jest.mock('../../detect', () => ({ ...jest.requireActual('../../detect'), detectPnp: jest.fn(), })); describe('wrapRequire', () => { describe('check', () => { it('should return null if not in a monorepo and pnp is not enabled', async () => { (detect.detectPnp as any as jest.SpyInstance).mockResolvedValue(false); const check = wrapRequire.check({ packageManager: { isStorybookInMonorepo: () => false, }, storybookVersion: '7.0.0', mainConfigPath: require.resolve('./__test__/main-config-without-wrappers.js'), } as any); await expect(check).resolves.toBeNull(); }); it('should return the configuration object if in a pnp environment', async () => { (detect.detectPnp as any as jest.SpyInstance).mockResolvedValue(true); const check = wrapRequire.check({ packageManager: { isStorybookInMonorepo: () => false, }, storybookVersion: '7.0.0', mainConfigPath: require.resolve('./__test__/main-config-without-wrappers.js'), } as any); await expect(check).resolves.toEqual({ isConfigTypescript: false, isPnp: true, isStorybookInMonorepo: false, storybookVersion: '7.0.0', }); }); it('should return the configuration object if in a monorepo environment', async () => { (detect.detectPnp as any as jest.SpyInstance).mockResolvedValue(false); const check = wrapRequire.check({ packageManager: { isStorybookInMonorepo: () => true, }, storybookVersion: '7.0.0', mainConfigPath: require.resolve('./__test__/main-config-without-wrappers.js'), } as any); await expect(check).resolves.toEqual({ isConfigTypescript: false, isPnp: false, isStorybookInMonorepo: true, storybookVersion: '7.0.0', }); }); it('should return null, if all fields have the require wrapper', async () => { (detect.detectPnp as any as jest.SpyInstance).mockResolvedValue(true); const check = wrapRequire.check({ packageManager: { isStorybookInMonorepo: () => true, }, storybookVersion: '7.0.0', mainConfigPath: require.resolve('./__test__/main-config-with-wrappers.js'), } as any); await expect(check).resolves.toBeNull(); }); }); });
554
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/fixes/__snapshots__/angular-builders.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`is not Nx project angular builders Angular < 14.0.0 should throw an Error 1`] = ` "❌ Your project uses Angular < 14.0.0. Storybook 7.0 for Angular requires Angular 14.0.0 or higher. Please upgrade your Angular version to at least version 14.0.0 to use Storybook 7.0 in your project." `;
557
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/helpers/checkWebpack5Builder.test.ts
import type { StorybookConfig } from '@storybook/types'; import { checkWebpack5Builder } from './checkWebpack5Builder'; import { getBuilderPackageName } from './mainConfigFile'; const mockMainConfig: StorybookConfig = { framework: 'react', addons: [], stories: [], }; jest.mock('./mainConfigFile'); describe('checkWebpack5Builder', () => { let loggerWarnSpy: jest.SpyInstance; let loggerInfoSpy: jest.SpyInstance; beforeEach(() => { loggerWarnSpy = jest.spyOn(console, 'warn').mockImplementation(); loggerInfoSpy = jest.spyOn(console, 'info').mockImplementation(); }); afterEach(() => { loggerWarnSpy.mockRestore(); loggerInfoSpy.mockRestore(); }); it('should return null and log a warning if storybook version is below 6.3.0', async () => { const result = await checkWebpack5Builder({ mainConfig: mockMainConfig, storybookVersion: '6.2.9', }); expect(result).toBeNull(); expect(loggerWarnSpy).toHaveBeenCalledWith(expect.any(String)); }); it('should return null if storybook version is 7.0.0 or above', async () => { const result = await checkWebpack5Builder({ mainConfig: mockMainConfig, storybookVersion: '7.0.0', }); expect(result).toBeNull(); expect(loggerWarnSpy).not.toHaveBeenCalled(); }); it('should return null and log a warning if mainConfig is missing', async () => { const result = await checkWebpack5Builder({ mainConfig: undefined, storybookVersion: '6.3.0', }); expect(result).toBeNull(); expect(loggerWarnSpy).toHaveBeenCalledWith(expect.any(String)); }); it('should return null and log an info message if builderPackageName is found but not "webpack4"', async () => { jest.mocked(getBuilderPackageName).mockReturnValueOnce('webpack5'); const result = await checkWebpack5Builder({ mainConfig: mockMainConfig, storybookVersion: '6.3.0', }); expect(result).toBeNull(); expect(loggerInfoSpy).toHaveBeenCalledWith(expect.any(String)); }); it('should return { storybookVersion } if all checks pass', async () => { jest.mocked(getBuilderPackageName).mockReturnValueOnce('webpack4'); const result = await checkWebpack5Builder({ mainConfig: mockMainConfig, storybookVersion: '6.3.0', }); expect(result).toEqual({ storybookVersion: '6.3.0' }); expect(loggerWarnSpy).not.toHaveBeenCalled(); expect(loggerInfoSpy).not.toHaveBeenCalled(); }); });
562
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/helpers/getMigrationSummary.test.ts
import { getMigrationSummary } from './getMigrationSummary'; import { FixStatus } from '../types'; import type { InstallationMetadata } from '../../js-package-manager/types'; jest.mock('boxen', () => // eslint-disable-next-line no-control-regex jest.fn((str, { title = '' }) => `${title}\n\n${str.replace(/\x1b\[[0-9;]*[mG]/g, '')}`) ); describe('getMigrationSummary', () => { const fixResults = { 'foo-package': FixStatus.SUCCEEDED, 'bar-package': FixStatus.MANUAL_SUCCEEDED, 'baz-package': FixStatus.CHECK_FAILED, 'qux-package': FixStatus.FAILED, 'quux-package': FixStatus.UNNECESSARY, }; const fixSummary = { succeeded: ['foo-package'], failed: { 'baz-package': 'Some error message' }, manual: ['bar-package'], skipped: ['quux-package'], }; const installationMetadata: InstallationMetadata = { duplicatedDependencies: { '@storybook/core-client': ['7.0.0', '7.1.0'], '@storybook/instrumenter': ['6.0.0', '7.1.0'], '@storybook/core-common': ['6.0.0', '7.1.0'], '@storybook/addon-essentials': ['7.0.0', '7.1.0'], }, dependencies: {}, infoCommand: 'yarn why', dedupeCommand: 'yarn dedupe', }; const logFile = '/path/to/log/file'; test('renders a summary with a "no migrations" message if all migrations were unnecessary', () => { const summary = getMigrationSummary({ fixResults: { 'foo-package': FixStatus.UNNECESSARY }, fixSummary: { succeeded: [], failed: {}, manual: [], skipped: [], }, installationMetadata, logFile, }); expect(summary).toContain('No migrations were applicable to your project'); }); test('renders a summary with a "check failed" message if at least one migration completely failed', () => { const summary = getMigrationSummary({ fixResults: { 'foo-package': FixStatus.SUCCEEDED, 'bar-package': FixStatus.MANUAL_SUCCEEDED, 'baz-package': FixStatus.FAILED, }, fixSummary: { succeeded: [], failed: { 'baz-package': 'Some error message' }, manual: ['bar-package'], skipped: [], }, installationMetadata, logFile, }); expect(summary).toContain('Migration check ran with failures'); }); test('renders a summary with successful, manual, failed, and skipped migrations', () => { const summary = getMigrationSummary({ fixResults, fixSummary, installationMetadata: null, logFile, }); expect(summary).toMatchInlineSnapshot(` "Migration check ran with failures Successful migrations: foo-package Failed migrations: baz-package: Some error message You can find the full logs in /path/to/log/file Manual migrations: bar-package Skipped migrations: quux-package ───────────────────────────────────────────────── If you'd like to run the migrations again, you can do so by running 'npx storybook@next automigrate' The automigrations try to migrate common patterns in your project, but might not contain everything needed to migrate to the latest version of Storybook. Please check the changelog and migration guide for manual migrations and more information: https://storybook.js.org/migration-guides/7.0 And reach out on Discord if you need help: https://discord.gg/storybook" `); }); test('renders a summary with a warning if there are duplicated dependencies outside the allow list', () => { const summary = getMigrationSummary({ fixResults: {}, fixSummary: { succeeded: [], failed: {}, manual: [], skipped: [] }, installationMetadata, logFile, }); expect(summary).toMatchInlineSnapshot(` "No migrations were applicable to your project If you'd like to run the migrations again, you can do so by running 'npx storybook@next automigrate' The automigrations try to migrate common patterns in your project, but might not contain everything needed to migrate to the latest version of Storybook. Please check the changelog and migration guide for manual migrations and more information: https://storybook.js.org/migration-guides/7.0 And reach out on Discord if you need help: https://discord.gg/storybook ───────────────────────────────────────────────── Critical: The following dependencies are duplicated and WILL cause unexpected behavior: @storybook/instrumenter: 6.0.0, 7.1.0 @storybook/core-common: 6.0.0, 7.1.0 Attention: The following dependencies are duplicated which might cause unexpected behavior: @storybook/addon-essentials: 7.0.0, 7.1.0 You can find more information for a given dependency by running yarn why <package-name> Please try de-duplicating these dependencies by running yarn dedupe" `); }); test('renders a basic summary if there are no duplicated dependencies or migrations', () => { const summary = getMigrationSummary({ fixResults: {}, fixSummary: { succeeded: [], failed: {}, manual: [], skipped: [] }, installationMetadata: undefined, logFile, }); expect(summary).toMatchInlineSnapshot(` "No migrations were applicable to your project If you'd like to run the migrations again, you can do so by running 'npx storybook@next automigrate' The automigrations try to migrate common patterns in your project, but might not contain everything needed to migrate to the latest version of Storybook. Please check the changelog and migration guide for manual migrations and more information: https://storybook.js.org/migration-guides/7.0 And reach out on Discord if you need help: https://discord.gg/storybook" `); }); });
564
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/helpers/mainConfigFile.test.ts
import { getBuilderPackageName, getFrameworkPackageName, getRendererPackageNameFromFramework, } from './mainConfigFile'; describe('getBuilderPackageName', () => { it('should return null when mainConfig is undefined or null', () => { const packageName = getBuilderPackageName(undefined); expect(packageName).toBeNull(); const packageName2 = getBuilderPackageName(null); expect(packageName2).toBeNull(); }); it('should return null when builder package name or path is not found', () => { const mainConfig = {}; const packageName = getBuilderPackageName(mainConfig as any); expect(packageName).toBeNull(); }); it('should return builder package name when core.builder is a string', () => { const builderPackage = '@storybook/builder-webpack5'; const mainConfig = { core: { builder: builderPackage, }, }; const packageName = getBuilderPackageName(mainConfig as any); expect(packageName).toBe(builderPackage); }); it('should return builder package name when core.builder.name contains valid builder package name', () => { const builderPackage = '@storybook/builder-webpack5'; const packageNameOrPath = `/path/to/${builderPackage}`; const mainConfig = { core: { builder: { name: packageNameOrPath }, }, }; const packageName = getBuilderPackageName(mainConfig as any); expect(packageName).toBe(builderPackage); }); it('should return builder package name when core.builder.name contains windows backslash paths', () => { const builderPackage = '@storybook/builder-webpack5'; const packageNameOrPath = 'c:\\path\\to\\@storybook\\builder-webpack5'; const mainConfig = { core: { builder: { name: packageNameOrPath }, }, }; const packageName = getBuilderPackageName(mainConfig as any); expect(packageName).toBe(builderPackage); }); it(`should return package name or path when core.builder doesn't contain the name of a valid builder package`, () => { const packageNameOrPath = '@my-org/storybook-builder'; const mainConfig = { core: { builder: packageNameOrPath, }, }; const packageName = getBuilderPackageName(mainConfig as any); expect(packageName).toBe(packageNameOrPath); }); }); describe('getFrameworkPackageName', () => { it('should return null when mainConfig is undefined or null', () => { const packageName = getFrameworkPackageName(undefined); expect(packageName).toBeNull(); const packageName2 = getFrameworkPackageName(null); expect(packageName2).toBeNull(); }); it('should return null when framework package name or path is not found', () => { const mainConfig = {}; const packageName = getFrameworkPackageName(mainConfig as any); expect(packageName).toBeNull(); }); it('should return framework package name when framework is a string', () => { const frameworkPackage = '@storybook/react'; const mainConfig = { framework: frameworkPackage, }; const packageName = getFrameworkPackageName(mainConfig as any); expect(packageName).toBe(frameworkPackage); }); it('should return framework package name when framework.name contains valid framework package name', () => { const frameworkPackage = '@storybook/react-vite'; const packageNameOrPath = `/path/to/${frameworkPackage}`; const mainConfig = { framework: { name: packageNameOrPath }, }; const packageName = getFrameworkPackageName(mainConfig as any); expect(packageName).toBe(frameworkPackage); }); it('should return builder package name when framework.name contains windows backslash paths', () => { const builderPackage = '@storybook/react-vite'; const packageNameOrPath = 'c:\\path\\to\\@storybook\\react-vite'; const mainConfig = { framework: { name: packageNameOrPath }, }; const packageName = getFrameworkPackageName(mainConfig as any); expect(packageName).toBe(builderPackage); }); it(`should return package name or path when framework does not contain the name of a valid framework package`, () => { const packageNameOrPath = '@my-org/storybook-framework'; const mainConfig = { framework: packageNameOrPath, }; const packageName = getFrameworkPackageName(mainConfig as any); expect(packageName).toBe(packageNameOrPath); }); }); describe('getRendererPackageNameFromFramework', () => { it('should return null when given no package name', () => { const packageName = getRendererPackageNameFromFramework(undefined); expect(packageName).toBeNull(); }); it('should return the frameworkPackageName if it exists in rendererPackages', () => { const frameworkPackageName = '@storybook/angular'; const packageName = getRendererPackageNameFromFramework(frameworkPackageName); expect(packageName).toBe(frameworkPackageName); }); it('should return the corresponding key of rendererPackages if the value is the same as the frameworkPackageName', () => { const frameworkPackageName = 'vue'; const expectedPackageName = '@storybook/vue'; const packageName = getRendererPackageNameFromFramework(frameworkPackageName); expect(packageName).toBe(expectedPackageName); }); it('should return null if a frameworkPackageName is known but not available in rendererPackages', () => { const frameworkPackageName = '@storybook/unknown'; const packageName = getRendererPackageNameFromFramework(frameworkPackageName); expect(packageName).toBeNull(); }); });
566
0
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate
petrpan-code/storybookjs/storybook/code/lib/cli/src/automigrate/helpers/new-frameworks-utils.test.ts
import * as findUp from 'find-up'; import { detectBuilderInfo as _getBuilderInfo, getNextjsAddonOptions, } from './new-frameworks-utils'; import type { JsPackageManager } from '../../js-package-manager'; jest.mock('find-up'); type GetBuilderInfoParams = Parameters<typeof _getBuilderInfo>[0]['mainConfig']; const getBuilderInfo = async ({ mainConfig = {}, packageManager = {}, configDir = '.storybook', }: { mainConfig?: Partial<GetBuilderInfoParams>; packageManager?: Partial<JsPackageManager>; configDir?: string; }) => { return _getBuilderInfo({ mainConfig: mainConfig as any, configDir, packageManager: packageManager as any, }); }; describe('getBuilderInfo', () => { it('should infer webpack5 info from builder', async () => { await expect( getBuilderInfo({ mainConfig: { core: { builder: '@storybook/builder-webpack5', }, }, }) ).resolves.toEqual({ name: 'webpack5', options: {} }); await expect( getBuilderInfo({ mainConfig: { core: { builder: { name: '@storybook/builder-webpack5', options: { lazyCompilation: true }, }, }, }, }) ).resolves.toEqual({ name: 'webpack5', options: { lazyCompilation: true }, }); }); it('should infer webpack5 info from framework', async () => { await expect( getBuilderInfo({ packageManager: { getPackageVersion: (packageName) => { if (packageName === '@storybook/react-webpack5') { return Promise.resolve('1.0.0'); } return Promise.resolve(null); }, }, mainConfig: { framework: '@storybook/react-webpack5', }, }) ).resolves.toEqual({ name: 'webpack5', options: {} }); await expect( getBuilderInfo({ mainConfig: { framework: { name: '@storybook/react-webpack5', options: { builder: { lazyCompilation: true, }, }, }, }, }) ).resolves.toEqual({ name: 'webpack5', options: { lazyCompilation: true }, }); }); it('should infer vite info from builder', async () => { await expect( getBuilderInfo({ mainConfig: { core: { builder: '@storybook/builder-vite' }, }, }) ).resolves.toEqual({ name: 'vite', options: {} }); await expect( getBuilderInfo({ mainConfig: { core: { builder: { name: '@storybook/builder-vite', options: { foo: 'bar' }, }, }, }, }) ).resolves.toEqual({ name: 'vite', options: { foo: 'bar' }, }); }); it('should infer vite info from framework', async () => { await expect( getBuilderInfo({ mainConfig: { framework: '@storybook/react-vite', }, }) ).resolves.toEqual({ name: 'vite', options: {} }); await expect( getBuilderInfo({ mainConfig: { framework: { name: '@storybook/react-vite', options: { builder: { foo: 'bar' } }, }, }, }) ).resolves.toEqual({ name: 'vite', options: { foo: 'bar' }, }); }); it('should infer vite info from known community frameworks', async () => { await expect( getBuilderInfo({ mainConfig: { framework: 'storybook-framework-qwik', }, }) ).resolves.toEqual({ name: 'vite', options: {} }); await expect( getBuilderInfo({ mainConfig: { framework: { name: 'storybook-solidjs-vite', options: { builder: { foo: 'bar' } }, }, }, }) ).resolves.toEqual({ name: 'vite', options: { foo: 'bar' }, }); }); it('when main.js has legacy renderer as framework, it should infer vite info from vite config file', async () => { const findUpSpy = jest .spyOn(findUp, 'default') .mockReturnValueOnce(Promise.resolve('vite.config.js')); await expect(getBuilderInfo({ mainConfig: { framework: 'react' } })).resolves.toEqual({ name: 'vite', options: {}, }); expect(findUpSpy).toHaveBeenCalledTimes(1); }); it('when main.js has legacy renderer as framework, it should infer webpack info from webpack config file', async () => { const findUpSpy = jest .spyOn(findUp, 'default') .mockReturnValueOnce(Promise.resolve(undefined)) .mockReturnValueOnce(Promise.resolve('webpack.config.js')); await expect(getBuilderInfo({ mainConfig: { framework: 'react' } })).resolves.toEqual({ name: 'webpack5', options: {}, }); expect(findUpSpy).toHaveBeenCalledTimes(2); }); it('when main.js has no builder or framework, it should infer vite info from vite config file', async () => { const findUpSpy = jest .spyOn(findUp, 'default') .mockReturnValueOnce(Promise.resolve('vite.config.js')); await expect(getBuilderInfo({ mainConfig: {} })).resolves.toEqual({ name: 'vite', options: {}, }); expect(findUpSpy).toHaveBeenCalledTimes(1); }); it('when main.js has no builder or framework, it should infer webpack info from webpack config file', async () => { const findUpSpy = jest .spyOn(findUp, 'default') .mockReturnValueOnce(Promise.resolve(undefined)) .mockReturnValueOnce(Promise.resolve('webpack.config.js')); await expect(getBuilderInfo({ mainConfig: {} })).resolves.toEqual({ name: 'webpack5', options: {}, }); expect(findUpSpy).toHaveBeenCalledTimes(2); }); it('when main.js has no builder or framework, and there is no vite or webpack config, infer vite from dependencies', async () => { const findUpSpy = jest.spyOn(findUp, 'default').mockReturnValue(Promise.resolve(undefined)); await expect( getBuilderInfo({ mainConfig: {}, packageManager: { getPackageVersion: (packageName) => { if (packageName === '@storybook/builder-vite') { return Promise.resolve('7.0.0'); } return Promise.resolve(null); }, }, }) ).resolves.toEqual({ name: 'vite', options: {}, }); expect(findUpSpy).toHaveBeenCalledTimes(2); }); it('when main.js has no builder or framework, and there is no vite or webpack config, infer webpack from dependencies', async () => { const findUpSpy = jest.spyOn(findUp, 'default').mockReturnValue(Promise.resolve(undefined)); await expect( getBuilderInfo({ mainConfig: {}, packageManager: { getPackageVersion: (packageName) => { if (packageName === '@storybook/builder-webpack5') { return Promise.resolve('7.0.0'); } return Promise.resolve(null); }, }, }) ).resolves.toEqual({ name: 'webpack5', options: {}, }); expect(findUpSpy).toHaveBeenCalledTimes(2); }); }); describe('getNextjsAddonOptions', () => { it('should find storybook-addon-next and extract its options', () => { expect(getNextjsAddonOptions(['foo', 'bar'])).toEqual({}); expect(getNextjsAddonOptions(['foo', 'storybook-addon-next'])).toEqual({}); expect(getNextjsAddonOptions(['foo', { name: 'storybook-addon-next' }])).toEqual({}); expect(getNextjsAddonOptions(['foo', { name: 'storybook-addon-next', options: {} }])).toEqual( {} ); expect( getNextjsAddonOptions([ 'foo', { name: 'storybook-addon-next', options: { nextConfigPath: 'foo/bar', }, }, ]) ).toEqual({ nextConfigPath: 'foo/bar' }); }); });
575
0
petrpan-code/storybookjs/storybook/code/lib/cli/src
petrpan-code/storybookjs/storybook/code/lib/cli/src/generators/configure.test.ts
import fse from 'fs-extra'; import dedent from 'ts-dedent'; import { SupportedLanguage } from '../project_types'; import { configureMain, configurePreview } from './configure'; jest.mock('fs-extra'); describe('configureMain', () => { beforeAll(() => { jest.clearAllMocks(); }); test('should generate main.js', async () => { await configureMain({ language: SupportedLanguage.JAVASCRIPT, addons: [], prefixes: [], storybookConfigFolder: '.storybook', framework: { name: '@storybook/react-vite', }, }); const { calls } = (fse.writeFile as unknown as jest.Mock).mock; const [mainConfigPath, mainConfigContent] = calls[0]; expect(mainConfigPath).toEqual('./.storybook/main.js'); expect(mainConfigContent).toMatchInlineSnapshot(` "/** @type { import('@storybook/react-vite').StorybookConfig } */ const config = { stories: ['../stories/**/*.mdx', '../stories/**/*.stories.@(js|jsx|mjs|ts|tsx)'], addons: [], framework: { name: '@storybook/react-vite', }, }; export default config; " `); }); test('should generate main.ts', async () => { await configureMain({ language: SupportedLanguage.TYPESCRIPT_4_9, addons: [], prefixes: [], storybookConfigFolder: '.storybook', framework: { name: '@storybook/react-vite', }, }); const { calls } = (fse.writeFile as unknown as jest.Mock).mock; const [mainConfigPath, mainConfigContent] = calls[0]; expect(mainConfigPath).toEqual('./.storybook/main.ts'); expect(mainConfigContent).toMatchInlineSnapshot(` "import type { StorybookConfig } from '@storybook/react-vite'; const config: StorybookConfig = { stories: ['../stories/**/*.mdx', '../stories/**/*.stories.@(js|jsx|mjs|ts|tsx)'], addons: [], framework: { name: '@storybook/react-vite', }, }; export default config; " `); }); test('should handle resolved paths in pnp', async () => { await configureMain({ language: SupportedLanguage.JAVASCRIPT, prefixes: [], addons: [ "%%path.dirname(require.resolve(path.join('@storybook/addon-links', 'package.json')))%%", "%%path.dirname(require.resolve(path.join('@storybook/addon-essentials', 'package.json')))%%", "%%path.dirname(require.resolve(path.join('@storybook/preset-create-react-app', 'package.json')))%%", "%%path.dirname(require.resolve(path.join('@storybook/addon-interactions', 'package.json')))%%", ], storybookConfigFolder: '.storybook', framework: { name: "%%path.dirname(require.resolve(path.join('@storybook/react-webpack5', 'package.json')))%%", }, }); const { calls } = (fse.writeFile as unknown as jest.Mock).mock; const [mainConfigPath, mainConfigContent] = calls[0]; expect(mainConfigPath).toEqual('./.storybook/main.js'); expect(mainConfigContent).toMatchInlineSnapshot(` "import path from 'path'; /** @type { import('@storybook/react-webpack5').StorybookConfig } */ const config = { stories: ['../stories/**/*.mdx', '../stories/**/*.stories.@(js|jsx|mjs|ts|tsx)'], addons: [ path.dirname(require.resolve(path.join('@storybook/addon-links', 'package.json'))), path.dirname(require.resolve(path.join('@storybook/addon-essentials', 'package.json'))), path.dirname(require.resolve(path.join('@storybook/preset-create-react-app', 'package.json'))), path.dirname(require.resolve(path.join('@storybook/addon-interactions', 'package.json'))), ], framework: { name: path.dirname(require.resolve(path.join('@storybook/react-webpack5', 'package.json'))), }, }; export default config; " `); }); }); describe('configurePreview', () => { test('should generate preview.js', async () => { await configurePreview({ language: SupportedLanguage.JAVASCRIPT, storybookConfigFolder: '.storybook', rendererId: 'react', }); const { calls } = (fse.writeFile as unknown as jest.Mock).mock; const [previewConfigPath, previewConfigContent] = calls[0]; expect(previewConfigPath).toEqual('./.storybook/preview.js'); expect(previewConfigContent).toMatchInlineSnapshot(` "/** @type { import('@storybook/react').Preview } */ const preview = { parameters: { actions: { argTypesRegex: '^on[A-Z].*' }, controls: { matchers: { color: /(background|color)$/i, date: /Date$/i, }, }, }, }; export default preview; " `); }); test('should generate preview.ts', async () => { await configurePreview({ language: SupportedLanguage.TYPESCRIPT_4_9, storybookConfigFolder: '.storybook', rendererId: 'react', }); const { calls } = (fse.writeFile as unknown as jest.Mock).mock; const [previewConfigPath, previewConfigContent] = calls[0]; expect(previewConfigPath).toEqual('./.storybook/preview.ts'); expect(previewConfigContent).toMatchInlineSnapshot(` "import type { Preview } from '@storybook/react'; const preview: Preview = { parameters: { actions: { argTypesRegex: '^on[A-Z].*' }, controls: { matchers: { color: /(background|color)$/i, date: /Date$/i, }, }, }, }; export default preview; " `); }); test('should not do anything if the framework template already included a preview', async () => { (fse.pathExists as unknown as jest.Mock).mockReturnValueOnce(true); await configurePreview({ language: SupportedLanguage.TYPESCRIPT_4_9, storybookConfigFolder: '.storybook', rendererId: 'react', }); expect(fse.writeFile).not.toHaveBeenCalled(); }); test('should add prefix if frameworkParts are passed', async () => { await configurePreview({ language: SupportedLanguage.TYPESCRIPT_4_9, storybookConfigFolder: '.storybook', rendererId: 'angular', frameworkPreviewParts: { prefix: dedent` import { setCompodocJson } from "@storybook/addon-docs/angular"; import docJson from "../documentation.json"; setCompodocJson(docJson); `, }, }); const { calls } = (fse.writeFile as unknown as jest.Mock).mock; const [previewConfigPath, previewConfigContent] = calls[0]; expect(previewConfigPath).toEqual('./.storybook/preview.ts'); expect(previewConfigContent).toMatchInlineSnapshot(` "import type { Preview } from '@storybook/angular'; import { setCompodocJson } from '@storybook/addon-docs/angular'; import docJson from '../documentation.json'; setCompodocJson(docJson); const preview: Preview = { parameters: { actions: { argTypesRegex: '^on[A-Z].*' }, controls: { matchers: { color: /(background|color)$/i, date: /Date$/i, }, }, }, }; export default preview; " `); }); });
598
0
petrpan-code/storybookjs/storybook/code/lib/cli/src
petrpan-code/storybookjs/storybook/code/lib/cli/src/js-package-manager/JsPackageManagerFactory.test.ts
import { sync as spawnSync } from 'cross-spawn'; import { sync as findUpSync } from 'find-up'; import path from 'path'; import { JsPackageManagerFactory } from './JsPackageManagerFactory'; import { NPMProxy } from './NPMProxy'; import { PNPMProxy } from './PNPMProxy'; import { Yarn1Proxy } from './Yarn1Proxy'; import { Yarn2Proxy } from './Yarn2Proxy'; jest.mock('cross-spawn'); const spawnSyncMock = spawnSync as jest.Mock; jest.mock('find-up'); const findUpSyncMock = findUpSync as unknown as jest.Mock; describe('JsPackageManagerFactory', () => { beforeEach(() => { findUpSyncMock.mockReturnValue(undefined); }); describe('getPackageManager', () => { describe('return an NPM proxy', () => { it('when `force` option is `npm`', () => { expect(JsPackageManagerFactory.getPackageManager({ force: 'npm' })).toBeInstanceOf( NPMProxy ); }); it('when all package managers are ok, but only a `package-lock.json` file', () => { spawnSyncMock.mockImplementation((command) => { // Yarn is ok if (command === 'yarn') { return { status: 0, output: '1.22.4', }; } // NPM is ok if (command === 'npm') { return { status: 0, output: '6.5.12', }; } // PNPM is ok if (command === 'pnpm') { return { status: 0, output: '7.9.5', }; } // Unknown package manager is ko return { status: 1, }; }); // There is only a package-lock.json findUpSyncMock.mockImplementation(() => '/Users/johndoe/Documents/package-lock.json'); expect(JsPackageManagerFactory.getPackageManager()).toBeInstanceOf(NPMProxy); }); }); describe('return a PNPM proxy', () => { it('when `force` option is `pnpm`', () => { expect(JsPackageManagerFactory.getPackageManager({ force: 'pnpm' })).toBeInstanceOf( PNPMProxy ); }); it('when all package managers are ok, but only a `pnpm-lock.yaml` file', () => { spawnSyncMock.mockImplementation((command) => { // Yarn is ok if (command === 'yarn') { return { status: 0, output: '1.22.4', }; } // NPM is ok if (command === 'npm') { return { status: 0, output: '6.5.12', }; } // PNPM is ok if (command === 'pnpm') { return { status: 0, output: '7.9.5', }; } // Unknown package manager is ko return { status: 1, }; }); // There is only a pnpm-lock.yaml findUpSyncMock.mockImplementation(() => '/Users/johndoe/Documents/pnpm-lock.yaml'); expect(JsPackageManagerFactory.getPackageManager()).toBeInstanceOf(PNPMProxy); }); it('when a pnpm-lock.yaml file is closer than a yarn.lock', () => { // Allow find-up to work as normal, we'll set the cwd to our fixture package findUpSyncMock.mockImplementation(jest.requireActual('find-up').sync); spawnSyncMock.mockImplementation((command) => { // Yarn is ok if (command === 'yarn') { return { status: 0, output: '1.22.4', }; } // NPM is ok if (command === 'npm') { return { status: 0, output: '6.5.12', }; } // PNPM is ok if (command === 'pnpm') { return { status: 0, output: '7.9.5', }; } // Unknown package manager is ko return { status: 1, }; }); const fixture = path.join(__dirname, 'fixtures', 'pnpm-workspace', 'package'); expect(JsPackageManagerFactory.getPackageManager({}, fixture)).toBeInstanceOf(PNPMProxy); }); }); describe('return a Yarn 1 proxy', () => { it('when `force` option is `yarn1`', () => { expect(JsPackageManagerFactory.getPackageManager({ force: 'yarn1' })).toBeInstanceOf( Yarn1Proxy ); }); it('when Yarn command is ok, Yarn version is <2, NPM is ko, PNPM is ko', () => { spawnSyncMock.mockImplementation((command) => { // Yarn is ok if (command === 'yarn') { return { status: 0, output: '1.22.4', }; } // NPM is ko if (command === 'npm') { return { status: 1, }; } // PNPM is ko if (command === 'pnpm') { return { status: 1, }; } // Unknown package manager is ko return { status: 1, }; }); // there is no lockfile findUpSyncMock.mockReturnValue(undefined); expect(JsPackageManagerFactory.getPackageManager()).toBeInstanceOf(Yarn1Proxy); }); it('when Yarn command is ok, Yarn version is <2, NPM and PNPM are ok, there is a `yarn.lock` file', () => { spawnSyncMock.mockImplementation((command) => { // Yarn is ok if (command === 'yarn') { return { status: 0, output: '1.22.4', }; } // NPM is ok if (command === 'npm') { return { status: 0, output: '6.5.12', }; } // PNPM is ok if (command === 'pnpm') { return { status: 0, output: '7.9.5', }; } // Unknown package manager is ko return { status: 1, }; }); // There is a yarn.lock findUpSyncMock.mockImplementation(() => '/Users/johndoe/Documents/yarn.lock'); expect(JsPackageManagerFactory.getPackageManager()).toBeInstanceOf(Yarn1Proxy); }); it('when multiple lockfiles are in a project, prefers yarn', () => { // Allow find-up to work as normal, we'll set the cwd to our fixture package findUpSyncMock.mockImplementation(jest.requireActual('find-up').sync); spawnSyncMock.mockImplementation((command) => { // Yarn is ok if (command === 'yarn') { return { status: 0, output: '1.22.4', }; } // NPM is ok if (command === 'npm') { return { status: 0, output: '6.5.12', }; } // PNPM is ok if (command === 'pnpm') { return { status: 0, output: '7.9.5', }; } // Unknown package manager is ko return { status: 1, }; }); const fixture = path.join(__dirname, 'fixtures', 'multiple-lockfiles'); expect(JsPackageManagerFactory.getPackageManager({}, fixture)).toBeInstanceOf(Yarn1Proxy); }); }); describe('return a Yarn 2 proxy', () => { it('when `force` option is `yarn2`', () => { expect(JsPackageManagerFactory.getPackageManager({ force: 'yarn2' })).toBeInstanceOf( Yarn2Proxy ); }); it('when Yarn command is ok, Yarn version is >=2, NPM is ko, PNPM is ko', () => { spawnSyncMock.mockImplementation((command) => { // Yarn is ok if (command === 'yarn') { return { status: 0, output: '2.0.0-rc.33', }; } // NPM is ko if (command === 'npm') { return { status: 1, }; } // PNPM is ko if (command === 'pnpm') { return { status: 1, }; } // Unknown package manager is ko return { status: 1, }; }); expect(JsPackageManagerFactory.getPackageManager()).toBeInstanceOf(Yarn2Proxy); }); it('when Yarn command is ok, Yarn version is >=2, NPM and PNPM are ok, there is a `yarn.lock` file', () => { spawnSyncMock.mockImplementation((command) => { // Yarn is ok if (command === 'yarn') { return { status: 0, output: '2.0.0-rc.33', }; } // NPM is ok if (command === 'npm') { return { status: 0, output: '6.5.12', }; } // PNPM is ok if (command === 'pnpm') { return { status: 0, output: '7.9.5', }; } // Unknown package manager is ko return { status: 1, }; }); // There is a yarn.lock findUpSyncMock.mockImplementation(() => '/Users/johndoe/Documents/yarn.lock'); expect(JsPackageManagerFactory.getPackageManager()).toBeInstanceOf(Yarn2Proxy); }); }); it('throws an error if Yarn, NPM, and PNPM are not found', () => { spawnSyncMock.mockReturnValue({ status: 1 }); expect(() => JsPackageManagerFactory.getPackageManager()).toThrow(); }); }); });
600
0
petrpan-code/storybookjs/storybook/code/lib/cli/src
petrpan-code/storybookjs/storybook/code/lib/cli/src/js-package-manager/NPMProxy.test.ts
import { NPMProxy } from './NPMProxy'; // mock createLogStream jest.mock('../utils', () => ({ createLogStream: jest.fn(() => ({ logStream: '', readLogFile: jest.fn(), moveLogFile: jest.fn(), removeLogFile: jest.fn(), })), })); describe('NPM Proxy', () => { let npmProxy: NPMProxy; beforeEach(() => { npmProxy = new NPMProxy(); }); it('type should be npm', () => { expect(npmProxy.type).toEqual('npm'); }); describe('initPackageJson', () => { it('should run `npm init -y`', async () => { const executeCommandSpy = jest.spyOn(npmProxy, 'executeCommand').mockResolvedValueOnce(''); await npmProxy.initPackageJson(); expect(executeCommandSpy).toHaveBeenCalledWith( expect.objectContaining({ command: 'npm', args: ['init', '-y'] }) ); }); }); describe('setRegistryUrl', () => { it('should run `npm config set registry https://foo.bar`', async () => { const executeCommandSpy = jest.spyOn(npmProxy, 'executeCommand').mockResolvedValueOnce(''); await npmProxy.setRegistryURL('https://foo.bar'); expect(executeCommandSpy).toHaveBeenCalledWith( expect.objectContaining({ command: 'npm', args: ['config', 'set', 'registry', 'https://foo.bar'], }) ); }); }); describe('installDependencies', () => { describe('npm6', () => { it('should run `npm install`', async () => { const executeCommandSpy = jest .spyOn(npmProxy, 'executeCommand') .mockResolvedValueOnce('6.0.0'); await npmProxy.installDependencies(); expect(executeCommandSpy).toHaveBeenLastCalledWith( expect.objectContaining({ command: 'npm', args: ['install'] }) ); }); }); describe('npm7', () => { it('should run `npm install`', async () => { const executeCommandSpy = jest .spyOn(npmProxy, 'executeCommand') .mockResolvedValueOnce('7.1.0'); await npmProxy.installDependencies(); expect(executeCommandSpy).toHaveBeenLastCalledWith( expect.objectContaining({ command: 'npm', args: ['install'] }) ); }); }); }); describe('runScript', () => { describe('npm6', () => { it('should execute script `npm exec -- compodoc -e json -d .`', async () => { const executeCommandSpy = jest .spyOn(npmProxy, 'executeCommand') .mockResolvedValueOnce('6.0.0'); npmProxy.runPackageCommand('compodoc', ['-e', 'json', '-d', '.']); expect(executeCommandSpy).toHaveBeenLastCalledWith( expect.objectContaining({ command: 'npm', args: ['exec', '--', 'compodoc', '-e', 'json', '-d', '.'], }) ); }); }); describe('npm7', () => { it('should execute script `npm run compodoc -- -e json -d .`', async () => { const executeCommandSpy = jest .spyOn(npmProxy, 'executeCommand') .mockResolvedValueOnce('7.1.0'); await npmProxy.runPackageCommand('compodoc', ['-e', 'json', '-d', '.']); expect(executeCommandSpy).toHaveBeenLastCalledWith( expect.objectContaining({ command: 'npm', args: ['exec', '--', 'compodoc', '-e', 'json', '-d', '.'], }) ); }); }); }); describe('addDependencies', () => { describe('npm6', () => { it('with devDep it should run `npm install -D @storybook/preview-api`', async () => { const executeCommandSpy = jest .spyOn(npmProxy, 'executeCommand') .mockResolvedValueOnce('6.0.0'); await npmProxy.addDependencies({ installAsDevDependencies: true }, [ '@storybook/preview-api', ]); expect(executeCommandSpy).toHaveBeenLastCalledWith( expect.objectContaining({ command: 'npm', args: ['install', '-D', '@storybook/preview-api'], }) ); }); }); describe('npm7', () => { it('with devDep it should run `npm install -D @storybook/preview-api`', async () => { const executeCommandSpy = jest .spyOn(npmProxy, 'executeCommand') .mockResolvedValueOnce('7.0.0'); await npmProxy.addDependencies({ installAsDevDependencies: true }, [ '@storybook/preview-api', ]); expect(executeCommandSpy).toHaveBeenLastCalledWith( expect.objectContaining({ command: 'npm', args: ['install', '-D', '@storybook/preview-api'], }) ); }); }); }); describe('removeDependencies', () => { describe('npm6', () => { it('with devDep it should run `npm uninstall @storybook/preview-api`', async () => { const executeCommandSpy = jest .spyOn(npmProxy, 'executeCommand') .mockResolvedValueOnce('6.0.0'); npmProxy.removeDependencies({}, ['@storybook/preview-api']); expect(executeCommandSpy).toHaveBeenLastCalledWith( expect.objectContaining({ command: 'npm', args: ['uninstall', '@storybook/preview-api'] }) ); }); }); describe('npm7', () => { it('with devDep it should run `npm uninstall @storybook/preview-api`', async () => { const executeCommandSpy = jest .spyOn(npmProxy, 'executeCommand') .mockResolvedValueOnce('7.0.0'); await npmProxy.removeDependencies({}, ['@storybook/preview-api']); expect(executeCommandSpy).toHaveBeenLastCalledWith( expect.objectContaining({ command: 'npm', args: ['uninstall', '@storybook/preview-api'] }) ); }); }); describe('skipInstall', () => { it('should only change package.json without running install', async () => { const executeCommandSpy = jest .spyOn(npmProxy, 'executeCommand') .mockResolvedValueOnce('7.0.0'); const writePackageSpy = jest .spyOn(npmProxy, 'writePackageJson') .mockImplementation(jest.fn()); await npmProxy.removeDependencies( { skipInstall: true, packageJson: { devDependencies: { '@storybook/manager-webpack5': 'x.x.x', '@storybook/react': 'x.x.x', }, }, }, ['@storybook/manager-webpack5'] ); expect(writePackageSpy).toHaveBeenCalledWith({ devDependencies: { '@storybook/react': 'x.x.x', }, }); expect(executeCommandSpy).not.toHaveBeenCalled(); }); }); }); describe('latestVersion', () => { it('without constraint it returns the latest version', async () => { const executeCommandSpy = jest .spyOn(npmProxy, 'executeCommand') .mockResolvedValueOnce('"5.3.19"'); const version = await npmProxy.latestVersion('@storybook/preview-api'); expect(executeCommandSpy).toHaveBeenCalledWith( expect.objectContaining({ command: 'npm', args: ['info', '@storybook/preview-api', 'version', '--json'], }) ); expect(version).toEqual('5.3.19'); }); it('with constraint it returns the latest version satisfying the constraint', async () => { const executeCommandSpy = jest .spyOn(npmProxy, 'executeCommand') .mockResolvedValueOnce('["4.25.3","5.3.19","6.0.0-beta.23"]'); const version = await npmProxy.latestVersion('@storybook/preview-api', '5.X'); expect(executeCommandSpy).toHaveBeenCalledWith( expect.objectContaining({ command: 'npm', args: ['info', '@storybook/preview-api', 'versions', '--json'], }) ); expect(version).toEqual('5.3.19'); }); it('throws an error if command output is not a valid JSON', async () => { jest.spyOn(npmProxy, 'executeCommand').mockResolvedValueOnce('NOT A JSON'); await expect(npmProxy.latestVersion('@storybook/preview-api')).rejects.toThrow(); }); }); describe('getVersion', () => { it('with a Storybook package listed in versions.json it returns the version', async () => { // eslint-disable-next-line global-require const storybookAngularVersion = require('../versions').default['@storybook/angular']; const executeCommandSpy = jest .spyOn(npmProxy, 'executeCommand') .mockResolvedValueOnce('"5.3.19"'); const version = await npmProxy.getVersion('@storybook/angular'); expect(executeCommandSpy).toHaveBeenCalledWith( expect.objectContaining({ command: 'npm', args: ['info', '@storybook/angular', 'version', '--json'], }) ); expect(version).toEqual(`^${storybookAngularVersion}`); }); it('with a Storybook package not listed in versions.json it returns the latest version', async () => { const packageVersion = '5.3.19'; const executeCommandSpy = jest .spyOn(npmProxy, 'executeCommand') .mockResolvedValueOnce(`"${packageVersion}"`); const version = await npmProxy.getVersion('@storybook/react-native'); expect(executeCommandSpy).toHaveBeenCalledWith( expect.objectContaining({ command: 'npm', args: ['info', '@storybook/react-native', 'version', '--json'], }) ); expect(version).toEqual(`^${packageVersion}`); }); }); describe('addPackageResolutions', () => { it('adds resolutions to package.json and account for existing resolutions', async () => { const writePackageSpy = jest .spyOn(npmProxy, 'writePackageJson') .mockImplementation(jest.fn()); jest.spyOn(npmProxy, 'retrievePackageJson').mockImplementation( jest.fn(async () => ({ dependencies: {}, devDependencies: {}, overrides: { bar: 'x.x.x', }, })) ); const versions = { foo: 'x.x.x', }; await npmProxy.addPackageResolutions(versions); expect(writePackageSpy).toHaveBeenCalledWith({ dependencies: {}, devDependencies: {}, overrides: { ...versions, bar: 'x.x.x', }, }); }); }); describe('mapDependencies', () => { it('should display duplicated dependencies based on npm output', async () => { // npm ls --depth 10 --json jest.spyOn(npmProxy, 'executeCommand').mockResolvedValueOnce(` { "dependencies": { "unrelated-and-should-be-filtered": { "version": "1.0.0" }, "@storybook/addon-interactions": { "version": "7.0.0-rc.7", "resolved": "https://registry.npmjs.org/@storybook/addon-interactions/-/addon-interactions-7.0.0-rc.7.tgz", "overridden": false, "dependencies": { "@storybook/instrumenter": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/@storybook/instrumenter/-/instrumenter-7.0.0-rc.7.tgz", "overridden": false, "dependencies": { "@storybook/channels": { "version": "7.0.0-rc.7" } } } } }, "@storybook/instrumenter": { "version": "7.0.0-beta.11", "resolved": "https://registry.npmjs.org/@storybook/instrumenter/-/instrumenter-7.0.0-beta.11.tgz", "overridden": false, "dependencies": {} }, "@storybook/jest": { "version": "0.0.11-next.1", "resolved": "https://registry.npmjs.org/@storybook/jest/-/jest-0.0.11-next.1.tgz", "overridden": false, "dependencies": { "@storybook/instrumenter": { "version": "7.0.0-alpha.21" } } }, "@storybook/testing-library": { "version": "0.0.14-next.1", "resolved": "https://registry.npmjs.org/@storybook/testing-library/-/testing-library-0.0.14-next.1.tgz", "overridden": false, "dependencies": { "@storybook/instrumenter": { "version": "5.4.2-alpha.0" } } } } } `); const installations = await npmProxy.findInstallations(); expect(installations).toMatchInlineSnapshot(` Object { "dedupeCommand": "npm dedupe", "dependencies": Object { "@storybook/addon-interactions": Array [ Object { "location": "", "version": "7.0.0-rc.7", }, ], "@storybook/channels": Array [ Object { "location": "", "version": "7.0.0-rc.7", }, ], "@storybook/instrumenter": Array [ Object { "location": "", "version": "6.0.0", }, Object { "location": "", "version": "7.0.0-beta.11", }, Object { "location": "", "version": "7.0.0-alpha.21", }, Object { "location": "", "version": "5.4.2-alpha.0", }, ], "@storybook/jest": Array [ Object { "location": "", "version": "0.0.11-next.1", }, ], "@storybook/testing-library": Array [ Object { "location": "", "version": "0.0.14-next.1", }, ], }, "duplicatedDependencies": Object { "@storybook/instrumenter": Array [ "5.4.2-alpha.0", "6.0.0", "7.0.0-alpha.21", "7.0.0-beta.11", ], }, "infoCommand": "npm ls --depth=1", } `); }); }); describe('parseErrors', () => { it('should parse npm errors', () => { const NPM_RESOLVE_ERROR_SAMPLE = ` npm ERR! npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: before-storybook@1.0.0 npm ERR! Found: react@undefined npm ERR! node_modules/react npm ERR! react@"30" from the root project `; const NPM_TIMEOUT_ERROR_SAMPLE = ` npm notice npm notice New major version of npm available! 8.5.0 -> 9.6.7 npm notice Changelog: <https://github.com/npm/cli/releases/tag/v9.6.7> npm notice Run \`npm install -g npm@9.6.7\` to update! npm notice npm ERR! code ERR_SOCKET_TIMEOUT npm ERR! errno ERR_SOCKET_TIMEOUT npm ERR! network Invalid response body while trying to fetch https://registry.npmjs.org/@storybook%2ftypes: Socket timeout npm ERR! network This is a problem related to network connectivity. `; expect(npmProxy.parseErrorFromLogs(NPM_RESOLVE_ERROR_SAMPLE)).toEqual( 'NPM error ERESOLVE - Dependency resolution error.' ); expect(npmProxy.parseErrorFromLogs(NPM_TIMEOUT_ERROR_SAMPLE)).toEqual( 'NPM error ERR_SOCKET_TIMEOUT - Socket timed out.' ); }); it('should show unknown npm error', () => { const NPM_ERROR_SAMPLE = ` npm ERR! npm ERR! While resolving: before-storybook@1.0.0 npm ERR! Found: react@undefined npm ERR! node_modules/react npm ERR! react@"30" from the root project `; expect(npmProxy.parseErrorFromLogs(NPM_ERROR_SAMPLE)).toEqual(`NPM error`); }); }); });
README.md exists but content is empty.
Downloads last month
35