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`);
});
});
});
|
602 | 0 | petrpan-code/storybookjs/storybook/code/lib/cli/src | petrpan-code/storybookjs/storybook/code/lib/cli/src/js-package-manager/PNPMProxy.test.ts | import { PNPMProxy } from './PNPMProxy';
describe('PNPM Proxy', () => {
let pnpmProxy: PNPMProxy;
beforeEach(() => {
pnpmProxy = new PNPMProxy();
});
it('type should be pnpm', () => {
expect(pnpmProxy.type).toEqual('pnpm');
});
describe('initPackageJson', () => {
it('should run `pnpm init`', async () => {
const executeCommandSpy = jest.spyOn(pnpmProxy, 'executeCommand').mockResolvedValueOnce('');
await pnpmProxy.initPackageJson();
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({ command: 'pnpm', args: ['init'] })
);
});
});
describe('setRegistryUrl', () => {
it('should run `npm config set registry https://foo.bar`', async () => {
const executeCommandSpy = jest.spyOn(pnpmProxy, 'executeCommand').mockResolvedValueOnce('');
await pnpmProxy.setRegistryURL('https://foo.bar');
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({
command: 'npm',
args: ['config', 'set', 'registry', 'https://foo.bar'],
})
);
});
});
describe('installDependencies', () => {
it('should run `pnpm install`', async () => {
const executeCommandSpy = jest
.spyOn(pnpmProxy, 'executeCommand')
.mockResolvedValueOnce('7.1.0');
await pnpmProxy.installDependencies();
expect(executeCommandSpy).toHaveBeenLastCalledWith(
expect.objectContaining({ command: 'pnpm', args: ['install'] })
);
});
});
describe('runScript', () => {
it('should execute script `pnpm exec compodoc -- -e json -d .`', async () => {
const executeCommandSpy = jest
.spyOn(pnpmProxy, 'executeCommand')
.mockResolvedValueOnce('7.1.0');
await pnpmProxy.runPackageCommand('compodoc', ['-e', 'json', '-d', '.']);
expect(executeCommandSpy).toHaveBeenLastCalledWith(
expect.objectContaining({
command: 'pnpm',
args: ['exec', 'compodoc', '-e', 'json', '-d', '.'],
})
);
});
});
describe('addDependencies', () => {
it('with devDep it should run `pnpm add -D @storybook/preview-api`', async () => {
const executeCommandSpy = jest
.spyOn(pnpmProxy, 'executeCommand')
.mockResolvedValueOnce('6.0.0');
await pnpmProxy.addDependencies({ installAsDevDependencies: true }, [
'@storybook/preview-api',
]);
expect(executeCommandSpy).toHaveBeenLastCalledWith(
expect.objectContaining({ command: 'pnpm', args: ['add', '-D', '@storybook/preview-api'] })
);
});
});
describe('removeDependencies', () => {
it('with devDep it should run `npm uninstall @storybook/preview-api`', async () => {
const executeCommandSpy = jest
.spyOn(pnpmProxy, 'executeCommand')
.mockResolvedValueOnce('6.0.0');
await pnpmProxy.removeDependencies({}, ['@storybook/preview-api']);
expect(executeCommandSpy).toHaveBeenLastCalledWith(
expect.objectContaining({ command: 'pnpm', args: ['remove', '@storybook/preview-api'] })
);
});
describe('skipInstall', () => {
it('should only change package.json without running install', async () => {
const executeCommandSpy = jest
.spyOn(pnpmProxy, 'executeCommand')
.mockResolvedValueOnce('7.0.0');
const writePackageSpy = jest
.spyOn(pnpmProxy, 'writePackageJson')
.mockImplementation(jest.fn());
await pnpmProxy.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(pnpmProxy, 'executeCommand')
.mockResolvedValueOnce('"5.3.19"');
const version = await pnpmProxy.latestVersion('@storybook/preview-api');
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({
command: 'pnpm',
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(pnpmProxy, 'executeCommand')
.mockResolvedValueOnce('["4.25.3","5.3.19","6.0.0-beta.23"]');
const version = await pnpmProxy.latestVersion('@storybook/preview-api', '5.X');
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({
command: 'pnpm',
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(pnpmProxy, 'executeCommand').mockResolvedValueOnce('NOT A JSON');
await expect(pnpmProxy.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(pnpmProxy, 'executeCommand')
.mockResolvedValueOnce('"5.3.19"');
const version = await pnpmProxy.getVersion('@storybook/angular');
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({
command: 'pnpm',
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(pnpmProxy, 'executeCommand')
.mockResolvedValueOnce(`"${packageVersion}"`);
const version = await pnpmProxy.getVersion('@storybook/react-native');
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({
command: 'pnpm',
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(pnpmProxy, 'writePackageJson')
.mockImplementation(jest.fn());
const basePackageAttributes = {
dependencies: {},
devDependencies: {},
};
jest.spyOn(pnpmProxy, 'retrievePackageJson').mockImplementation(
jest.fn(async () => ({
...basePackageAttributes,
overrides: {
bar: 'x.x.x',
},
}))
);
const versions = {
foo: 'x.x.x',
};
await pnpmProxy.addPackageResolutions(versions);
expect(writePackageSpy).toHaveBeenCalledWith({
...basePackageAttributes,
overrides: {
...versions,
bar: 'x.x.x',
},
});
});
});
describe('mapDependencies', () => {
it('should display duplicated dependencies based on pnpm output', async () => {
// pnpm list "@storybook/*" "storybook" --depth 10 --json
jest.spyOn(pnpmProxy, 'executeCommand').mockResolvedValueOnce(`
[
{
"peerDependencies": {
"unrelated-and-should-be-filtered": {
"version": "1.0.0",
"from": "",
"resolved": ""
}
},
"dependencies": {
"@storybook/addon-interactions": {
"from": "@storybook/addon-interactions",
"version": "7.0.0-beta.13",
"resolved": "https://registry.npmjs.org/@storybook/addon-interactions/-/addon-interactions-7.0.0-beta.13.tgz",
"dependencies": {
"@storybook/instrumenter": {
"from": "@storybook/instrumenter",
"version": "7.0.0-beta.13",
"resolved": "https://registry.npmjs.org/@storybook/instrumenter/-/instrumenter-7.0.0-beta.13.tgz"
}
}
}
},
"devDependencies": {
"@storybook/jest": {
"from": "@storybook/jest",
"version": "0.0.11-next.0",
"resolved": "https://registry.npmjs.org/@storybook/jest/-/jest-0.0.11-next.0.tgz",
"dependencies": {
"@storybook/instrumenter": {
"from": "@storybook/instrumenter",
"version": "7.0.0-rc.7",
"resolved": "https://registry.npmjs.org/@storybook/instrumenter/-/instrumenter-7.0.0-rc.7.tgz"
}
}
},
"@storybook/testing-library": {
"from": "@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",
"dependencies": {
"@storybook/instrumenter": {
"from": "@storybook/instrumenter",
"version": "7.0.0-rc.7",
"resolved": "https://registry.npmjs.org/@storybook/instrumenter/-/instrumenter-7.0.0-rc.7.tgz"
}
}
},
"@storybook/nextjs": {
"from": "@storybook/nextjs",
"version": "7.0.0-beta.13",
"resolved": "https://registry.npmjs.org/@storybook/nextjs/-/nextjs-7.0.0-beta.13.tgz",
"dependencies": {
"@storybook/builder-webpack5": {
"from": "@storybook/builder-webpack5",
"version": "7.0.0-beta.13",
"resolved": "https://registry.npmjs.org/@storybook/builder-webpack5/-/builder-webpack5-7.0.0-beta.13.tgz",
"dependencies": {
"@storybook/addons": {
"from": "@storybook/addons",
"version": "7.0.0-beta.13",
"resolved": "https://registry.npmjs.org/@storybook/addons/-/addons-7.0.0-beta.13.tgz"
}
}
}
}
}
}
}
]
`);
const installations = await pnpmProxy.findInstallations(['@storybook/*']);
expect(installations).toMatchInlineSnapshot(`
Object {
"dedupeCommand": "pnpm dedupe",
"dependencies": Object {
"@storybook/addon-interactions": Array [
Object {
"location": "",
"version": "7.0.0-beta.13",
},
],
"@storybook/addons": Array [
Object {
"location": "",
"version": "7.0.0-beta.13",
},
],
"@storybook/builder-webpack5": Array [
Object {
"location": "",
"version": "7.0.0-beta.13",
},
],
"@storybook/instrumenter": Array [
Object {
"location": "",
"version": "7.0.0-rc.7",
},
Object {
"location": "",
"version": "7.0.0-beta.13",
},
],
"@storybook/jest": Array [
Object {
"location": "",
"version": "0.0.11-next.0",
},
],
"@storybook/nextjs": Array [
Object {
"location": "",
"version": "7.0.0-beta.13",
},
],
"@storybook/testing-library": Array [
Object {
"location": "",
"version": "0.0.14-next.1",
},
],
},
"duplicatedDependencies": Object {
"@storybook/instrumenter": Array [
"7.0.0-rc.7",
"7.0.0-beta.13",
],
},
"infoCommand": "pnpm list --depth=1",
}
`);
});
});
describe('parseErrors', () => {
it('should parse pnpm errors', () => {
const PNPM_ERROR_SAMPLE = `
ERR_PNPM_NO_MATCHING_VERSION No matching version found for react@29.2.0
This error happened while installing a direct dependency of /Users/yannbraga/open-source/sandboxes/react-vite/default-js/before-storybook
The latest release of react is "18.2.0".
`;
expect(pnpmProxy.parseErrorFromLogs(PNPM_ERROR_SAMPLE)).toEqual(
'PNPM error ERR_PNPM_NO_MATCHING_VERSION No matching version found for react@29.2.0'
);
});
it('should show unknown pnpm error', () => {
const PNPM_ERROR_SAMPLE = `
This error happened while installing a direct dependency of /Users/yannbraga/open-source/sandboxes/react-vite/default-js/before-storybook
The latest release of react is "18.2.0".
`;
expect(pnpmProxy.parseErrorFromLogs(PNPM_ERROR_SAMPLE)).toEqual(`PNPM error`);
});
});
});
|
605 | 0 | petrpan-code/storybookjs/storybook/code/lib/cli/src | petrpan-code/storybookjs/storybook/code/lib/cli/src/js-package-manager/Yarn1Proxy.test.ts | import dedent from 'ts-dedent';
import { Yarn1Proxy } from './Yarn1Proxy';
describe('Yarn 1 Proxy', () => {
let yarn1Proxy: Yarn1Proxy;
beforeEach(() => {
yarn1Proxy = new Yarn1Proxy();
});
it('type should be yarn1', () => {
expect(yarn1Proxy.type).toEqual('yarn1');
});
describe('initPackageJson', () => {
it('should run `yarn init -y`', async () => {
const executeCommandSpy = jest.spyOn(yarn1Proxy, 'executeCommand').mockResolvedValueOnce('');
await yarn1Proxy.initPackageJson();
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({ command: 'yarn', args: ['init', '-y'] })
);
});
});
describe('setRegistryUrl', () => {
it('should run `yarn config set npmRegistryServer https://foo.bar`', async () => {
const executeCommandSpy = jest.spyOn(yarn1Proxy, 'executeCommand').mockResolvedValueOnce('');
await yarn1Proxy.setRegistryURL('https://foo.bar');
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({
command: 'npm',
args: ['config', 'set', 'registry', 'https://foo.bar'],
})
);
});
});
describe('installDependencies', () => {
it('should run `yarn`', async () => {
const executeCommandSpy = jest.spyOn(yarn1Proxy, 'executeCommand').mockResolvedValueOnce('');
await yarn1Proxy.installDependencies();
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({
command: 'yarn',
args: ['install', '--ignore-workspace-root-check'],
})
);
});
});
describe('runScript', () => {
it('should execute script `yarn compodoc -- -e json -d .`', async () => {
const executeCommandSpy = jest
.spyOn(yarn1Proxy, 'executeCommand')
.mockResolvedValueOnce('7.1.0');
await yarn1Proxy.runPackageCommand('compodoc', ['-e', 'json', '-d', '.']);
expect(executeCommandSpy).toHaveBeenLastCalledWith(
expect.objectContaining({ command: 'yarn', args: ['compodoc', '-e', 'json', '-d', '.'] })
);
});
});
describe('addDependencies', () => {
it('with devDep it should run `yarn install -D --ignore-workspace-root-check @storybook/preview-api`', async () => {
const executeCommandSpy = jest.spyOn(yarn1Proxy, 'executeCommand').mockResolvedValueOnce('');
await yarn1Proxy.addDependencies({ installAsDevDependencies: true }, [
'@storybook/preview-api',
]);
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({
command: 'yarn',
args: ['add', '--ignore-workspace-root-check', '-D', '@storybook/preview-api'],
})
);
});
});
describe('removeDependencies', () => {
it('should run `yarn remove --ignore-workspace-root-check @storybook/preview-api`', async () => {
const executeCommandSpy = jest.spyOn(yarn1Proxy, 'executeCommand').mockResolvedValueOnce('');
yarn1Proxy.removeDependencies({}, ['@storybook/preview-api']);
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({
command: 'yarn',
args: ['remove', '--ignore-workspace-root-check', '@storybook/preview-api'],
})
);
});
it('skipInstall should only change package.json without running install', async () => {
const executeCommandSpy = jest
.spyOn(yarn1Proxy, 'executeCommand')
.mockResolvedValueOnce('7.0.0');
const writePackageSpy = jest
.spyOn(yarn1Proxy, 'writePackageJson')
.mockImplementation(jest.fn());
await yarn1Proxy.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(yarn1Proxy, 'executeCommand')
.mockResolvedValueOnce('{"type":"inspect","data":"5.3.19"}');
const version = await yarn1Proxy.latestVersion('@storybook/preview-api');
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({
command: 'yarn',
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(yarn1Proxy, 'executeCommand')
.mockResolvedValueOnce('{"type":"inspect","data":["4.25.3","5.3.19","6.0.0-beta.23"]}');
const version = await yarn1Proxy.latestVersion('@storybook/preview-api', '5.X');
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({
command: 'yarn',
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(yarn1Proxy, 'executeCommand').mockResolvedValueOnce('NOT A JSON');
await expect(yarn1Proxy.latestVersion('@storybook/preview-api')).rejects.toThrow();
});
});
describe('addPackageResolutions', () => {
it('adds resolutions to package.json and account for existing resolutions', async () => {
const writePackageSpy = jest
.spyOn(yarn1Proxy, 'writePackageJson')
.mockImplementation(jest.fn());
jest.spyOn(yarn1Proxy, 'retrievePackageJson').mockImplementation(
jest.fn(async () => ({
dependencies: {},
devDependencies: {},
resolutions: {
bar: 'x.x.x',
},
}))
);
const versions = {
foo: 'x.x.x',
};
await yarn1Proxy.addPackageResolutions(versions);
expect(writePackageSpy).toHaveBeenCalledWith({
dependencies: {},
devDependencies: {},
resolutions: {
...versions,
bar: 'x.x.x',
},
});
});
});
describe('mapDependencies', () => {
it('should display duplicated dependencies based on yarn output', async () => {
// yarn list --pattern "@storybook/*" "@storybook/react" --recursive --json
jest.spyOn(yarn1Proxy, 'executeCommand').mockResolvedValueOnce(`
{
"type": "tree",
"data": {
"type": "list",
"trees": [
{
"name": "unrelated-and-should-be-filtered@1.0.0",
"children": []
},
{
"name": "@storybook/instrumenter@7.0.0-beta.12",
"children": [
{
"name": "@storybook/types@7.0.0-beta.12",
"children": []
}
]
},
{
"name": "@storybook/addon-interactions@7.0.0-beta.19",
"children": [
{
"name": "@storybook/instrumenter@7.0.0-beta.19",
"children": []
}
]
}
]
}
}
`);
const installations = await yarn1Proxy.findInstallations(['@storybook/*']);
expect(installations).toMatchInlineSnapshot(`
Object {
"dedupeCommand": "yarn dedupe",
"dependencies": Object {
"@storybook/addon-interactions": Array [
Object {
"location": "",
"version": "7.0.0-beta.19",
},
],
"@storybook/instrumenter": Array [
Object {
"location": "",
"version": "7.0.0-beta.12",
},
Object {
"location": "",
"version": "7.0.0-beta.19",
},
],
"@storybook/types": Array [
Object {
"location": "",
"version": "7.0.0-beta.12",
},
],
},
"duplicatedDependencies": Object {
"@storybook/instrumenter": Array [
"7.0.0-beta.12",
"7.0.0-beta.19",
],
},
"infoCommand": "yarn why",
}
`);
});
});
describe('parseErrors', () => {
it('should parse yarn1 errors', () => {
const YARN1_ERROR_SAMPLE = dedent`
yarn add v1.22.19
[1/4] Resolving packages...
error Couldn't find any versions for "react" that matches "28.2.0"
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.
`;
expect(yarn1Proxy.parseErrorFromLogs(YARN1_ERROR_SAMPLE)).toEqual(
`YARN1 error: Couldn't find any versions for "react" that matches "28.2.0"`
);
});
it('should show unknown yarn1 error', () => {
const YARN1_ERROR_SAMPLE = dedent`
yarn install v1.22.19
[1/4] π Resolving packages...
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
`;
expect(yarn1Proxy.parseErrorFromLogs(YARN1_ERROR_SAMPLE)).toEqual(`YARN1 error`);
});
});
});
|
607 | 0 | petrpan-code/storybookjs/storybook/code/lib/cli/src | petrpan-code/storybookjs/storybook/code/lib/cli/src/js-package-manager/Yarn2Proxy.test.ts | import dedent from 'ts-dedent';
import { Yarn2Proxy } from './Yarn2Proxy';
describe('Yarn 2 Proxy', () => {
let yarn2Proxy: Yarn2Proxy;
beforeEach(() => {
yarn2Proxy = new Yarn2Proxy();
});
it('type should be yarn2', () => {
expect(yarn2Proxy.type).toEqual('yarn2');
});
describe('initPackageJson', () => {
it('should run `yarn init`', async () => {
const executeCommandSpy = jest.spyOn(yarn2Proxy, 'executeCommand').mockResolvedValueOnce('');
await yarn2Proxy.initPackageJson();
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({ command: 'yarn', args: ['init'] })
);
});
});
describe('installDependencies', () => {
it('should run `yarn`', async () => {
const executeCommandSpy = jest.spyOn(yarn2Proxy, 'executeCommand').mockResolvedValueOnce('');
await yarn2Proxy.installDependencies();
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({ command: 'yarn', args: ['install'] })
);
});
});
describe('runScript', () => {
it('should execute script `yarn compodoc -- -e json -d .`', async () => {
const executeCommandSpy = jest
.spyOn(yarn2Proxy, 'executeCommand')
.mockResolvedValueOnce('7.1.0');
await yarn2Proxy.runPackageCommand('compodoc', ['-e', 'json', '-d', '.']);
expect(executeCommandSpy).toHaveBeenLastCalledWith(
expect.objectContaining({
command: 'yarn',
args: ['compodoc', '-e', 'json', '-d', '.'],
})
);
});
});
describe('setRegistryUrl', () => {
it('should run `yarn config set npmRegistryServer https://foo.bar`', async () => {
const executeCommandSpy = jest.spyOn(yarn2Proxy, 'executeCommand').mockResolvedValueOnce('');
await yarn2Proxy.setRegistryURL('https://foo.bar');
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({
command: 'npm',
args: ['config', 'set', 'registry', 'https://foo.bar'],
})
);
});
});
describe('addDependencies', () => {
it('with devDep it should run `yarn install -D @storybook/preview-api`', async () => {
const executeCommandSpy = jest.spyOn(yarn2Proxy, 'executeCommand').mockResolvedValueOnce('');
await yarn2Proxy.addDependencies({ installAsDevDependencies: true }, [
'@storybook/preview-api',
]);
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({ command: 'yarn', args: ['add', '-D', '@storybook/preview-api'] })
);
});
});
describe('removeDependencies', () => {
it('should run `yarn remove @storybook/preview-api`', async () => {
const executeCommandSpy = jest.spyOn(yarn2Proxy, 'executeCommand').mockResolvedValueOnce('');
await yarn2Proxy.removeDependencies({}, ['@storybook/preview-api']);
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({
command: 'yarn',
args: ['remove', '@storybook/preview-api'],
})
);
});
it('skipInstall should only change package.json without running install', async () => {
const executeCommandSpy = jest
.spyOn(yarn2Proxy, 'executeCommand')
.mockResolvedValueOnce('7.0.0');
const writePackageSpy = jest
.spyOn(yarn2Proxy, 'writePackageJson')
.mockImplementation(jest.fn());
await yarn2Proxy.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(yarn2Proxy, 'executeCommand')
.mockResolvedValueOnce('{"name":"@storybook/preview-api","version":"5.3.19"}');
const version = await yarn2Proxy.latestVersion('@storybook/preview-api');
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({
command: 'yarn',
args: ['npm', 'info', '@storybook/preview-api', '--fields', 'version', '--json'],
})
);
expect(version).toEqual('5.3.19');
});
it('with constraint it returns the latest version satisfying the constraint', async () => {
const executeCommandSpy = jest
.spyOn(yarn2Proxy, 'executeCommand')
.mockResolvedValueOnce(
'{"name":"@storybook/preview-api","versions":["4.25.3","5.3.19","6.0.0-beta.23"]}'
);
const version = await yarn2Proxy.latestVersion('@storybook/preview-api', '5.X');
expect(executeCommandSpy).toHaveBeenCalledWith(
expect.objectContaining({
command: 'yarn',
args: ['npm', 'info', '@storybook/preview-api', '--fields', 'versions', '--json'],
})
);
expect(version).toEqual('5.3.19');
});
it('throws an error if command output is not a valid JSON', async () => {
jest.spyOn(yarn2Proxy, 'executeCommand').mockResolvedValueOnce('NOT A JSON');
await expect(yarn2Proxy.latestVersion('@storybook/preview-api')).rejects.toThrow();
});
});
describe('addPackageResolutions', () => {
it('adds resolutions to package.json and account for existing resolutions', async () => {
const writePackageSpy = jest
.spyOn(yarn2Proxy, 'writePackageJson')
.mockImplementation(jest.fn());
jest.spyOn(yarn2Proxy, 'retrievePackageJson').mockImplementation(
jest.fn(async () => ({
dependencies: {},
devDependencies: {},
resolutions: {
bar: 'x.x.x',
},
}))
);
const versions = {
foo: 'x.x.x',
};
await yarn2Proxy.addPackageResolutions(versions);
expect(writePackageSpy).toHaveBeenCalledWith({
dependencies: {},
devDependencies: {},
resolutions: {
...versions,
bar: 'x.x.x',
},
});
});
});
describe('mapDependencies', () => {
it('should display duplicated dependencies based on yarn2 output', async () => {
// yarn info --name-only --recursive "@storybook/*" "storybook"
jest.spyOn(yarn2Proxy, 'executeCommand').mockResolvedValueOnce(`
"unrelated-and-should-be-filtered@npm:1.0.0"
"@storybook/global@npm:5.0.0"
"@storybook/instrumenter@npm:7.0.0-beta.12"
"@storybook/instrumenter@npm:7.0.0-beta.19"
"@storybook/jest@npm:0.0.11-next.0"
"@storybook/manager-api@npm:7.0.0-beta.19"
"@storybook/manager@npm:7.0.0-beta.19"
"@storybook/mdx2-csf@npm:0.1.0-next.5"
`);
const installations = await yarn2Proxy.findInstallations(['@storybook/*']);
expect(installations).toMatchInlineSnapshot(`
Object {
"dedupeCommand": "yarn dedupe",
"dependencies": Object {
"@storybook/global": Array [
Object {
"location": "",
"version": "5.0.0",
},
],
"@storybook/instrumenter": Array [
Object {
"location": "",
"version": "7.0.0-beta.12",
},
Object {
"location": "",
"version": "7.0.0-beta.19",
},
],
"@storybook/jest": Array [
Object {
"location": "",
"version": "0.0.11-next.0",
},
],
"@storybook/manager": Array [
Object {
"location": "",
"version": "7.0.0-beta.19",
},
],
"@storybook/manager-api": Array [
Object {
"location": "",
"version": "7.0.0-beta.19",
},
],
"@storybook/mdx2-csf": Array [
Object {
"location": "",
"version": "0.1.0-next.5",
},
],
},
"duplicatedDependencies": Object {
"@storybook/instrumenter": Array [
"7.0.0-beta.12",
"7.0.0-beta.19",
],
},
"infoCommand": "yarn why",
}
`);
});
});
describe('parseErrors', () => {
it('should parse yarn2 errors', () => {
const YARN2_ERROR_SAMPLE = `
β€ YN0000: β Resolution step
β€ YN0001: β Error: react@npm:28.2.0: No candidates found
at ge (/Users/yannbraga/.cache/node/corepack/yarn/3.5.1/yarn.js:439:8124)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Promise.allSettled (index 8)
at async io (/Users/yannbraga/.cache/node/corepack/yarn/3.5.1/yarn.js:390:10398)
β€ YN0000: β Completed in 2s 369ms
β€ YN0000: Failed with errors in 2s 372ms
β€ YN0032: fsevents@npm:2.3.2: Implicit dependencies on node-gyp are discouraged
β€ YN0061: @npmcli/move-file@npm:2.0.1 is deprecated: This functionality has been moved to @npmcli/fs
`;
expect(yarn2Proxy.parseErrorFromLogs(YARN2_ERROR_SAMPLE)).toEqual(
'YARN2 error YN0001 - EXCEPTION: react@npm:28.2.0: No candidates found'
);
});
it('should show unknown yarn2 error', () => {
const YARN2_ERROR_SAMPLE = dedent`
β€ YN0000: β Resolution step
β€ YN0000: β Completed in 2s 369ms
β€ YN0000: Failed with errors in 2s 372ms
β€ YN0032: fsevents@npm:2.3.2: Implicit dependencies on node-gyp are discouraged
β€ YN0061: @npmcli/move-file@npm:2.0.1 is deprecated: This functionality has been moved to @npmcli/fs
`;
expect(yarn2Proxy.parseErrorFromLogs(YARN2_ERROR_SAMPLE)).toEqual(`YARN2 error`);
});
});
});
|
631 | 0 | petrpan-code/storybookjs/storybook/code/lib/client-logger | petrpan-code/storybookjs/storybook/code/lib/client-logger/src/index.test.ts | import { logger } from '.';
jest.mock('@storybook/global', () => ({ global: { ...global, LOGLEVEL: 'debug' } }));
describe('client-logger default LOGLEVEL', () => {
const initialConsole = { ...global.console };
beforeEach(() => {
global.console.trace = jest.fn();
global.console.debug = jest.fn();
global.console.log = jest.fn();
global.console.info = jest.fn();
global.console.warn = jest.fn();
global.console.error = jest.fn();
});
afterAll(() => {
global.console = initialConsole;
});
it('should have an debug method that displays the message in red, with a trace', () => {
const message = 'debug message';
logger.debug(message);
expect(global.console.debug).toHaveBeenCalledWith(message);
});
it('should have an log method that displays the message in red, with a trace', () => {
const message = 'log message';
logger.log(message);
expect(global.console.log).toHaveBeenCalledWith(message);
});
it('should have an info method that displays the message', () => {
const message = 'information';
logger.info(message);
expect(global.console.info).toHaveBeenCalledWith(message);
});
it('should have a warning method that displays the message in yellow, with a trace', () => {
const message = 'warning message';
logger.warn(message);
expect(global.console.warn).toHaveBeenCalledWith(message);
});
it('should have an error method that displays the message in red, with a trace', () => {
const message = 'error message';
logger.error(message);
expect(global.console.error).toHaveBeenCalledWith(message);
});
});
|
727 | 0 | petrpan-code/storybookjs/storybook/code/lib/codemod/src/transforms | petrpan-code/storybookjs/storybook/code/lib/codemod/src/transforms/__tests__/csf-2-to-3.test.ts | import { describe, it, expect } from '@jest/globals';
import { dedent } from 'ts-dedent';
import type { API } from 'jscodeshift';
import ansiRegex from 'ansi-regex';
import _transform from '../csf-2-to-3';
expect.addSnapshotSerializer({
print: (val: any) => val,
test: () => true,
});
const jsTransform = (source: string) =>
_transform({ source, path: 'Component.stories.js' }, {} as API, {}).trim();
const tsTransform = (source: string) =>
_transform({ source, path: 'Component.stories.ts' }, {} as API, { parser: 'tsx' }).trim();
describe('csf-2-to-3', () => {
describe('javascript', () => {
it('should replace non-simple function exports with objects', () => {
expect(
jsTransform(dedent`
export default { title: 'Cat' };
export const A = () => <Cat />;
export const B = (args) => <Button {...args} />;
`)
).toMatchInlineSnapshot(`
export default { title: 'Cat' };
export const A = () => <Cat />;
export const B = {
render: (args) => <Button {...args} />,
};
`);
});
it('should move annotations into story objects', () => {
expect(
jsTransform(dedent`
export default { title: 'Cat' };
export const A = () => <Cat />;
A.storyName = 'foo';
A.parameters = { bar: 2 };
A.play = () => {};
`)
).toMatchInlineSnapshot(`
export default { title: 'Cat' };
export const A = {
render: () => <Cat />,
name: 'foo',
parameters: { bar: 2 },
play: () => {},
};
`);
});
it('should ignore non-story exports, statements', () => {
expect(
jsTransform(dedent`
export default { title: 'components/Fruit', includeStories: ['A'] };
export const A = (args) => <Apple {...args} />;
export const B = (args) => <Banana {...args} />;
const C = (args) => <Cherry {...args} />;
`)
).toMatchInlineSnapshot(`
export default { title: 'components/Fruit', includeStories: ['A'] };
export const A = {
render: (args) => <Apple {...args} />,
};
export const B = (args) => <Banana {...args} />;
const C = (args) => <Cherry {...args} />;
`);
});
it('should do nothing when there is no meta', () => {
expect(
jsTransform(dedent`
export const A = () => <Apple />;
export const B = (args) => <Banana {...args} />;
`)
).toMatchInlineSnapshot(`
export const A = () => <Apple />;
export const B = (args) => <Banana {...args} />;
`);
});
it('should remove implicit global render function (react)', () => {
expect(
jsTransform(dedent`
export default { title: 'Cat', component: Cat };
export const A = (args) => <Cat {...args} />;
export const B = (args) => <Banana {...args} />;
`)
).toMatchInlineSnapshot(`
export default { title: 'Cat', component: Cat };
export const A = {};
export const B = {
render: (args) => <Banana {...args} />,
};
`);
});
it('should ignore object exports', () => {
expect(
jsTransform(dedent`
export default { title: 'Cat', component: Cat };
export const A = {
render: (args) => <Cat {...args} />
};
`)
).toMatchInlineSnapshot(`
export default { title: 'Cat', component: Cat };
export const A = {
render: (args) => <Cat {...args} />,
};
`);
});
it('should hoist template.bind (if there is only one)', () => {
expect(
jsTransform(dedent`
export default { title: 'Cat' };
const Template = (args) => <Cat {...args} />;
export const A = Template.bind({});
A.args = { isPrimary: false };
`)
).toMatchInlineSnapshot(`
export default { title: 'Cat' };
const Template = (args) => <Cat {...args} />;
export const A = {
render: Template,
args: { isPrimary: false },
};
`);
});
it('should reuse the template when there are multiple Template.bind references but no component defined', () => {
expect(
jsTransform(dedent`
export default { title: 'Cat' };
const Template = (args) => <Cat {...args} />;
export const A = Template.bind({});
A.args = { isPrimary: false };
export const B = Template.bind({});
B.args = { isPrimary: true };
export const C = Template.bind({});
C.args = { bla: true };
export const D = Template.bind({});
D.args = { bla: false };
`)
).toMatchInlineSnapshot(`
export default { title: 'Cat' };
const Template = (args) => <Cat {...args} />;
export const A = {
render: Template,
args: { isPrimary: false },
};
export const B = {
render: Template,
args: { isPrimary: true },
};
export const C = {
render: Template,
args: { bla: true },
};
export const D = {
render: Template,
args: { bla: false },
};
`);
});
it('should remove implicit global render for template.bind', () => {
expect(
jsTransform(dedent`
export default { title: 'Cat', component: Cat };
const Template = (args) => <Cat {...args} />;
export const A = Template.bind({});
A.args = { isPrimary: false };
const Template2 = (args) => <Banana {...args} />;
export const B = Template2.bind({});
B.args = { isPrimary: true };
`)
).toMatchInlineSnapshot(`
export default { title: 'Cat', component: Cat };
export const A = {
args: { isPrimary: false },
};
const Template2 = (args) => <Banana {...args} />;
export const B = {
render: Template2,
args: { isPrimary: true },
};
`);
});
it('should ignore no-arg stories without annotations', () => {
expect(
jsTransform(dedent`
export default { title: 'Cat', component: Cat };
export const A = (args) => <Cat {...args} />;
export const B = () => <Cat name="frisky" />;
export const C = () => <Cat name="fluffy" />;
C.parameters = { foo: 2 };
`)
).toMatchInlineSnapshot(`
export default { title: 'Cat', component: Cat };
export const A = {};
export const B = () => <Cat name="frisky" />;
export const C = {
render: () => <Cat name="fluffy" />,
parameters: { foo: 2 },
};
`);
});
it('should work for v1-style annotations', () => {
expect(
jsTransform(dedent`
export default { title: 'Cat' };
export const A = (args) => <Cat {...args} />;
A.story = {
parameters: { foo: 2 }
};
`)
).toMatchInlineSnapshot(`
export default { title: 'Cat' };
export const A = {
render: (args) => <Cat {...args} />,
parameters: { foo: 2 },
};
`);
});
});
describe('typescript', () => {
it('should error with namespace imports', () => {
expect.addSnapshotSerializer({
serialize: (value) => value.replace(ansiRegex(), ''),
test: () => true,
});
expect(() =>
tsTransform(dedent`
import * as SB from '@storybook/react';
import { CatProps } from './Cat';
const meta = { title: 'Cat', component: Cat } as Meta<CatProps>
export default meta;
export const A: SB.StoryFn<CatProps> = () => <Cat />;
`)
).toThrowErrorMatchingInlineSnapshot(`
This codemod does not support namespace imports for a @storybook/react package.
Replace the namespace import with named imports and try again.
`);
});
it('should keep local names', () => {
expect(
tsTransform(dedent`
import { Meta, StoryObj as CSF3, StoryFn as CSF2 } from '@storybook/react';
import { CatProps } from './Cat';
const meta = { title: 'Cat', component: Cat } satisfies Meta<CatProps>
export default meta;
export const A: CSF2<CatProps> = () => <Cat />;
export const B: CSF3<CatProps> = {
args: { name: "already csf3" }
};
export const C: CSF2<CatProps> = (args) => <Cat {...args} />;
C.args = {
name: "Fluffy"
};
`)
).toMatchInlineSnapshot(`
import { Meta, StoryObj as CSF3, StoryFn as CSF2 } from '@storybook/react';
import { CatProps } from './Cat';
const meta = { title: 'Cat', component: Cat } satisfies Meta<CatProps>;
export default meta;
export const A: CSF2<CatProps> = () => <Cat />;
export const B: CSF3<CatProps> = {
args: { name: 'already csf3' },
};
export const C: CSF3<CatProps> = {
args: {
name: 'Fluffy',
},
};
`);
});
it('should replace function exports with objects and update type', () => {
expect(
tsTransform(dedent`
import { Story, StoryFn, ComponentStory, ComponentStoryObj } from '@storybook/react';
// some extra whitespace to test
export default {
title: 'Cat',
component: Cat,
} as Meta<CatProps>;
export const A: Story<CatProps> = (args) => <Cat {...args} />;
A.args = { name: "Fluffy" };
export const B: any = (args) => <Button {...args} />;
export const C: Story<CatProps> = () => <Cat />;
export const D: StoryFn<CatProps> = (args) => <Cat {...args} />;
D.args = {
name: "Fluffy"
};
export const E: ComponentStory<Cat> = (args) => <Cat {...args} />;
E.args = { name: "Fluffy" };
export const F: Story = (args) => <Cat {...args} />;
F.args = {
name: "Fluffy"
};
export const G: ComponentStoryObj<typeof Cat> = {
args: {
name: 'Fluffy',
},
};
`)
).toMatchInlineSnapshot(`
import { StoryObj, StoryFn } from '@storybook/react';
// some extra whitespace to test
export default {
title: 'Cat',
component: Cat,
} as Meta<CatProps>;
export const A: StoryObj<CatProps> = {
args: { name: 'Fluffy' },
};
export const B: any = {
render: (args) => <Button {...args} />,
};
export const C: StoryFn<CatProps> = () => <Cat />;
export const D: StoryObj<CatProps> = {
args: {
name: 'Fluffy',
},
};
export const E: StoryObj<Cat> = {
args: { name: 'Fluffy' },
};
export const F: StoryObj = {
args: {
name: 'Fluffy',
},
};
export const G: StoryObj<typeof Cat> = {
args: {
name: 'Fluffy',
},
};
`);
});
it('migrate Story type to StoryFn when used in an not exported Template function', () => {
expect(
tsTransform(dedent`
import { Story, Meta } from '@storybook/react'
export default {
component: Cat,
} satisfies Meta
const Template: Story = () => <div>Hello World</div>;
export const Default = Template.bind({})
`)
).toMatchInlineSnapshot(`
import { StoryFn, Meta } from '@storybook/react';
export default {
component: Cat,
} satisfies Meta;
const Template: StoryFn = () => <div>Hello World</div>;
export const Default = {
render: Template,
};
`);
});
});
});
|
728 | 0 | petrpan-code/storybookjs/storybook/code/lib/codemod/src/transforms | petrpan-code/storybookjs/storybook/code/lib/codemod/src/transforms/__tests__/mdx-to-csf.test.ts | import * as fs_ from 'node:fs';
import { expect, test } from '@jest/globals';
import dedent from 'ts-dedent';
import jscodeshift, { nameToValidExport } from '../mdx-to-csf';
expect.addSnapshotSerializer({
print: (val: any) => (typeof val === 'string' ? val : JSON.stringify(val, null, 2) ?? ''),
test: () => true,
});
jest.mock('node:fs');
const fs = fs_ as jest.Mocked<typeof import('node:fs')>;
beforeEach(() => {
fs.existsSync.mockImplementation(() => false);
});
test('update import even when no stories can be extracted', () => {
const input = dedent`
import { Heading } from '@storybook/addon-docs';
<Heading />
`;
const mdx = jscodeshift({ source: input, path: 'Foobar.stories.mdx' });
expect(mdx).toMatchInlineSnapshot(`
import { Heading } from '@storybook/blocks';
<Heading />
`);
});
test('drop invalid story nodes', () => {
const input = dedent`
import { Meta, Story } from '@storybook/addon-docs';
<Meta title="Foobar" />
<Story>No name!</Story>
<Story name="Primary">Story</Story>
`;
const mdx = jscodeshift({ source: input, path: 'Foobar.stories.mdx' });
expect(mdx).toMatchInlineSnapshot(`
import { Meta, Story } from '@storybook/blocks';
import * as FoobarStories from './Foobar.stories';
<Meta of={FoobarStories} />
<Story of={FoobarStories.Primary} />
`);
});
test('convert story re-definition', () => {
const input = dedent`
import { Meta, Story } from '@storybook/addon-docs';
import { Primary } from './Foobar.stories';
<Meta title="Foobar" />
<Story story={Primary} />
`;
fs.existsSync.mockImplementation((path) => path === 'Foobar.stories.js');
const mdx = jscodeshift({ source: input, path: 'Foobar.stories.mdx' });
expect(mdx).toMatchInlineSnapshot(`
import { Meta, Story } from '@storybook/blocks';
import { Primary } from './Foobar.stories';
import * as FoobarStories from './Foobar_.stories';
<Meta of={FoobarStories} />
<Story of={FoobarStories.Primary} />
`);
const [csfFileName, csf] = fs.writeFileSync.mock.calls[0];
expect(csfFileName).toMatchInlineSnapshot(`Foobar_.stories.js`);
expect(csf).toMatchInlineSnapshot(`
import { Primary } from './Foobar.stories';
export default {
title: 'Foobar',
};
export { Primary };
`);
});
test('Comment out story nodes with id', () => {
const input = dedent`
import { Meta, Story } from '@storybook/addon-docs';
<Meta title="Foobar" />
<Story id="button--primary" />
`;
const mdx = jscodeshift({ source: input, path: 'Foobar.stories.mdx' });
expect(mdx).toMatchInlineSnapshot(`
import { Meta, Story } from '@storybook/blocks';
import * as FoobarStories from './Foobar.stories';
<Meta of={FoobarStories} />
{/* <Story id="button--primary" /> is deprecated, please migrate it to <Story of={referenceToStory} /> see: https://storybook.js.org/migration-guides/7.0 */}
<Story id="button--primary" />
`);
});
test('convert correct story nodes', () => {
const input = dedent`
import { Meta, Story } from '@storybook/addon-docs';
<Meta title="Foobar" />
<Story name="Primary">Story</Story>
`;
const mdx = jscodeshift({ source: input, path: 'Foobar.stories.mdx' });
expect(mdx).toMatchInlineSnapshot(`
import { Meta, Story } from '@storybook/blocks';
import * as FoobarStories from './Foobar.stories';
<Meta of={FoobarStories} />
<Story of={FoobarStories.Primary} />
`);
const [, csf] = fs.writeFileSync.mock.calls[0];
expect(csf).toMatchInlineSnapshot(`
export default {
title: 'Foobar',
};
export const Primary = {
render: () => 'Story',
name: 'Primary',
};
`);
});
test('convert addon-docs imports', () => {
const input = dedent`
import { Meta } from '@storybook/addon-docs';
import { Story } from '@storybook/addon-docs/blocks';
<Meta title="Foobar" />
<Story name="Primary">Story</Story>
`;
const mdx = jscodeshift({ source: input, path: 'Foobar.stories.mdx' });
expect(mdx).toMatchInlineSnapshot(`
import { Meta } from '@storybook/blocks';
import { Story } from '@storybook/blocks';
import * as FoobarStories from './Foobar.stories';
<Meta of={FoobarStories} />
<Story of={FoobarStories.Primary} />
`);
});
test('convert story nodes with spaces', () => {
const input = dedent`
import { Meta, Story } from '@storybook/addon-docs';
<Meta title="Foobar" />
<Story name="Primary Space">Story</Story>
`;
const mdx = jscodeshift({ source: input, path: 'Foobar.stories.mdx' });
expect(mdx).toMatchInlineSnapshot(`
import { Meta, Story } from '@storybook/blocks';
import * as FoobarStories from './Foobar.stories';
<Meta of={FoobarStories} />
<Story of={FoobarStories.PrimarySpace} />
`);
const [, csf] = fs.writeFileSync.mock.calls[0];
expect(csf).toMatchInlineSnapshot(`
export default {
title: 'Foobar',
};
export const PrimarySpace = {
render: () => 'Story',
name: 'Primary Space',
};
`);
});
test('extract esm into csf head code', () => {
const input = dedent`
import { Meta, Story } from '@storybook/addon-docs';
import { Button } from './Button';
# hello
export const args = { bla: 1 };
export const Template = (args) => <Button {...args} />;
<Meta title="foobar" />
world {2 + 1}
<Story name="foo">bar</Story>
<Story
name="Unchecked"
args={{
...args,
label: 'Unchecked',
}}>
{Template.bind({})}
</Story>
`;
const mdx = jscodeshift({ source: input, path: 'Foobar.stories.mdx' });
expect(mdx).toMatchInlineSnapshot(`
import { Meta, Story } from '@storybook/blocks';
import { Button } from './Button';
import * as FoobarStories from './Foobar.stories';
# hello
export const args = { bla: 1 };
export const Template = (args) => <Button {...args} />;
<Meta of={FoobarStories} />
world {2 + 1}
<Story of={FoobarStories.Foo} />
<Story of={FoobarStories.Unchecked} />
`);
const [csfFileName, csf] = fs.writeFileSync.mock.calls[0];
expect(csfFileName).toMatchInlineSnapshot(`Foobar.stories.js`);
expect(csf).toMatchInlineSnapshot(`
import { Button } from './Button';
const args = { bla: 1 };
const Template = (args) => <Button {...args} />;
export default {
title: 'foobar',
};
export const Foo = {
render: () => 'bar',
name: 'foo',
};
export const Unchecked = {
render: Template.bind({}),
name: 'Unchecked',
args: {
...args,
label: 'Unchecked',
},
};
`);
});
test('extract all meta parameters', () => {
const input = dedent`
import { Meta, Story } from '@storybook/addon-docs';
export const args = { bla: 1 };
<Meta title="foobar" args={{...args}} parameters={{a: '1'}} />
<Story name="foo">bar</Story>
`;
jscodeshift({ source: input, path: 'Foobar.stories.mdx' });
const [, csf] = fs.writeFileSync.mock.calls[0];
expect(csf).toMatchInlineSnapshot(`
const args = { bla: 1 };
export default {
title: 'foobar',
args: {
...args,
},
parameters: {
a: '1',
},
};
export const Foo = {
render: () => 'bar',
name: 'foo',
};
`);
});
test('extract all story attributes', () => {
const input = dedent`
import { Meta, Story } from '@storybook/addon-docs';
import { Button } from './Button';
export const args = { bla: 1 };
export const Template = (args) => <Button {...args} />;
<Meta title="foobar" />
<Story name="foo">bar</Story>
<Story
name="Unchecked"
args={{
...args,
label: 'Unchecked',
}}>
{Template.bind({})}
</Story>
<Story name="Second">{Template.bind({})}</Story>
`;
jscodeshift({ source: input, path: 'Foobar.stories.mdx' });
const [, csf] = fs.writeFileSync.mock.calls[0];
expect(csf).toMatchInlineSnapshot(`
import { Button } from './Button';
const args = { bla: 1 };
const Template = (args) => <Button {...args} />;
export default {
title: 'foobar',
};
export const Foo = {
render: () => 'bar',
name: 'foo',
};
export const Unchecked = {
render: Template.bind({}),
name: 'Unchecked',
args: {
...args,
label: 'Unchecked',
},
};
export const Second = {
render: Template.bind({}),
name: 'Second',
};
`);
});
test('duplicate story name', () => {
const input = dedent`
import { Meta, Story } from '@storybook/addon-docs';
import { Button } from './Button';
export const Default = (args) => <Button {...args} />;
<Meta title="Button" />
<Story name="Default">
{Default.bind({})}
</Story>
<Story name="Second">{Default.bind({})}</Story>
`;
const mdx = jscodeshift({ source: input, path: 'Foobar.stories.mdx' });
const [, csf] = fs.writeFileSync.mock.calls[0];
expect(mdx).toMatchInlineSnapshot(`
import { Meta, Story } from '@storybook/blocks';
import { Button } from './Button';
import * as FoobarStories from './Foobar.stories';
export const Default = (args) => <Button {...args} />;
<Meta of={FoobarStories} />
<Story of={FoobarStories.Default_} />
<Story of={FoobarStories.Second} />
`);
expect(csf).toMatchInlineSnapshot(`
import { Button } from './Button';
const Default = (args) => <Button {...args} />;
export default {
title: 'Button',
};
export const Default_ = {
render: Default.bind({}),
name: 'Default',
};
export const Second = {
render: Default.bind({}),
name: 'Second',
};
`);
});
test('kebab case file name', () => {
const input = dedent`
import { Meta, Story } from '@storybook/addon-docs';
import { Kebab } from './my-component/some-kebab-case';
export const Template = (args) => <Kebab {...args} />;
<Meta title="Kebab" />
<Story name="Much-Kebab">
{Template.bind({})}
</Story>
<Story name="Really-Much-Kebab">{Template.bind({})}</Story>
`;
const mdx = jscodeshift({ source: input, path: 'some-kebab-case.stories.mdx' });
expect(mdx).toMatchInlineSnapshot(`
import { Meta, Story } from '@storybook/blocks';
import { Kebab } from './my-component/some-kebab-case';
import * as SomeKebabCaseStories from './some-kebab-case.stories';
export const Template = (args) => <Kebab {...args} />;
<Meta of={SomeKebabCaseStories} />
<Story of={SomeKebabCaseStories.MuchKebab} />
<Story of={SomeKebabCaseStories.ReallyMuchKebab} />
`);
const [, csf] = fs.writeFileSync.mock.calls[0];
expect(csf).toMatchInlineSnapshot(`
import { Kebab } from './my-component/some-kebab-case';
const Template = (args) => <Kebab {...args} />;
export default {
title: 'Kebab',
};
export const MuchKebab = {
render: Template.bind({}),
name: 'Much-Kebab',
};
export const ReallyMuchKebab = {
render: Template.bind({}),
name: 'Really-Much-Kebab',
};
`);
});
test('story child is jsx', () => {
const input = dedent`
import { Canvas, Meta, Story } from '@storybook/addon-docs';
import { Button } from './button';
<Story name="Primary">
<Button>
<div>Hello!</div>
</Button>
</Story>
`;
jscodeshift({ source: input, path: 'Foobar.stories.mdx' });
const [, csf] = fs.writeFileSync.mock.calls[0];
expect(csf).toMatchInlineSnapshot(`
import { Button } from './button';
export default {};
export const Primary = {
render: () => (
<Button>
<div>Hello!</div>
</Button>
),
name: 'Primary',
};
`);
});
test('story child is CSF3', () => {
const input = dedent`
import { Story } from '@storybook/addon-docs';
import { Button } from './button';
<Story name="Primary" render={(args) => <Button {...args}></Button> } args={{label: 'Hello' }} />
`;
jscodeshift({ source: input, path: 'Foobar.stories.mdx' });
const [, csf] = fs.writeFileSync.mock.calls[0];
expect(csf).toMatchInlineSnapshot(`
import { Button } from './button';
export default {};
export const Primary = {
name: 'Primary',
render: (args) => <Button {...args}></Button>,
args: {
label: 'Hello',
},
};
`);
});
test('story child is arrow function', () => {
const input = dedent`
import { Canvas, Meta, Story } from '@storybook/addon-docs';
import { Button } from './button';
<Story name="Primary">
{(args) => <Button />}
</Story>
`;
jscodeshift({ source: input, path: 'Foobar.stories.mdx' });
const [, csf] = fs.writeFileSync.mock.calls[0];
expect(csf).toMatchInlineSnapshot(`
import { Button } from './button';
export default {};
export const Primary = {
render: (args) => <Button />,
name: 'Primary',
};
`);
});
test('story child is identifier', () => {
const input = dedent`
import { Canvas, Meta, Story } from '@storybook/addon-docs';
import { Button } from './button';
<Story name="Primary">
{Button}
</Story>
`;
jscodeshift({ source: input, path: 'Foobar.stories.mdx' });
const [, csf] = fs.writeFileSync.mock.calls[0];
expect(csf).toMatchInlineSnapshot(`
import { Button } from './button';
export default {};
export const Primary = {
render: Button,
name: 'Primary',
};
`);
});
test('nameToValidExport', () => {
expect(nameToValidExport('1 starts with digit')).toMatchInlineSnapshot(`$1StartsWithDigit`);
expect(nameToValidExport('name')).toMatchInlineSnapshot(`Name`);
expect(nameToValidExport('Multi words')).toMatchInlineSnapshot(`MultiWords`);
// Unicode is valid in JS variable names
expect(nameToValidExport('Keep unicode π
')).toMatchInlineSnapshot(`KeepUnicodeπ
`);
});
|
730 | 0 | petrpan-code/storybookjs/storybook/code/lib/codemod/src/transforms | petrpan-code/storybookjs/storybook/code/lib/codemod/src/transforms/__tests__/upgrade-deprecated-types.test.ts | import { describe, expect, it } from '@jest/globals';
import { dedent } from 'ts-dedent';
import type { API } from 'jscodeshift';
import ansiRegex from 'ansi-regex';
import _transform from '../upgrade-deprecated-types';
expect.addSnapshotSerializer({
print: (val: any) => val,
test: () => true,
});
const tsTransform = (source: string) =>
_transform({ source, path: 'Component.stories.ts' }, {} as API, { parser: 'tsx' }).trim();
describe('upgrade-deprecated-types', () => {
describe('typescript', () => {
it('upgrade regular imports', () => {
expect(
tsTransform(dedent`
import { Story, ComponentMeta, Meta, ComponentStory, ComponentStoryObj, ComponentStoryFn } from '@storybook/react';
import { Cat, CatProps } from './Cat';
const meta = { title: 'Cat', component: Cat } satisfies ComponentMeta<typeof Cat>
const meta2: Meta<CatProps> = { title: 'Cat', component: Cat };
export default meta;
export const A: ComponentStory<typeof Cat> = (args) => <Cat {...args} />;
export const B: any = (args) => <Button {...args} />;
export const C: ComponentStoryFn<typeof Cat> = (args) => <Cat {...args} />;
export const D: ComponentStoryObj<typeof Cat> = {
args: {
name: 'Fluffy',
},
};
export const E: Story<CatProps> = (args) => <Cat {...args} />;
`)
).toMatchInlineSnapshot(`
import { StoryFn, Meta, StoryObj } from '@storybook/react';
import { Cat, CatProps } from './Cat';
const meta = { title: 'Cat', component: Cat } satisfies Meta<typeof Cat>;
const meta2: Meta<CatProps> = { title: 'Cat', component: Cat };
export default meta;
export const A: StoryFn<typeof Cat> = (args) => <Cat {...args} />;
export const B: any = (args) => <Button {...args} />;
export const C: StoryFn<typeof Cat> = (args) => <Cat {...args} />;
export const D: StoryObj<typeof Cat> = {
args: {
name: 'Fluffy',
},
};
export const E: StoryFn<CatProps> = (args) => <Cat {...args} />;
`);
});
it('upgrade imports with local names', () => {
expect(
tsTransform(dedent`
import { Story as Story_, ComponentMeta as ComponentMeta_, ComponentStory as Story__, ComponentStoryObj as ComponentStoryObj_, ComponentStoryFn as StoryFn_ } from '@storybook/react';
import { Cat } from './Cat';
const meta = { title: 'Cat', component: Cat } satisfies ComponentMeta_<typeof Cat>
const meta2: ComponentMeta_<typeof Cat> = { title: 'Cat', component: Cat };
export default meta;
export const A: Story__<typeof Cat> = (args) => <Cat {...args} />;
export const B: any = (args) => <Button {...args} />;
export const C: StoryFn_<typeof Cat> = (args) => <Cat {...args} />;
export const D: ComponentStoryObj_<typeof Cat> = {
args: {
name: 'Fluffy',
},
};
export const E: Story_<CatProps> = (args) => <Cat {...args} />;
`)
).toMatchInlineSnapshot(`
import {
StoryFn as Story_,
Meta as ComponentMeta_,
StoryObj as ComponentStoryObj_,
} from '@storybook/react';
import { Cat } from './Cat';
const meta = { title: 'Cat', component: Cat } satisfies ComponentMeta_<typeof Cat>;
const meta2: ComponentMeta_<typeof Cat> = { title: 'Cat', component: Cat };
export default meta;
export const A: Story__<typeof Cat> = (args) => <Cat {...args} />;
export const B: any = (args) => <Button {...args} />;
export const C: StoryFn_<typeof Cat> = (args) => <Cat {...args} />;
export const D: ComponentStoryObj_<typeof Cat> = {
args: {
name: 'Fluffy',
},
};
export const E: Story_<CatProps> = (args) => <Cat {...args} />;
`);
});
it('upgrade imports with conflicting local names', () => {
expect.addSnapshotSerializer({
serialize: (value) => value.replace(ansiRegex(), ''),
test: () => true,
});
expect(() =>
tsTransform(dedent`
import { ComponentMeta as Meta, ComponentStory as StoryFn } from '@storybook/react';
import { Cat } from './Cat';
const meta = { title: 'Cat', component: Cat } satisfies Meta<typeof Cat>
export default meta;
export const A: StoryFn<typeof Cat> = (args) => <Cat {...args} />;
`)
).toThrowErrorMatchingInlineSnapshot(`
This codemod does not support local imports that are called the same as a storybook import.
Rename this local import and try again.
> 1 | import { ComponentMeta as Meta, ComponentStory as StoryFn } from '@storybook/react';
| ^^^^^^^^^^^^^^^^^^^^^
2 | import { Cat } from './Cat';
3 |
4 | const meta = { title: 'Cat', component: Cat } satisfies Meta<typeof Cat>
`);
});
it('upgrade namespaces', () => {
expect(
tsTransform(dedent`
import * as SB from '@storybook/react';
import { Cat, CatProps } from './Cat';
const meta = { title: 'Cat', component: Cat } satisfies SB.ComponentMeta<typeof Cat>;
const meta2: SB.ComponentMeta<typeof Cat> = { title: 'Cat', component: Cat };
export default meta;
export const A: SB.ComponentStory<typeof Cat> = (args) => <Cat {...args} />;
export const B: any = (args) => <Button {...args} />;
export const C: SB.ComponentStoryFn<typeof Cat> = (args) => <Cat {...args} />;
export const D: SB.ComponentStoryObj<typeof Cat> = {
args: {
name: 'Fluffy',
},
};
export const E: SB.Story<CatProps> = (args) => <Cat {...args} />;
`)
).toMatchInlineSnapshot(`
import * as SB from '@storybook/react';
import { Cat, CatProps } from './Cat';
const meta = { title: 'Cat', component: Cat } satisfies SB.Meta<typeof Cat>;
const meta2: SB.Meta<typeof Cat> = { title: 'Cat', component: Cat };
export default meta;
export const A: SB.StoryFn<typeof Cat> = (args) => <Cat {...args} />;
export const B: any = (args) => <Button {...args} />;
export const C: SB.StoryFn<typeof Cat> = (args) => <Cat {...args} />;
export const D: SB.StoryObj<typeof Cat> = {
args: {
name: 'Fluffy',
},
};
export const E: SB.StoryFn<CatProps> = (args) => <Cat {...args} />;
`);
});
});
});
|
736 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-common | petrpan-code/storybookjs/storybook/code/lib/core-common/src/config.test.ts | import { filterPresetsConfig } from './presets';
describe('filterPresetsConfig', () => {
it('string config', () => {
expect(filterPresetsConfig(['@storybook/preset-scss', '@storybook/preset-typescript'])).toEqual(
['@storybook/preset-scss']
);
});
it('windows paths', () => {
expect(filterPresetsConfig(['a', '@storybook\\preset-typescript'])).toEqual(['a']);
});
it('object config', () => {
const tsConfig = {
name: '@storybook/preset-typescript',
options: { foo: 1 },
};
expect(filterPresetsConfig([tsConfig, 'a'])).toEqual(['a']);
});
});
|
738 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-common | petrpan-code/storybookjs/storybook/code/lib/core-common/src/presets.test.ts | import path from 'path';
import { logger } from '@storybook/node-logger';
import './presets';
function wrapPreset(basePresets: any): { babel: Function; webpack: Function } {
return {
babel: async (config: any, args: any) => basePresets.apply('babel', config, args),
webpack: async (config: any, args: any) => basePresets.apply('webpack', config, args),
};
}
function mockPreset(name: string, mockPresetObject: any) {
jest.mock(name, () => mockPresetObject, { virtual: true });
}
jest.mock('@storybook/node-logger', () => ({
logger: {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
},
}));
jest.mock('./utils/safeResolve', () => {
const KNOWN_FILES = [
'@storybook/react',
'@storybook/addon-actions/manager',
'@storybook/addon-actions/register',
'./local/preset',
'./local/addons',
'/absolute/preset',
'/absolute/addons',
'@storybook/addon-docs',
'@storybook/addon-cool',
'@storybook/addon-docs/preset',
'@storybook/addon-interactions/preset',
'@storybook/addon-essentials',
'@storybook/addon-knobs/manager',
'@storybook/addon-knobs/register',
'@storybook/addon-notes/register-panel',
'@storybook/preset-create-react-app',
'@storybook/preset-typescript',
'addon-bar/preset.js',
'addon-bar',
'addon-baz/register.js',
'addon-foo/register.js',
];
return {
safeResolveFrom: jest.fn((l: any, name: string) => {
if (KNOWN_FILES.includes(name)) {
return name;
}
return undefined;
}),
safeResolve: jest.fn((name: string) => {
if (KNOWN_FILES.includes(name)) {
return name;
}
return undefined;
}),
};
});
describe('presets', () => {
it('does not throw when there is no preset file', async () => {
const { getPresets } = jest.requireActual('./presets');
let presets;
async function testPresets() {
presets = wrapPreset(await getPresets());
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
expect(presets).toBeDefined();
});
it('does not throw when presets are empty', async () => {
const { getPresets } = jest.requireActual('./presets');
const presets = wrapPreset(await getPresets([]));
async function testPresets() {
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
});
it('does not throw when preset can not be loaded', async () => {
const { getPresets } = jest.requireActual('./presets');
const presets = wrapPreset(await getPresets(['preset-foo']));
async function testPresets() {
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
});
it('throws when preset can not be loaded and is critical', async () => {
const { getPresets } = jest.requireActual('./presets');
await expect(getPresets(['preset-foo'], { isCritical: true })).rejects.toThrow();
});
it('loads and applies presets when they are combined in another preset', async () => {
mockPreset('preset-foo', {
foo: (exec: string[]) => exec.concat('foo'),
});
mockPreset('preset-bar', {
foo: (exec: string[]) => exec.concat('bar'),
});
mockPreset('preset-got', [
'preset-dracarys',
{ name: 'preset-valar', options: { custom: 'morghulis' } },
]);
mockPreset('preset-dracarys', {
foo: (exec: string[]) => exec.concat('dracarys'),
});
mockPreset('preset-valar', {
foo: (exec: string[], options: any) => exec.concat(`valar ${options.custom}`),
});
const { getPresets } = jest.requireActual('./presets');
const presets = await getPresets(['preset-foo', 'preset-got', 'preset-bar'], {});
const result = await presets.apply('foo', []);
expect(result).toEqual(['foo', 'dracarys', 'valar morghulis', 'bar']);
});
it('loads and applies presets when they are declared as a string', async () => {
const mockPresetFooExtendWebpack = jest.fn();
const mockPresetBarExtendBabel = jest.fn();
mockPreset('preset-foo', {
webpack: mockPresetFooExtendWebpack,
});
mockPreset('preset-bar', {
babel: mockPresetBarExtendBabel,
});
const { getPresets } = jest.requireActual('./presets');
const presets = wrapPreset(await getPresets(['preset-foo', 'preset-bar'], {}));
async function testPresets() {
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
expect(mockPresetFooExtendWebpack).toHaveBeenCalled();
expect(mockPresetBarExtendBabel).toHaveBeenCalled();
});
it('loads and applies presets when they are declared as an object without props', async () => {
const mockPresetFooExtendWebpack = jest.fn();
const mockPresetBarExtendBabel = jest.fn();
mockPreset('preset-foo', {
webpack: mockPresetFooExtendWebpack,
});
mockPreset('preset-bar', {
babel: mockPresetBarExtendBabel,
});
const { getPresets } = jest.requireActual('./presets');
const presets = wrapPreset(
await getPresets([{ name: 'preset-foo' }, { name: 'preset-bar' }], {})
);
async function testPresets() {
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
expect(mockPresetFooExtendWebpack).toHaveBeenCalled();
expect(mockPresetBarExtendBabel).toHaveBeenCalled();
});
it('loads and applies presets when they are declared as an object with props', async () => {
const mockPresetFooExtendWebpack = jest.fn();
const mockPresetBarExtendBabel = jest.fn();
mockPreset('preset-foo', {
webpack: mockPresetFooExtendWebpack,
});
mockPreset('preset-bar', {
babel: mockPresetBarExtendBabel,
});
const { getPresets } = jest.requireActual('./presets');
const presets = wrapPreset(
await getPresets(
[
{ name: 'preset-foo', options: { foo: 1 } },
{ name: 'preset-bar', options: { bar: 'a' } },
],
{}
)
);
async function testPresets() {
await presets.webpack({});
await presets.babel({});
}
await expect(testPresets()).resolves.toBeUndefined();
expect(mockPresetFooExtendWebpack).toHaveBeenCalledWith(expect.anything(), {
foo: 1,
presetsList: expect.anything(),
presets: expect.anything(),
});
expect(mockPresetBarExtendBabel).toHaveBeenCalledWith(expect.anything(), {
bar: 'a',
presetsList: expect.anything(),
presets: expect.anything(),
});
});
it('loads and applies presets when they are declared as a string and as an object', async () => {
const mockPresetFooExtendWebpack = jest.fn();
const mockPresetBarExtendBabel = jest.fn();
mockPreset('preset-foo', {
webpack: mockPresetFooExtendWebpack,
});
mockPreset('preset-bar', {
babel: mockPresetBarExtendBabel,
});
const { getPresets } = jest.requireActual('./presets');
const presets = wrapPreset(
await getPresets(
[
'preset-foo',
{
name: 'preset-bar',
options: {
bar: 'a',
},
},
],
{}
)
);
async function testPresets() {
await presets.webpack({});
await presets.babel({});
}
await expect(testPresets()).resolves.toBeUndefined();
expect(mockPresetFooExtendWebpack).toHaveBeenCalled();
expect(mockPresetBarExtendBabel).toHaveBeenCalledWith(expect.anything(), {
bar: 'a',
presetsList: expect.arrayContaining([
expect.objectContaining({ name: 'preset-foo' }),
expect.objectContaining({ name: 'preset-bar' }),
]),
presets: expect.anything(),
});
});
it('applies presets in chain', async () => {
const mockPresetFooExtendWebpack = jest.fn((...args: any[]) => ({}));
const mockPresetBarExtendWebpack = jest.fn((...args: any[]) => ({}));
mockPreset('preset-foo', {
webpack: mockPresetFooExtendWebpack,
});
mockPreset('preset-bar', {
webpack: mockPresetBarExtendWebpack,
});
const { getPresets } = jest.requireActual('./presets');
const presets = wrapPreset(
await getPresets(
[
'preset-foo',
{
name: 'preset-bar',
options: {
bar: 'a',
presetsList: expect.arrayContaining([
expect.objectContaining({ name: 'preset-foo' }),
expect.objectContaining({ name: 'preset-bar' }),
]),
presets: expect.anything(),
},
},
],
{}
)
);
async function testPresets() {
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
expect(mockPresetFooExtendWebpack).toHaveBeenCalled();
expect(mockPresetBarExtendWebpack).toHaveBeenCalledWith(expect.anything(), {
bar: 'a',
presetsList: expect.arrayContaining([
expect.objectContaining({ name: 'preset-foo' }),
expect.objectContaining({ name: 'preset-bar' }),
]),
presets: expect.anything(),
});
});
it('allows for presets to export presets array', async () => {
const { getPresets } = jest.requireActual('./presets');
const input = {};
const mockPresetBar = jest.fn((...args: any[]) => input);
mockPreset('preset-foo', {
presets: ['preset-bar'],
});
mockPreset('preset-bar', {
bar: mockPresetBar,
});
const presets = await getPresets(['preset-foo'], {});
const output = await presets.apply('bar');
expect(mockPresetBar).toHaveBeenCalledWith(undefined, expect.any(Object));
expect(input).toBe(output);
});
it('allows for presets to export presets fn', async () => {
const { getPresets } = jest.requireActual('./presets');
const input = {};
const storybookOptions = { a: 1 };
const presetOptions = { b: 2 };
const mockPresetBar = jest.fn((...args: any[]) => input);
const mockPresetFoo = jest.fn((...args: any[]) => ['preset-bar']);
mockPreset('preset-foo', {
presets: mockPresetFoo,
});
mockPreset('preset-bar', {
bar: mockPresetBar,
});
const presets = await getPresets([{ name: 'preset-foo', options: { b: 2 } }], storybookOptions);
const output = await presets.apply('bar');
expect(mockPresetFoo).toHaveBeenCalledWith({ ...storybookOptions, ...presetOptions });
expect(mockPresetBar).toHaveBeenCalledWith(undefined, expect.any(Object));
expect(input).toBe(output);
});
afterEach(() => {
jest.resetModules();
});
});
describe('resolveAddonName', () => {
const { resolveAddonName } = jest.requireActual('./presets');
it('should resolve packages with metadata (relative path)', () => {
mockPreset('./local/preset', {
presets: [],
});
expect(resolveAddonName({}, './local/preset')).toEqual({
name: './local/preset',
type: 'presets',
});
});
it('should resolve packages with metadata (absolute path)', () => {
mockPreset('/absolute/preset', {
presets: [],
});
expect(resolveAddonName({}, '/absolute/preset')).toEqual({
name: '/absolute/preset',
type: 'presets',
});
});
it('should resolve packages without metadata', () => {
expect(resolveAddonName({}, '@storybook/preset-create-react-app')).toEqual({
name: '@storybook/preset-create-react-app',
type: 'presets',
});
});
it('should resolve managerEntries', () => {
expect(resolveAddonName({}, '@storybook/addon-actions/register')).toEqual({
name: '@storybook/addon-actions/register',
managerEntries: [path.normalize('@storybook/addon-actions/register')],
type: 'virtual',
});
});
it('should resolve managerEntries from new /manager path', () => {
expect(resolveAddonName({}, '@storybook/addon-actions/manager')).toEqual({
name: '@storybook/addon-actions/manager',
managerEntries: [path.normalize('@storybook/addon-actions/manager')],
type: 'virtual',
});
});
it('should resolve presets', () => {
expect(resolveAddonName({}, '@storybook/addon-docs/preset')).toEqual({
name: '@storybook/addon-docs/preset',
type: 'presets',
});
});
it('should resolve preset packages', () => {
expect(resolveAddonName({}, '@storybook/addon-essentials')).toEqual({
name: '@storybook/addon-essentials',
type: 'presets',
});
});
it('should error on invalid inputs', () => {
expect(() => resolveAddonName({}, null)).toThrow();
});
});
describe('loadPreset', () => {
mockPreset('@storybook/react', {});
mockPreset('@storybook/preset-typescript', {});
mockPreset('@storybook/addon-docs/preset', {});
mockPreset('@storybook/addon-actions/register', {});
mockPreset('addon-foo/register.js', {});
mockPreset('@storybook/addon-cool', {});
mockPreset('@storybook/addon-interactions/preset', {});
mockPreset('addon-bar', {
addons: ['@storybook/addon-cool'],
presets: ['@storybook/addon-interactions/preset'],
});
mockPreset('addon-baz/register.js', {});
mockPreset('@storybook/addon-notes/register-panel', {});
const { loadPreset } = jest.requireActual('./presets');
beforeEach(() => {
jest.spyOn(logger, 'warn');
});
it('should prepend framework field to list of presets', async () => {
const loaded = await loadPreset(
{
name: '',
type: 'virtual',
framework: '@storybook/react',
presets: ['@storybook/preset-typescript'],
addons: ['@storybook/addon-docs/preset'],
},
0,
{}
);
expect(loaded).toMatchInlineSnapshot(`
Array [
Object {
"name": "@storybook/preset-typescript",
"options": Object {},
"preset": Object {},
},
Object {
"name": "@storybook/addon-docs/preset",
"options": Object {},
"preset": Object {},
},
Object {
"name": Object {
"addons": Array [
"@storybook/addon-docs/preset",
],
"framework": "@storybook/react",
"name": "",
"presets": Array [
"@storybook/preset-typescript",
],
"type": "virtual",
},
"options": Object {},
"preset": Object {
"framework": "@storybook/react",
},
},
]
`);
});
it('should resolve all addons & presets in correct order', async () => {
const loaded = await loadPreset(
{
name: '',
type: 'virtual',
presets: ['@storybook/preset-typescript'],
addons: [
'@storybook/addon-docs/preset',
'@storybook/addon-actions/register',
'addon-foo/register.js',
'addon-bar',
'addon-baz/register.js',
'@storybook/addon-notes/register-panel',
],
},
0,
{}
);
expect(loaded).toEqual([
{
name: '@storybook/preset-typescript',
options: {},
preset: {},
},
{
name: '@storybook/addon-docs/preset',
options: {},
preset: {},
},
{
name: '@storybook/addon-actions/register',
options: {},
preset: {
managerEntries: [path.normalize('@storybook/addon-actions/register')],
},
},
{
name: 'addon-foo/register.js',
options: {},
preset: {
managerEntries: [path.normalize('addon-foo/register')],
},
},
{
name: '@storybook/addon-interactions/preset',
options: {},
preset: {},
},
{
name: '@storybook/addon-cool',
options: {},
preset: {},
},
{
name: 'addon-bar',
options: {},
preset: {},
},
{
name: 'addon-baz/register.js',
options: {},
preset: {
managerEntries: [path.normalize('addon-baz/register')],
},
},
{
name: '@storybook/addon-notes/register-panel',
options: {},
preset: {
managerEntries: [path.normalize('@storybook/addon-notes/register-panel')],
},
},
{
name: {
presets: ['@storybook/preset-typescript'],
addons: [
'@storybook/addon-docs/preset',
'@storybook/addon-actions/register',
'addon-foo/register.js',
'addon-bar',
'addon-baz/register.js',
'@storybook/addon-notes/register-panel',
],
name: '',
type: 'virtual',
},
options: {},
preset: {},
},
]);
});
it('should warn for addons that are not installed', async () => {
const loaded = await loadPreset(
{
name: '',
type: 'virtual',
framework: '@storybook/react',
presets: ['@storybook/preset-typescript'],
addons: ['@storybook/addon-docs/preset', 'uninstalled-addon'],
},
0,
{}
);
expect(logger.warn).toHaveBeenCalledWith(
'Could not resolve addon "uninstalled-addon", skipping. Is it installed?'
);
expect(loaded).toMatchInlineSnapshot(`
Array [
Object {
"name": "@storybook/preset-typescript",
"options": Object {},
"preset": Object {},
},
Object {
"name": "@storybook/addon-docs/preset",
"options": Object {},
"preset": Object {},
},
Object {
"name": Object {
"addons": Array [
"@storybook/addon-docs/preset",
"uninstalled-addon",
],
"framework": "@storybook/react",
"name": "",
"presets": Array [
"@storybook/preset-typescript",
],
"type": "virtual",
},
"options": Object {},
"preset": Object {
"framework": "@storybook/react",
},
},
]
`);
});
it('should filter out disabledAddons', async () => {
const loaded = await loadPreset(
{
name: '',
type: 'virtual',
framework: '@storybook/react',
presets: ['@storybook/preset-typescript'],
addons: ['@storybook/addon-docs', 'addon-bar'],
},
0,
{
build: {
test: {
disabledAddons: ['@storybook/addon-docs'],
},
},
}
);
// addon-docs should not be at the top level, but addon-bar and others should be.
expect(loaded).toMatchInlineSnapshot(`
Array [
Object {
"name": "@storybook/preset-typescript",
"options": Object {},
"preset": Object {},
},
Object {
"name": "@storybook/addon-interactions/preset",
"options": Object {},
"preset": Object {},
},
Object {
"name": "@storybook/addon-cool",
"options": Object {},
"preset": Object {},
},
Object {
"name": "addon-bar",
"options": Object {},
"preset": Object {},
},
Object {
"name": Object {
"addons": Array [
"@storybook/addon-docs",
"addon-bar",
],
"framework": "@storybook/react",
"name": "",
"presets": Array [
"@storybook/preset-typescript",
],
"type": "virtual",
},
"options": Object {},
"preset": Object {
"framework": "@storybook/react",
},
},
]
`);
});
});
|
751 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-common/src | petrpan-code/storybookjs/storybook/code/lib/core-common/src/utils/get-storybook-configuration.test.ts | import { getStorybookConfiguration } from './get-storybook-configuration';
describe('getStorybookConfiguration', () => {
it('handles short names', () => {
const port = getStorybookConfiguration('start-storybook -p 9001', '-p', '--port');
expect(port).toBe('9001');
});
it('handles long names', () => {
const port = getStorybookConfiguration('start-storybook --port 9001', '-p', '--port');
expect(port).toBe('9001');
});
it('handles equals', () => {
const port = getStorybookConfiguration('start-storybook --port=9001', '-p', '--port');
expect(port).toBe('9001');
});
it('handles double space', () => {
const port = getStorybookConfiguration('start-storybook --port 9001', '-p', '--port');
expect(port).toBe('9001');
});
it('handles complex scripts', () => {
const port = getStorybookConfiguration(
"node verify-node-version.js && concurrently --raw --kill-others 'yarn relay --watch' 'start-storybook -s ./public -p 9001'",
'-p',
'--port'
);
expect(port).toBe('9001');
});
});
|
776 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-common/src | petrpan-code/storybookjs/storybook/code/lib/core-common/src/utils/validate-config.test.ts | import { validateFrameworkName } from './validate-config';
describe('validateFrameworkName', () => {
afterEach(jest.resetAllMocks);
it('should throw if name is undefined', () => {
expect(() => validateFrameworkName(undefined)).toThrow();
});
it('should throw if name is a renderer', () => {
expect(() => validateFrameworkName('react')).toThrow();
expect(() => validateFrameworkName('@storybook/react')).toThrow();
});
it('should not throw if framework is a known framework', () => {
expect(() => validateFrameworkName('@storybook/react-vite')).not.toThrow();
});
it('should not throw if framework is unknown (community) but can be resolved', () => {
// mock require.resolve to return a value
jest.spyOn(require, 'resolve').mockReturnValue('some-community-framework');
expect(() => validateFrameworkName('some-community-framework')).toThrow();
});
it('should throw if framework is unknown and cannot be resolved', () => {
// mock require.resolve to fail
jest.spyOn(require, 'resolve').mockImplementation(() => {
throw new Error('Cannot resolve');
});
expect(() => validateFrameworkName('foo')).toThrow();
});
});
|
779 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-common/src/utils | petrpan-code/storybookjs/storybook/code/lib/core-common/src/utils/__tests__/check-addon-order.test.ts | import { logger } from '@storybook/node-logger';
import type {
CoreCommon_AddonEntry,
CoreCommon_AddonInfo,
CoreCommon_OptionsEntry,
} from '@storybook/types';
import { checkAddonOrder } from '../check-addon-order';
const configFile = './main.js';
const essentialAddons = [
'docs',
'controls',
'actions',
'backgrounds',
'viewport',
'toolbars',
'measure',
'outline',
];
const pkgName = (entry: CoreCommon_AddonEntry): string => {
if (typeof entry === 'string') {
if (entry.includes('node_modules')) return entry;
return `@storybook/addon-${entry}`;
}
return (entry as CoreCommon_OptionsEntry).name;
};
const fromName = (name: string): CoreCommon_AddonInfo => ({
name: pkgName(name),
inEssentials: essentialAddons.includes(name),
});
const str = (name: unknown) => JSON.stringify(name);
const warn = jest.spyOn(logger, 'warn');
afterEach(() => warn.mockReset());
describe.each([
['docs', 'controls', ['docs', 'controls']],
['docs', 'controls', ['docs', 'foo/node_modules/@storybook/addon-controls']],
['docs', 'controls', [{ name: '@storybook/addon-docs' }, 'controls']],
['docs', 'controls', ['essentials', 'controls']],
['docs', 'controls', ['essentials']],
])('checkAddonOrder', (_before, _after, _addons) => {
it(`${str(_before)} before ${str(_after)} in [${_addons.map(str).join(', ')}]`, async () => {
const before = fromName(_before);
const after = fromName(_after);
const addons = _addons.map(pkgName);
await checkAddonOrder({ before, after, configFile, getConfig: () => ({ addons }) });
expect(warn).not.toHaveBeenCalled();
});
});
describe.each([
['docs', 'controls', []],
['docs', 'controls', ['controls']],
['docs', 'controls', ['docs']],
['docs', 'controls', ['controls', 'docs']],
['docs', 'controls', ['essentials', 'docs']],
['docs', 'controls', ['controls', 'essentials']],
['docs', 'controls', ['essentials', 'controls', 'docs']],
])('checkAddonOrder', (_before, _after, _addons) => {
it(`${str(_before)} not before ${str(_after)} in [${_addons.map(str).join(', ')}]`, async () => {
const before = fromName(_before);
const after = fromName(_after);
const addons = _addons.map(pkgName);
await checkAddonOrder({ before, after, configFile, getConfig: () => ({ addons }) });
expect(warn).toHaveBeenCalledWith(
expect.stringMatching(
new RegExp(`Expected '${before.name}' .* to be listed before '${after.name}'`)
)
);
});
});
|
780 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-common/src/utils | petrpan-code/storybookjs/storybook/code/lib/core-common/src/utils/__tests__/interpret-files.test.ts | import mock from 'mock-fs';
import { getInterpretedFile } from '../interpret-files';
describe('interpret-files', () => {
it('will interpret file as file.ts when it exists in fs', () => {
mock({
'path/to/file.ts': 'ts file contents',
});
const file = getInterpretedFile('path/to/file');
expect(file).toEqual('path/to/file.ts');
});
it('will interpret file as file.js when both are in fs', () => {
mock({
'path/to/file.js': 'js file contents',
'path/to/file.ts': 'ts file contents',
});
const file = getInterpretedFile('path/to/file');
expect(file).toEqual('path/to/file.js');
});
it('will interpret file even if extension is already present', () => {
mock({
'path/to/file.js': 'js file contents',
'path/to/file.ts': 'ts file contents',
});
const file = getInterpretedFile('path/to/file.js');
expect(file).toEqual('path/to/file.js');
});
it('will return undefined if there is no candidate of a file in fs', () => {
mock({
'path/to/file.js': 'js file contents',
});
const file = getInterpretedFile('path/to/file2');
expect(file).toBeUndefined();
});
it('will interpret file as file.mts when it exists in fs', () => {
mock({
'path/to/file.mts': 'ts file contents',
});
const file = getInterpretedFile('path/to/file');
expect(file).toEqual('path/to/file.mts');
});
it('will interpret file as file.cts when it exists in fs', () => {
mock({
'path/to/file.cts': 'ts file contents',
});
const file = getInterpretedFile('path/to/file');
expect(file).toEqual('path/to/file.cts');
});
afterEach(mock.restore);
});
|
781 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-common/src/utils | petrpan-code/storybookjs/storybook/code/lib/core-common/src/utils/__tests__/normalize-stories.test.ts | // eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="../../test-typings.d.ts" />
import { dedent } from 'ts-dedent';
import { sep } from 'path';
import { InvalidStoriesEntryError } from '@storybook/core-events/server-errors';
import {
getDirectoryFromWorkingDir,
normalizeStories,
normalizeStoriesEntry,
} from '../normalize-stories';
expect.addSnapshotSerializer({
print: (val: any) => JSON.stringify(val, null, 2),
test: (val) => typeof val !== 'string',
});
expect.extend({
toMatchPaths(regex: RegExp, paths: string[]) {
const matched = paths.map((p) => !!p.match(regex));
const pass = matched.every(Boolean);
const failures = paths.filter((_, i) => (pass ? matched[i] : !matched[i]));
const message = () => dedent`Expected ${regex} to ${pass ? 'not ' : ''}match all strings.
Failures:${['', ...failures].join('\n - ')}`;
return {
pass,
message,
};
},
});
jest.mock('fs', () => {
const mockStat = (
path: string,
options: Record<string, any>,
cb: (error?: Error, stats?: Record<string, any>) => void
) => {
cb(undefined, {
isDirectory: () => !path.match(/\.[a-z]+$/),
});
};
return {
access: (path: string, mode: number, cb: (err?: Error) => void): void => undefined,
lstatSync: (path: string) => ({
isDirectory: () => !path.match(/\.[a-z]+$/),
}),
stat: mockStat,
lstat: mockStat,
};
});
const options = {
configDir: '/path/to/project/.storybook',
workingDir: '/path/to/project',
};
describe('normalizeStoriesEntry', () => {
it('direct file path', () => {
const specifier = normalizeStoriesEntry('../path/to/file.stories.mdx', options);
expect(specifier).toMatchInlineSnapshot(`
{
"titlePrefix": "",
"directory": "./path/to",
"files": "file.stories.mdx",
"importPathMatcher": {}
}
`);
expect(specifier.importPathMatcher).toMatchPaths(['./path/to/file.stories.mdx']);
expect(specifier.importPathMatcher).not.toMatchPaths([
'./path/to/file.stories.js',
'./file.stories.mdx',
'../file.stories.mdx',
]);
});
it('story in config dir', () => {
const specifier = normalizeStoriesEntry('./file.stories.mdx', options);
expect(specifier).toMatchInlineSnapshot(`
{
"titlePrefix": "",
"directory": "./.storybook",
"files": "file.stories.mdx",
"importPathMatcher": {}
}
`);
expect(specifier.importPathMatcher).toMatchPaths(['./.storybook/file.stories.mdx']);
expect(specifier.importPathMatcher).not.toMatchPaths([
'.storybook/file.stories.mdx',
'./file.stories.mdx',
'../file.stories.mdx',
]);
});
it('non-recursive files glob', () => {
const specifier = normalizeStoriesEntry('../*/*.stories.mdx', options);
expect(specifier).toMatchInlineSnapshot(`
{
"titlePrefix": "",
"directory": ".",
"files": "*/*.stories.mdx",
"importPathMatcher": {}
}
`);
expect(specifier.importPathMatcher).toMatchPaths([
'./path/file.stories.mdx',
'./second-path/file.stories.mdx',
]);
expect(specifier.importPathMatcher).not.toMatchPaths([
'./path/file.stories.js',
'./path/to/file.stories.mdx',
'./file.stories.mdx',
'../file.stories.mdx',
]);
});
it('double non-recursive directory/files glob', () => {
const specifier = normalizeStoriesEntry('../*/*/*.stories.mdx', options);
expect(specifier).toMatchInlineSnapshot(`
{
"titlePrefix": "",
"directory": ".",
"files": "*/*/*.stories.mdx",
"importPathMatcher": {}
}
`);
expect(specifier.importPathMatcher).toMatchPaths([
'./path/to/file.stories.mdx',
'./second-path/to/file.stories.mdx',
]);
expect(specifier.importPathMatcher).not.toMatchPaths([
'./file.stories.mdx',
'./path/file.stories.mdx',
'./path/to/third/file.stories.mdx',
'./path/to/file.stories.js',
'../file.stories.mdx',
]);
});
it('directory/files glob', () => {
const specifier = normalizeStoriesEntry('../**/*.stories.mdx', options);
expect(specifier).toMatchInlineSnapshot(`
{
"titlePrefix": "",
"directory": ".",
"files": "**/*.stories.mdx",
"importPathMatcher": {}
}
`);
expect(specifier.importPathMatcher).toMatchPaths([
'./file.stories.mdx',
'./path/file.stories.mdx',
'./path/to/file.stories.mdx',
'./path/to/third/file.stories.mdx',
]);
expect(specifier.importPathMatcher).not.toMatchPaths([
'./file.stories.js',
'../file.stories.mdx',
]);
});
it('double stars glob', () => {
const specifier = normalizeStoriesEntry('../**/foo/**/*.stories.mdx', options);
expect(specifier).toMatchInlineSnapshot(`
{
"titlePrefix": "",
"directory": ".",
"files": "**/foo/**/*.stories.mdx",
"importPathMatcher": {}
}
`);
expect(specifier.importPathMatcher).toMatchPaths([
'./foo/file.stories.mdx',
'./path/to/foo/file.stories.mdx',
'./path/to/foo/third/fourth/file.stories.mdx',
]);
expect(specifier.importPathMatcher).not.toMatchPaths([
'./file.stories.mdx',
'./file.stories.js',
'../file.stories.mdx',
]);
});
it('intermediate directory glob', () => {
const specifier = normalizeStoriesEntry('../**/foo/*.stories.mdx', options);
expect(specifier).toMatchInlineSnapshot(`
{
"titlePrefix": "",
"directory": ".",
"files": "**/foo/*.stories.mdx",
"importPathMatcher": {}
}
`);
expect(specifier.importPathMatcher).toMatchPaths([
'./path/to/foo/file.stories.mdx',
'./foo/file.stories.mdx',
]);
expect(specifier.importPathMatcher).not.toMatchPaths([
'./file.stories.mdx',
'./file.stories.js',
'./path/to/foo/third/fourth/file.stories.mdx',
'../file.stories.mdx',
]);
});
it('directory outside of working dir', () => {
const specifier = normalizeStoriesEntry('../../src/*.stories.mdx', options);
expect(specifier).toMatchInlineSnapshot(`
{
"titlePrefix": "",
"directory": "../src",
"files": "*.stories.mdx",
"importPathMatcher": {}
}
`);
expect(specifier.importPathMatcher).toMatchPaths(['../src/file.stories.mdx']);
expect(specifier.importPathMatcher).not.toMatchPaths([
'./src/file.stories.mdx',
'../src/file.stories.js',
]);
});
it('directory', () => {
const specifier = normalizeStoriesEntry('..', options);
expect(specifier).toMatchInlineSnapshot(`
{
"titlePrefix": "",
"directory": ".",
"files": "**/*.@(mdx|stories.@(js|jsx|mjs|ts|tsx))",
"importPathMatcher": {}
}
`);
});
it('directory specifier', () => {
const specifier = normalizeStoriesEntry({ directory: '..' }, options);
expect(specifier).toMatchInlineSnapshot(`
{
"titlePrefix": "",
"files": "**/*.@(mdx|stories.@(js|jsx|mjs|ts|tsx))",
"directory": ".",
"importPathMatcher": {}
}
`);
});
it('directory/files specifier', () => {
const specifier = normalizeStoriesEntry({ directory: '..', files: '*.stories.mdx' }, options);
expect(specifier).toMatchInlineSnapshot(`
{
"titlePrefix": "",
"files": "*.stories.mdx",
"directory": ".",
"importPathMatcher": {}
}
`);
});
it('directory/titlePrefix specifier', () => {
const specifier = normalizeStoriesEntry({ directory: '..', titlePrefix: 'atoms' }, options);
expect(specifier).toMatchInlineSnapshot(`
{
"titlePrefix": "atoms",
"files": "**/*.@(mdx|stories.@(js|jsx|mjs|ts|tsx))",
"directory": ".",
"importPathMatcher": {}
}
`);
});
it('directory/titlePrefix/files specifier', () => {
const specifier = normalizeStoriesEntry(
{ directory: '..', titlePrefix: 'atoms', files: '*.stories.mdx' },
options
);
expect(specifier).toMatchInlineSnapshot(`
{
"titlePrefix": "atoms",
"files": "*.stories.mdx",
"directory": ".",
"importPathMatcher": {}
}
`);
});
it('globs with negation', () => {
const specifier = normalizeStoriesEntry('../!(negation)/*.stories.mdx', options);
expect(specifier).toMatchInlineSnapshot(`
{
"titlePrefix": "",
"directory": ".",
"files": "!(negation)/*.stories.mdx",
"importPathMatcher": {}
}
`);
expect(specifier.importPathMatcher).toMatchPaths([
'./path/file.stories.mdx',
'./second-path/file.stories.mdx',
]);
expect(specifier.importPathMatcher).not.toMatchPaths([
'./path/file.stories.js',
'./path/to/file.stories.mdx',
'./file.stories.mdx',
'../file.stories.mdx',
]);
});
});
describe('getDirectoryFromWorkingDir', () => {
it('should return normalized story path', () => {
const normalizedPath = getDirectoryFromWorkingDir({
configDir: '/path/to/project/.storybook',
workingDir: '/path/to/project',
directory: '/path/to/project/src',
});
expect(normalizedPath).toBe(`.${sep}src`);
});
});
describe('normalizeStories', () => {
it('should throw InvalidStoriesEntryError for empty entries', () => {
expect(() => normalizeStories([], options)).toThrow(InvalidStoriesEntryError);
});
});
|
782 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-common/src/utils | petrpan-code/storybookjs/storybook/code/lib/core-common/src/utils/__tests__/paths.test.ts | import path from 'path';
import findUp from 'find-up';
import slash from 'slash';
import { normalizeStoryPath, getProjectRoot } from '../paths';
jest.mock('find-up');
describe('paths - normalizeStoryPath()', () => {
it('returns a path starting with "./" unchanged', () => {
const filename = `.${path.sep}${path.join('src', 'Comp.story.js')}`;
expect(normalizeStoryPath(filename)).toEqual(filename);
});
it('returns a path starting with "../" unchanged', () => {
const filename = path.join('..', 'src', 'Comp.story.js');
expect(normalizeStoryPath(filename)).toEqual(filename);
});
it('returns a path equal to "." unchanged', () => {
const filename = '.';
expect(normalizeStoryPath(filename)).toEqual(filename);
});
it('returns a path equal to ".." unchanged', () => {
const filename = '..';
expect(normalizeStoryPath(filename)).toEqual(filename);
});
it('adds "./" to a normalized relative path', () => {
const filename = path.join('src', 'Comp.story.js');
expect(normalizeStoryPath(filename)).toEqual(`.${path.sep}${filename}`);
});
it('adds "./" to a hidden folder', () => {
const filename = path.join('.storybook', 'Comp.story.js');
expect(normalizeStoryPath(filename)).toEqual(`.${path.sep}${filename}`);
});
it('adds "./" to a hidden file', () => {
const filename = `.Comp.story.js`;
expect(normalizeStoryPath(filename)).toEqual(`.${path.sep}${filename}`);
});
});
describe('getProjectRoot', () => {
const mockedFindUp = findUp as jest.Mocked<typeof findUp>;
it('should return the root directory containing a .git directory', () => {
mockedFindUp.sync.mockImplementation((name) =>
name === ('.git' as any) ? '/path/to/root' : undefined
);
expect(slash(getProjectRoot())).toBe('/path/to');
});
it('should return the root directory containing a .svn directory if there is no .git directory', () => {
mockedFindUp.sync.mockImplementation((name) =>
name === ('.svn' as any) ? '/path/to/root' : undefined
);
expect(slash(getProjectRoot())).toBe('/path/to');
});
it('should return the root directory containing a .yarn directory if there is no .git or .svn directory', () => {
mockedFindUp.sync.mockImplementation((name) =>
name === ('.yarn' as any) ? '/path/to/root' : undefined
);
expect(slash(getProjectRoot())).toBe('/path/to');
});
});
|
783 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-common/src/utils | petrpan-code/storybookjs/storybook/code/lib/core-common/src/utils/__tests__/template.test.ts | import mock from 'mock-fs';
import { getPreviewHeadTemplate, getPreviewBodyTemplate } from '../template';
const HEAD_HTML_CONTENTS = '<script>console.log("custom script!");</script>';
const BASE_HTML_CONTENTS = '<script>console.log("base script!");</script>';
const BASE_BODY_HTML_CONTENTS = '<div>story contents</div>';
const BODY_HTML_CONTENTS = '<div>custom body contents</div>';
describe('server.getPreviewHeadHtml', () => {
describe('when .storybook/preview-head.html does not exist', () => {
beforeEach(() => {
mock({
[`undefined/templates/base-preview-head.html`]: BASE_HTML_CONTENTS,
config: {},
});
});
afterEach(() => {
mock.restore();
});
it('return an empty string', () => {
const result = getPreviewHeadTemplate('./config');
expect(result).toEqual(BASE_HTML_CONTENTS);
});
});
describe('when .storybook/preview-head.html exists', () => {
beforeEach(() => {
mock({
[`undefined/templates/base-preview-head.html`]: BASE_HTML_CONTENTS,
config: {
'preview-head.html': HEAD_HTML_CONTENTS,
},
});
});
afterEach(() => {
mock.restore();
});
it('return the contents of the file', () => {
const result = getPreviewHeadTemplate('./config');
expect(result).toEqual(BASE_HTML_CONTENTS + HEAD_HTML_CONTENTS);
});
});
});
describe('server.getPreviewBodyHtml', () => {
describe('when .storybook/preview-body.html does not exist', () => {
beforeEach(() => {
mock({
[`undefined/templates/base-preview-body.html`]: BASE_BODY_HTML_CONTENTS,
config: {},
});
});
afterEach(() => {
mock.restore();
});
it('return an empty string', () => {
const result = getPreviewBodyTemplate('./config');
expect(result).toEqual(BASE_BODY_HTML_CONTENTS);
});
});
describe('when .storybook/preview-body.html exists', () => {
beforeEach(() => {
mock({
[`undefined/templates/base-preview-body.html`]: BASE_BODY_HTML_CONTENTS,
config: {
'preview-body.html': BODY_HTML_CONTENTS,
},
});
});
afterEach(() => {
mock.restore();
});
it('return the contents of the file', () => {
const result = getPreviewBodyTemplate('./config');
expect(result).toEqual(BODY_HTML_CONTENTS + BASE_BODY_HTML_CONTENTS);
});
});
});
|
793 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-events | petrpan-code/storybookjs/storybook/code/lib/core-events/src/index.test.ts | import * as EventsPackageExport from './index';
import EventsDefaultExport, { CHANNEL_CREATED } from './index';
describe('Core Events', () => {
it('Should export the module as a namespace', () => {
expect(EventsPackageExport.CHANNEL_CREATED).toBe('channelCreated');
});
it('Should export all values in the default export', () => {
expect(EventsDefaultExport.CHANNEL_CREATED).toBe('channelCreated');
});
it('Should export values as named exports', () => {
expect(CHANNEL_CREATED).toBe('channelCreated');
});
});
|
798 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-events/src | petrpan-code/storybookjs/storybook/code/lib/core-events/src/errors/server-errors.test.ts | /* eslint-disable local-rules/no-uncategorized-errors */
import { WebpackCompilationError } from './server-errors';
describe('WebpackCompilationError', () => {
it('should correctly handle error with stats.compilation.errors', () => {
const errors = [
new Error('Error 1 \u001B[4mmessage\u001B[0m'),
new Error('\u001B[4mError\u001B[0m 2 message'),
];
const webpackError = new WebpackCompilationError({ errors });
expect(webpackError.data.errors[0].message).toEqual('Error 1 message');
expect(webpackError.data.errors[1].message).toEqual('Error 2 message');
});
});
|
800 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-events/src | petrpan-code/storybookjs/storybook/code/lib/core-events/src/errors/storybook-error.test.ts | import { StorybookError } from './storybook-error';
describe('StorybookError', () => {
class TestError extends StorybookError {
category = 'TEST_CATEGORY';
code = 123;
template() {
return 'This is a test error.';
}
}
it('should generate the correct error name', () => {
const error = new TestError();
expect(error.name).toBe('SB_TEST_CATEGORY_0123 (TestError)');
});
it('should generate the correct message without documentation link', () => {
const error = new TestError();
const expectedMessage = 'This is a test error.';
expect(error.message).toBe(expectedMessage);
});
it('should generate the correct message with internal documentation link', () => {
const error = new TestError();
error.documentation = true;
const expectedMessage =
'This is a test error.\n\nMore info: https://storybook.js.org/error/SB_TEST_CATEGORY_0123\n';
expect(error.message).toBe(expectedMessage);
});
it('should generate the correct message with external documentation link', () => {
const error = new TestError();
error.documentation = 'https://example.com/docs/test-error';
expect(error.message).toMatchInlineSnapshot(`
"This is a test error.
More info: https://example.com/docs/test-error
"
`);
});
it('should generate the correct message with multiple external documentation links', () => {
const error = new TestError();
error.documentation = [
'https://example.com/docs/first-error',
'https://example.com/docs/second-error',
];
expect(error.message).toMatchInlineSnapshot(`
"This is a test error.
More info:
- https://example.com/docs/first-error
- https://example.com/docs/second-error
"
`);
});
it('should have default documentation value of false', () => {
const error = new TestError();
expect(error.documentation).toBe(false);
});
});
|
815 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-server | petrpan-code/storybookjs/storybook/code/lib/core-server/src/withTelemetry.test.ts | /* eslint-disable local-rules/no-uncategorized-errors */
/// <reference types="@types/jest" />;
import prompts from 'prompts';
import { loadAllPresets, cache } from '@storybook/core-common';
import { telemetry, oneWayHash } from '@storybook/telemetry';
import { getErrorLevel, sendTelemetryError, withTelemetry } from './withTelemetry';
jest.mock('prompts');
jest.mock('@storybook/core-common');
jest.mock('@storybook/telemetry');
const cliOptions = {};
describe('withTelemetry', () => {
it('works in happy path', async () => {
const run = jest.fn();
await withTelemetry('dev', { cliOptions }, run);
expect(telemetry).toHaveBeenCalledTimes(1);
expect(telemetry).toHaveBeenCalledWith('boot', { eventType: 'dev' }, { stripMetadata: true });
});
it('does not send boot when cli option is passed', async () => {
const run = jest.fn();
await withTelemetry('dev', { cliOptions: { disableTelemetry: true } }, run);
expect(telemetry).toHaveBeenCalledTimes(0);
});
describe('when command fails', () => {
const error = new Error('An Error!');
const run = jest.fn(async () => {
throw error;
});
it('sends boot message', async () => {
await expect(async () =>
withTelemetry('dev', { cliOptions, printError: jest.fn() }, run)
).rejects.toThrow(error);
expect(telemetry).toHaveBeenCalledWith('boot', { eventType: 'dev' }, { stripMetadata: true });
});
it('does not send boot when cli option is passed', async () => {
await expect(async () =>
withTelemetry('dev', { cliOptions: { disableTelemetry: true }, printError: jest.fn() }, run)
).rejects.toThrow(error);
expect(telemetry).toHaveBeenCalledTimes(0);
});
it('sends error message when no options are passed', async () => {
await expect(async () =>
withTelemetry('dev', { cliOptions, printError: jest.fn() }, run)
).rejects.toThrow(error);
expect(telemetry).toHaveBeenCalledTimes(2);
expect(telemetry).toHaveBeenCalledWith(
'error',
expect.objectContaining({ eventType: 'dev', error }),
expect.objectContaining({})
);
});
it('does not send error message when cli opt out is passed', async () => {
await expect(async () =>
withTelemetry('dev', { cliOptions: { disableTelemetry: true }, printError: jest.fn() }, run)
).rejects.toThrow(error);
expect(telemetry).toHaveBeenCalledTimes(0);
expect(telemetry).not.toHaveBeenCalledWith(
'error',
expect.objectContaining({}),
expect.objectContaining({})
);
});
it('does not send full error message when crash reports are disabled', async () => {
jest.mocked(loadAllPresets).mockResolvedValueOnce({
apply: async () => ({ enableCrashReports: false } as any),
});
await expect(async () =>
withTelemetry(
'dev',
{ cliOptions: {} as any, presetOptions: {} as any, printError: jest.fn() },
run
)
).rejects.toThrow(error);
expect(telemetry).toHaveBeenCalledTimes(2);
expect(telemetry).toHaveBeenCalledWith(
'error',
expect.objectContaining({ eventType: 'dev' }),
expect.objectContaining({})
);
});
it('does send error message when crash reports are enabled', async () => {
jest.mocked(loadAllPresets).mockResolvedValueOnce({
apply: async () => ({ enableCrashReports: true } as any),
});
await expect(async () =>
withTelemetry(
'dev',
{ cliOptions: {} as any, presetOptions: {} as any, printError: jest.fn() },
run
)
).rejects.toThrow(error);
expect(telemetry).toHaveBeenCalledTimes(2);
expect(telemetry).toHaveBeenCalledWith(
'error',
expect.objectContaining({ eventType: 'dev', error }),
expect.objectContaining({})
);
});
it('does not send any error message when telemetry is disabled', async () => {
jest.mocked(loadAllPresets).mockResolvedValueOnce({
apply: async () => ({ disableTelemetry: true } as any),
});
await expect(async () =>
withTelemetry(
'dev',
{ cliOptions: {} as any, presetOptions: {} as any, printError: jest.fn() },
run
)
).rejects.toThrow(error);
expect(telemetry).toHaveBeenCalledTimes(1);
expect(telemetry).not.toHaveBeenCalledWith(
'error',
expect.objectContaining({}),
expect.objectContaining({})
);
});
it('does send error messages when telemetry is disabled, but crash reports are enabled', async () => {
jest.mocked(loadAllPresets).mockResolvedValueOnce({
apply: async () => ({ disableTelemetry: true, enableCrashReports: true } as any),
});
await expect(async () =>
withTelemetry(
'dev',
{ cliOptions: {} as any, presetOptions: {} as any, printError: jest.fn() },
run
)
).rejects.toThrow(error);
expect(telemetry).toHaveBeenCalledTimes(2);
expect(telemetry).toHaveBeenCalledWith(
'error',
expect.objectContaining({ eventType: 'dev', error }),
expect.objectContaining({})
);
});
it('does not send full error messages when disabled crash reports are cached', async () => {
jest.mocked(loadAllPresets).mockResolvedValueOnce({
apply: async () => ({} as any),
});
jest.mocked(cache.get).mockResolvedValueOnce(false);
await expect(async () =>
withTelemetry(
'dev',
{ cliOptions: {} as any, presetOptions: {} as any, printError: jest.fn() },
run
)
).rejects.toThrow(error);
expect(telemetry).toHaveBeenCalledTimes(2);
expect(telemetry).toHaveBeenCalledWith(
'error',
expect.objectContaining({ eventType: 'dev' }),
expect.objectContaining({})
);
});
it('does send error messages when enabled crash reports are cached', async () => {
jest.mocked(loadAllPresets).mockResolvedValueOnce({
apply: async () => ({} as any),
});
jest.mocked(cache.get).mockResolvedValueOnce(true);
await expect(async () =>
withTelemetry(
'dev',
{ cliOptions: {} as any, presetOptions: {} as any, printError: jest.fn() },
run
)
).rejects.toThrow(error);
expect(telemetry).toHaveBeenCalledTimes(2);
expect(telemetry).toHaveBeenCalledWith(
'error',
expect.objectContaining({ eventType: 'dev', error }),
expect.objectContaining({})
);
});
it('does not send full error messages when disabled crash reports are prompted', async () => {
jest.mocked(loadAllPresets).mockResolvedValueOnce({
apply: async () => ({} as any),
});
jest.mocked(cache.get).mockResolvedValueOnce(undefined);
jest.mocked(prompts).mockResolvedValueOnce({ enableCrashReports: false });
await expect(async () =>
withTelemetry(
'dev',
{ cliOptions: {} as any, presetOptions: {} as any, printError: jest.fn() },
run
)
).rejects.toThrow(error);
expect(telemetry).toHaveBeenCalledTimes(2);
expect(telemetry).toHaveBeenCalledWith(
'error',
expect.objectContaining({ eventType: 'dev' }),
expect.objectContaining({})
);
});
it('does send error messages when enabled crash reports are prompted', async () => {
jest.mocked(loadAllPresets).mockResolvedValueOnce({
apply: async () => ({} as any),
});
jest.mocked(cache.get).mockResolvedValueOnce(undefined);
jest.mocked(prompts).mockResolvedValueOnce({ enableCrashReports: true });
await expect(async () =>
withTelemetry(
'dev',
{ cliOptions: {} as any, presetOptions: {} as any, printError: jest.fn() },
run
)
).rejects.toThrow(error);
expect(telemetry).toHaveBeenCalledTimes(2);
expect(telemetry).toHaveBeenCalledWith(
'error',
expect.objectContaining({ eventType: 'dev', error }),
expect.objectContaining({})
);
});
// if main.js has errors, we have no way to tell if they've disabled error reporting,
// so we assume they have.
it('does not send full error messages when presets fail to evaluate', async () => {
jest.mocked(loadAllPresets).mockRejectedValueOnce(error);
await expect(async () =>
withTelemetry(
'dev',
{ cliOptions: {} as any, presetOptions: {} as any, printError: jest.fn() },
run
)
).rejects.toThrow(error);
expect(telemetry).toHaveBeenCalledTimes(2);
expect(telemetry).toHaveBeenCalledWith(
'error',
expect.objectContaining({ eventType: 'dev' }),
expect.objectContaining({})
);
});
});
});
describe('sendTelemetryError', () => {
it('handles error instances and sends telemetry', async () => {
const options: any = {
cliOptions: {},
skipPrompt: false,
};
const mockError = new Error('Test error');
const eventType: any = 'testEventType';
jest.mocked(oneWayHash).mockReturnValueOnce('some-hash');
await sendTelemetryError(mockError, eventType, options);
expect(telemetry).toHaveBeenCalledWith(
'error',
expect.objectContaining({
error: mockError,
eventType,
isErrorInstance: true,
errorHash: 'some-hash',
}),
expect.any(Object)
);
});
it('handles non-error instances and sends telemetry with no-message hash', async () => {
const options: any = {
cliOptions: {},
skipPrompt: false,
};
const mockError = { error: new Error('Test error') };
const eventType: any = 'testEventType';
await sendTelemetryError(mockError, eventType, options);
expect(telemetry).toHaveBeenCalledWith(
'error',
expect.objectContaining({
error: mockError,
eventType,
isErrorInstance: false,
errorHash: 'NO_MESSAGE',
}),
expect.any(Object)
);
});
it('handles error with empty message and sends telemetry with empty-message hash', async () => {
const options: any = {
cliOptions: {},
skipPrompt: false,
};
const mockError = new Error();
const eventType: any = 'testEventType';
await sendTelemetryError(mockError, eventType, options);
expect(telemetry).toHaveBeenCalledWith(
'error',
expect.objectContaining({
error: mockError,
eventType,
isErrorInstance: true,
errorHash: 'EMPTY_MESSAGE',
}),
expect.any(Object)
);
});
});
describe('getErrorLevel', () => {
beforeEach(() => {
jest.resetAllMocks();
});
it('returns "none" when cliOptions.disableTelemetry is true', async () => {
const options: any = {
cliOptions: {
disableTelemetry: true,
},
presetOptions: undefined,
skipPrompt: false,
};
const errorLevel = await getErrorLevel(options);
expect(errorLevel).toBe('none');
});
it('returns "full" when presetOptions is not provided', async () => {
const options: any = {
cliOptions: {
disableTelemetry: false,
},
presetOptions: undefined,
skipPrompt: false,
};
const errorLevel = await getErrorLevel(options);
expect(errorLevel).toBe('full');
});
it('returns "full" when core.enableCrashReports is true', async () => {
const options: any = {
cliOptions: {
disableTelemetry: false,
},
presetOptions: {},
skipPrompt: false,
};
jest.mocked(loadAllPresets).mockResolvedValueOnce({
apply: async () => ({ enableCrashReports: true } as any),
});
jest.mocked(cache.get).mockResolvedValueOnce(false);
const errorLevel = await getErrorLevel(options);
expect(errorLevel).toBe('full');
});
it('returns "error" when core.enableCrashReports is false', async () => {
const options: any = {
cliOptions: {
disableTelemetry: false,
},
presetOptions: {},
skipPrompt: false,
};
jest.mocked(loadAllPresets).mockResolvedValueOnce({
apply: async () => ({ enableCrashReports: false } as any),
});
jest.mocked(cache.get).mockResolvedValueOnce(false);
const errorLevel = await getErrorLevel(options);
expect(errorLevel).toBe('error');
});
it('returns "none" when core.disableTelemetry is true', async () => {
const options: any = {
cliOptions: {
disableTelemetry: false,
},
presetOptions: {},
skipPrompt: false,
};
jest.mocked(loadAllPresets).mockResolvedValueOnce({
apply: async () => ({ disableTelemetry: true } as any),
});
jest.mocked(cache.get).mockResolvedValueOnce(false);
const errorLevel = await getErrorLevel(options);
expect(errorLevel).toBe('none');
});
it('returns "full" if cache contains crashReports true', async () => {
const options: any = {
cliOptions: {
disableTelemetry: false,
},
presetOptions: {},
skipPrompt: false,
};
jest.mocked(cache.get).mockResolvedValueOnce(true);
jest.mocked(loadAllPresets).mockResolvedValueOnce({
apply: async () => ({} as any),
});
const errorLevel = await getErrorLevel(options);
expect(errorLevel).toBe('full');
});
it('returns "error" when skipPrompt is true', async () => {
const options: any = {
cliOptions: {
disableTelemetry: false,
},
presetOptions: {},
skipPrompt: true,
};
jest.mocked(loadAllPresets).mockResolvedValueOnce({
apply: async () => ({} as any),
});
jest.mocked(cache.get).mockResolvedValueOnce(undefined);
const errorLevel = await getErrorLevel(options);
expect(errorLevel).toBe('error');
});
});
|
829 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-server/src | petrpan-code/storybookjs/storybook/code/lib/core-server/src/presets/favicon.test.ts | /// <reference types="@types/jest" />;
import { join } from 'path';
import * as fs from 'fs-extra';
import { logger } from '@storybook/node-logger';
import * as m from './common-preset';
const defaultFavicon = require.resolve('@storybook/core-server/public/favicon.svg');
const createPath = (...p: string[]) => join(process.cwd(), ...p);
const createOptions = (locations: string[]): Parameters<typeof m.favicon>[1] => ({
configDir: '',
presets: {
apply: async (extension: string, config: any) => {
switch (extension) {
case 'staticDirs': {
return locations.map((location) => ({ from: location, to: '/' }));
}
default: {
return config as any;
}
}
},
},
});
jest.mock('fs-extra', () => {
return {
pathExists: jest.fn((p: string) => {
return false;
}),
existsSync: jest.fn((p: string) => {
return false;
}),
};
});
jest.mock('@storybook/node-logger', () => {
return {
logger: {
warn: jest.fn(() => {}),
},
};
});
const pathExists = fs.pathExists as jest.Mock;
test('with no staticDirs favicon should return default', async () => {
const options = createOptions([]);
expect(await m.favicon(undefined, options)).toBe(defaultFavicon);
});
test('with staticDirs containing a single favicon.ico should return the found favicon', async () => {
const location = 'static';
pathExists.mockImplementation((p: string) => {
if (p === createPath(location)) {
return true;
}
if (p === createPath(location, 'favicon.ico')) {
return true;
}
return false;
});
const options = createOptions([location]);
expect(await m.favicon(undefined, options)).toBe(createPath(location, 'favicon.ico'));
});
test('with staticDirs containing a single favicon.svg should return the found favicon', async () => {
const location = 'static';
pathExists.mockImplementation((p: string) => {
if (p === createPath(location)) {
return true;
}
if (p === createPath(location, 'favicon.svg')) {
return true;
}
return false;
});
const options = createOptions([location]);
expect(await m.favicon(undefined, options)).toBe(createPath(location, 'favicon.svg'));
});
test('with staticDirs containing a multiple favicons should return the first favicon and warn', async () => {
const location = 'static';
pathExists.mockImplementation((p: string) => {
if (p === createPath(location)) {
return true;
}
if (p === createPath(location, 'favicon.ico')) {
return true;
}
if (p === createPath(location, 'favicon.svg')) {
return true;
}
return false;
});
const options = createOptions([location]);
expect(await m.favicon(undefined, options)).toBe(createPath(location, 'favicon.svg'));
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('multiple favicons'));
});
test('with multiple staticDirs containing a multiple favicons should return the first favicon and warn', async () => {
const locationA = 'static-a';
const locationB = 'static-b';
pathExists.mockImplementation((p: string) => {
if (p === createPath(locationA)) {
return true;
}
if (p === createPath(locationB)) {
return true;
}
if (p === createPath(locationA, 'favicon.ico')) {
return true;
}
if (p === createPath(locationB, 'favicon.svg')) {
return true;
}
return false;
});
const options = createOptions([locationA, locationB]);
expect(await m.favicon(undefined, options)).toBe(createPath(locationA, 'favicon.ico'));
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('multiple favicons'));
});
|
831 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-server/src | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils/StoryIndexGenerator.deprecated.test.ts | /* eslint-disable @typescript-eslint/no-shadow */
/// <reference types="@types/jest" />;
/**
* @jest-environment node
*/
import path from 'path';
import fs from 'fs-extra';
import { normalizeStoriesEntry } from '@storybook/core-common';
import type { NormalizedStoriesSpecifier, StoryIndexEntry } from '@storybook/types';
import { loadCsf, getStorySortParameter } from '@storybook/csf-tools';
import { toId } from '@storybook/csf';
import { logger, once } from '@storybook/node-logger';
import type { StoryIndexGeneratorOptions } from './StoryIndexGenerator';
import { StoryIndexGenerator } from './StoryIndexGenerator';
jest.mock('@storybook/csf-tools');
jest.mock('@storybook/csf', () => {
const csf = jest.requireActual('@storybook/csf');
return {
...csf,
toId: jest.fn(csf.toId),
};
});
jest.mock('@storybook/node-logger');
const toIdMock = toId as jest.Mock<ReturnType<typeof toId>>;
const loadCsfMock = loadCsf as jest.Mock<ReturnType<typeof loadCsf>>;
const getStorySortParameterMock = getStorySortParameter as jest.Mock<
ReturnType<typeof getStorySortParameter>
>;
const csfIndexer = async (fileName: string, opts: any) => {
const code = (await fs.readFile(fileName, 'utf-8')).toString();
return loadCsf(code, { ...opts, fileName }).parse();
};
const storiesMdxIndexer = async (fileName: string, opts: any) => {
let code = (await fs.readFile(fileName, 'utf-8')).toString();
const { compile } = await import('@storybook/mdx2-csf');
code = await compile(code, {});
return loadCsf(code, { ...opts, fileName }).parse();
};
const options: StoryIndexGeneratorOptions = {
configDir: path.join(__dirname, '__mockdata__'),
workingDir: path.join(__dirname, '__mockdata__'),
storyIndexers: [
{ test: /\.stories\.mdx$/, indexer: storiesMdxIndexer },
{ test: /\.stories\.(m?js|ts)x?$/, indexer: csfIndexer },
],
indexers: [],
storiesV2Compatibility: false,
storyStoreV7: true,
docs: { defaultName: 'docs', autodocs: false },
};
describe('StoryIndexGenerator with deprecated indexer API', () => {
beforeEach(() => {
const actual = jest.requireActual('@storybook/csf-tools');
loadCsfMock.mockImplementation(actual.loadCsf);
jest.mocked(logger.warn).mockClear();
jest.mocked(once.warn).mockClear();
});
describe('extraction', () => {
const storiesSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/A.stories.(ts|js|mjs|jsx)',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/docs2/*.mdx',
options
);
describe('single file specifier', () => {
it('extracts stories from the right files', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/A.stories.js',
options
);
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"name": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
"type": "story",
},
},
"v": 4,
}
`);
});
});
describe('non-recursive specifier', () => {
it('extracts stories from the right files', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/*/*.stories.(ts|js|mjs|jsx)',
options
);
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"nested-button--story-one": Object {
"id": "nested-button--story-one",
"importPath": "./src/nested/Button.stories.ts",
"name": "Story One",
"tags": Array [
"component-tag",
"story",
],
"title": "nested/Button",
"type": "story",
},
"second-nested-g--story-one": Object {
"id": "second-nested-g--story-one",
"importPath": "./src/second-nested/G.stories.ts",
"name": "Story One",
"tags": Array [
"story",
],
"title": "second-nested/G",
"type": "story",
},
},
"v": 4,
}
`);
});
});
describe('recursive specifier', () => {
it('extracts stories from the right files', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"name": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
"type": "story",
},
"b--story-one": Object {
"id": "b--story-one",
"importPath": "./src/B.stories.ts",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "B",
"type": "story",
},
"d--story-one": Object {
"id": "d--story-one",
"importPath": "./src/D.stories.jsx",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "D",
"type": "story",
},
"first-nested-deeply-f--story-one": Object {
"id": "first-nested-deeply-f--story-one",
"importPath": "./src/first-nested/deeply/F.stories.js",
"name": "Story One",
"tags": Array [
"story",
],
"title": "first-nested/deeply/F",
"type": "story",
},
"h--story-one": Object {
"id": "h--story-one",
"importPath": "./src/H.stories.mjs",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "H",
"type": "story",
},
"nested-button--story-one": Object {
"id": "nested-button--story-one",
"importPath": "./src/nested/Button.stories.ts",
"name": "Story One",
"tags": Array [
"component-tag",
"story",
],
"title": "nested/Button",
"type": "story",
},
"second-nested-g--story-one": Object {
"id": "second-nested-g--story-one",
"importPath": "./src/second-nested/G.stories.ts",
"name": "Story One",
"tags": Array [
"story",
],
"title": "second-nested/G",
"type": "story",
},
},
"v": 4,
}
`);
});
});
describe('mdx tagged components', () => {
it('adds docs entry with docs enabled', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/nested/Page.stories.mdx',
options
);
const generator = new StoryIndexGenerator([specifier], {
...options,
});
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"page--docs": Object {
"id": "page--docs",
"importPath": "./src/nested/Page.stories.mdx",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"stories-mdx",
"docs",
],
"title": "Page",
"type": "docs",
},
"page--story-one": Object {
"id": "page--story-one",
"importPath": "./src/nested/Page.stories.mdx",
"name": "StoryOne",
"tags": Array [
"stories-mdx",
"story",
],
"title": "Page",
"type": "story",
},
},
"v": 4,
}
`);
});
});
describe('autodocs', () => {
const autodocsOptions = {
...options,
docs: { ...options.docs, autodocs: 'tag' as const },
};
it('generates an entry per CSF file with the autodocs tag', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
const generator = new StoryIndexGenerator([specifier], autodocsOptions);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"name": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
"type": "story",
},
"b--docs": Object {
"id": "b--docs",
"importPath": "./src/B.stories.ts",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"autodocs",
"docs",
],
"title": "B",
"type": "docs",
},
"b--story-one": Object {
"id": "b--story-one",
"importPath": "./src/B.stories.ts",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "B",
"type": "story",
},
"d--docs": Object {
"id": "d--docs",
"importPath": "./src/D.stories.jsx",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"autodocs",
"docs",
],
"title": "D",
"type": "docs",
},
"d--story-one": Object {
"id": "d--story-one",
"importPath": "./src/D.stories.jsx",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "D",
"type": "story",
},
"first-nested-deeply-f--story-one": Object {
"id": "first-nested-deeply-f--story-one",
"importPath": "./src/first-nested/deeply/F.stories.js",
"name": "Story One",
"tags": Array [
"story",
],
"title": "first-nested/deeply/F",
"type": "story",
},
"h--docs": Object {
"id": "h--docs",
"importPath": "./src/H.stories.mjs",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"autodocs",
"docs",
],
"title": "H",
"type": "docs",
},
"h--story-one": Object {
"id": "h--story-one",
"importPath": "./src/H.stories.mjs",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "H",
"type": "story",
},
"nested-button--story-one": Object {
"id": "nested-button--story-one",
"importPath": "./src/nested/Button.stories.ts",
"name": "Story One",
"tags": Array [
"component-tag",
"story",
],
"title": "nested/Button",
"type": "story",
},
"second-nested-g--story-one": Object {
"id": "second-nested-g--story-one",
"importPath": "./src/second-nested/G.stories.ts",
"name": "Story One",
"tags": Array [
"story",
],
"title": "second-nested/G",
"type": "story",
},
},
"v": 4,
}
`);
});
const autodocsTrueOptions = {
...autodocsOptions,
docs: {
...autodocsOptions.docs,
autodocs: true,
},
};
it('generates an entry for every CSF file when docsOptions.autodocs = true', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
const generator = new StoryIndexGenerator([specifier], autodocsTrueOptions);
await generator.initialize();
expect(Object.keys((await generator.getIndex()).entries)).toMatchInlineSnapshot(`
Array [
"a--docs",
"a--story-one",
"b--docs",
"b--story-one",
"d--docs",
"d--story-one",
"h--docs",
"h--story-one",
"first-nested-deeply-f--docs",
"first-nested-deeply-f--story-one",
"nested-button--docs",
"nested-button--story-one",
"second-nested-g--docs",
"second-nested-g--story-one",
]
`);
});
it('adds the autodocs tag to the autogenerated docs entries', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
const generator = new StoryIndexGenerator([specifier], autodocsTrueOptions);
await generator.initialize();
const index = await generator.getIndex();
expect(index.entries['first-nested-deeply-f--docs'].tags).toEqual(
expect.arrayContaining(['autodocs'])
);
});
it('throws an error if you attach a named MetaOf entry which clashes with a tagged autodocs entry', async () => {
const csfSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/B.stories.ts',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/MetaOfClashingDefaultName.mdx',
options
);
const generator = new StoryIndexGenerator([csfSpecifier, docsSpecifier], autodocsOptions);
await generator.initialize();
await expect(generator.getIndex()).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unable to index ./errors/MetaOfClashingDefaultName.mdx,./src/B.stories.ts"`
);
});
it('throws an error if you attach a unnamed MetaOf entry with the same name as the CSF file that clashes with a tagged autodocs entry', async () => {
const csfSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/B.stories.ts',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/B.mdx',
options
);
const generator = new StoryIndexGenerator([csfSpecifier, docsSpecifier], autodocsOptions);
await generator.initialize();
await expect(generator.getIndex()).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unable to index ./errors/B.mdx,./src/B.stories.ts"`
);
});
it('allows you to create a second unnamed MetaOf entry that does not clash with autodocs', async () => {
const csfSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/B.stories.ts',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/MetaOfNoName.mdx',
options
);
const generator = new StoryIndexGenerator([csfSpecifier, docsSpecifier], autodocsOptions);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"b--docs": Object {
"id": "b--docs",
"importPath": "./src/B.stories.ts",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"autodocs",
"docs",
],
"title": "B",
"type": "docs",
},
"b--metaofnoname": Object {
"id": "b--metaofnoname",
"importPath": "./errors/MetaOfNoName.mdx",
"name": "MetaOfNoName",
"storiesImports": Array [
"./src/B.stories.ts",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "B",
"type": "docs",
},
"b--story-one": Object {
"id": "b--story-one",
"importPath": "./src/B.stories.ts",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "B",
"type": "story",
},
},
"v": 4,
}
`);
});
it('allows you to create a second MetaOf entry with a different name to autodocs', async () => {
const csfSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/B.stories.ts',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/MetaOfName.mdx',
options
);
const generator = new StoryIndexGenerator([csfSpecifier, docsSpecifier], autodocsOptions);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"b--docs": Object {
"id": "b--docs",
"importPath": "./src/B.stories.ts",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"autodocs",
"docs",
],
"title": "B",
"type": "docs",
},
"b--name": Object {
"id": "b--name",
"importPath": "./errors/MetaOfName.mdx",
"name": "name",
"storiesImports": Array [
"./src/B.stories.ts",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "B",
"type": "docs",
},
"b--story-one": Object {
"id": "b--story-one",
"importPath": "./src/B.stories.ts",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "B",
"type": "story",
},
},
"v": 4,
}
`);
});
it('allows you to override autodocs with MetaOf if it is automatic', async () => {
const csfSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/A.stories.js',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/A.mdx',
options
);
const generator = new StoryIndexGenerator(
[csfSpecifier, docsSpecifier],
autodocsTrueOptions
);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"a--docs": Object {
"id": "a--docs",
"importPath": "./errors/A.mdx",
"name": "docs",
"storiesImports": Array [
"./src/A.stories.js",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "A",
"type": "docs",
},
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"name": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
"type": "story",
},
},
"v": 4,
}
`);
});
it('generates a combined entry if there are two stories files for the same title', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./duplicate/*.stories.(ts|js|mjs|jsx)',
options
);
const generator = new StoryIndexGenerator([specifier], autodocsOptions);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"duplicate-a--docs": Object {
"id": "duplicate-a--docs",
"importPath": "./duplicate/A.stories.js",
"name": "docs",
"storiesImports": Array [
"./duplicate/SecondA.stories.js",
],
"tags": Array [
"autodocs",
"docs",
],
"title": "duplicate/A",
"type": "docs",
},
"duplicate-a--story-one": Object {
"id": "duplicate-a--story-one",
"importPath": "./duplicate/A.stories.js",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "duplicate/A",
"type": "story",
},
"duplicate-a--story-two": Object {
"id": "duplicate-a--story-two",
"importPath": "./duplicate/SecondA.stories.js",
"name": "Story Two",
"tags": Array [
"autodocs",
"story",
],
"title": "duplicate/A",
"type": "story",
},
},
"v": 4,
}
`);
});
// https://github.com/storybookjs/storybook/issues/19142
it('does not generate a docs page entry if there are no stories in the CSF file', async () => {
const csfSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/NoStories.stories.ts',
options
);
const generator = new StoryIndexGenerator([csfSpecifier], autodocsOptions);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {},
"v": 4,
}
`);
});
});
describe('docs specifier', () => {
it('creates correct docs entries', async () => {
const generator = new StoryIndexGenerator([storiesSpecifier, docsSpecifier], options);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"a--metaof": Object {
"id": "a--metaof",
"importPath": "./src/docs2/MetaOf.mdx",
"name": "MetaOf",
"storiesImports": Array [
"./src/A.stories.js",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "A",
"type": "docs",
},
"a--second-docs": Object {
"id": "a--second-docs",
"importPath": "./src/docs2/SecondMetaOf.mdx",
"name": "Second Docs",
"storiesImports": Array [
"./src/A.stories.js",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "A",
"type": "docs",
},
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"name": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
"type": "story",
},
"componentreference--docs": Object {
"id": "componentreference--docs",
"importPath": "./src/docs2/ComponentReference.mdx",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "ComponentReference",
"type": "docs",
},
"docs2-yabbadabbadooo--docs": Object {
"id": "docs2-yabbadabbadooo--docs",
"importPath": "./src/docs2/Title.mdx",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "docs2/Yabbadabbadooo",
"type": "docs",
},
"notitle--docs": Object {
"id": "notitle--docs",
"importPath": "./src/docs2/NoTitle.mdx",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "NoTitle",
"type": "docs",
},
},
"v": 4,
}
`);
});
it('does not append title prefix if meta references a CSF file', async () => {
const generator = new StoryIndexGenerator(
[
storiesSpecifier,
normalizeStoriesEntry(
{ directory: './src/docs2', files: '**/*.mdx', titlePrefix: 'titlePrefix' },
options
),
],
options
);
await generator.initialize();
// NOTE: `toMatchInlineSnapshot` on objects sorts the keys, but in actuality, they are
// not sorted by default.
expect(Object.values((await generator.getIndex()).entries).map((e) => e.title))
.toMatchInlineSnapshot(`
Array [
"A",
"titlePrefix/ComponentReference",
"A",
"titlePrefix/NoTitle",
"A",
"titlePrefix/docs2/Yabbadabbadooo",
]
`);
});
it('Allows you to override default name for docs files', async () => {
const generator = new StoryIndexGenerator([storiesSpecifier, docsSpecifier], {
...options,
docs: {
...options.docs,
defaultName: 'Info',
},
});
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"a--metaof": Object {
"id": "a--metaof",
"importPath": "./src/docs2/MetaOf.mdx",
"name": "MetaOf",
"storiesImports": Array [
"./src/A.stories.js",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "A",
"type": "docs",
},
"a--second-docs": Object {
"id": "a--second-docs",
"importPath": "./src/docs2/SecondMetaOf.mdx",
"name": "Second Docs",
"storiesImports": Array [
"./src/A.stories.js",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "A",
"type": "docs",
},
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"name": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
"type": "story",
},
"componentreference--info": Object {
"id": "componentreference--info",
"importPath": "./src/docs2/ComponentReference.mdx",
"name": "Info",
"storiesImports": Array [],
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "ComponentReference",
"type": "docs",
},
"docs2-yabbadabbadooo--info": Object {
"id": "docs2-yabbadabbadooo--info",
"importPath": "./src/docs2/Title.mdx",
"name": "Info",
"storiesImports": Array [],
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "docs2/Yabbadabbadooo",
"type": "docs",
},
"notitle--info": Object {
"id": "notitle--info",
"importPath": "./src/docs2/NoTitle.mdx",
"name": "Info",
"storiesImports": Array [],
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "NoTitle",
"type": "docs",
},
},
"v": 4,
}
`);
});
it('pulls the attached story file to the front of the list', async () => {
const generator = new StoryIndexGenerator(
[
normalizeStoriesEntry('./src/A.stories.js', options),
normalizeStoriesEntry('./src/B.stories.ts', options),
normalizeStoriesEntry('./complex/TwoStoryReferences.mdx', options),
],
options
);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"name": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
"type": "story",
},
"b--story-one": Object {
"id": "b--story-one",
"importPath": "./src/B.stories.ts",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "B",
"type": "story",
},
"b--twostoryreferences": Object {
"id": "b--twostoryreferences",
"importPath": "./complex/TwoStoryReferences.mdx",
"name": "TwoStoryReferences",
"storiesImports": Array [
"./src/B.stories.ts",
"./src/A.stories.js",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "B",
"type": "docs",
},
},
"v": 4,
}
`);
});
});
describe('errors', () => {
it('when docs dependencies are missing', async () => {
const generator = new StoryIndexGenerator(
[normalizeStoriesEntry('./src/docs2/MetaOf.mdx', options)],
options
);
await generator.initialize();
await expect(() => generator.getIndex()).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unable to index ./src/docs2/MetaOf.mdx"`
);
});
});
describe('warnings', () => {
it('when entries do not match any files', async () => {
const generator = new StoryIndexGenerator(
[normalizeStoriesEntry('./src/docs2/wrong.js', options)],
options
);
await generator.initialize();
await generator.getIndex();
expect(once.warn).toHaveBeenCalledTimes(1);
const logMessage = jest.mocked(once.warn).mock.calls[0][0];
expect(logMessage).toContain(`No story files found for the specified pattern`);
});
});
describe('duplicates', () => {
it('errors when two MDX entries reference the same CSF file without a name', async () => {
const docsErrorSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/**/A.mdx',
options
);
const generator = new StoryIndexGenerator(
[storiesSpecifier, docsSpecifier, docsErrorSpecifier],
options
);
await generator.initialize();
await expect(generator.getIndex()).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unable to index ./errors/A.mdx,./errors/duplicate/A.mdx"`
);
});
it('errors when a MDX entry has the same name as a story', async () => {
const docsErrorSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/MetaOfClashingName.mdx',
options
);
const generator = new StoryIndexGenerator(
[storiesSpecifier, docsSpecifier, docsErrorSpecifier],
options
);
await generator.initialize();
await expect(generator.getIndex()).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unable to index ./src/A.stories.js,./errors/MetaOfClashingName.mdx"`
);
});
it('errors when a story has the default docs name', async () => {
const docsErrorSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/A.mdx',
options
);
const generator = new StoryIndexGenerator(
[storiesSpecifier, docsSpecifier, docsErrorSpecifier],
{
...options,
docs: { ...options.docs, defaultName: 'Story One' },
}
);
await generator.initialize();
await expect(generator.getIndex()).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unable to index ./src/A.stories.js,./errors/A.mdx"`
);
});
it('errors when two duplicate stories exists, with duplicated entries details', async () => {
const generator = new StoryIndexGenerator([storiesSpecifier, docsSpecifier], {
...options,
});
await generator.initialize();
const mockEntry: StoryIndexEntry = {
id: 'StoryId',
name: 'StoryName',
title: 'ComponentTitle',
importPath: 'Path',
type: 'story',
};
expect(() => {
generator.chooseDuplicate(mockEntry, { ...mockEntry, importPath: 'DifferentPath' });
}).toThrowErrorMatchingInlineSnapshot(`"Duplicate stories with id: StoryId"`);
});
it('DOES NOT error when the same MDX file matches two specifiers', async () => {
const generator = new StoryIndexGenerator(
[storiesSpecifier, docsSpecifier, docsSpecifier],
options
);
await generator.initialize();
expect(Object.keys((await generator.getIndex()).entries)).toMatchInlineSnapshot(`
Array [
"a--story-one",
"componentreference--docs",
"a--metaof",
"notitle--docs",
"a--second-docs",
"docs2-yabbadabbadooo--docs",
]
`);
expect(logger.warn).not.toHaveBeenCalled();
});
it('DOES NOT throw when the same CSF file matches two specifiers', async () => {
const generator = new StoryIndexGenerator([storiesSpecifier, storiesSpecifier], {
...options,
});
await generator.initialize();
expect(Object.keys((await generator.getIndex()).entries)).toMatchInlineSnapshot(`
Array [
"a--story-one",
]
`);
expect(logger.warn).not.toHaveBeenCalled();
});
it('DOES NOT throw when the same CSF file is indexed by both a deprecated and current indexer', async () => {
const generator = new StoryIndexGenerator([storiesSpecifier], {
...options,
indexers: [
{
test: /\.stories\.(m?js|ts)x?$/,
createIndex: async (fileName, options) => {
const code = (await fs.readFile(fileName, 'utf-8')).toString();
const csf = loadCsf(code, { ...options, fileName }).parse();
// eslint-disable-next-line no-underscore-dangle
return Object.entries(csf._stories).map(([exportName, story]) => ({
type: 'story',
importPath: fileName,
exportName,
name: story.name,
title: csf.meta.title,
metaId: csf.meta.id,
tags: story.tags ?? csf.meta.tags,
__id: story.id,
}));
},
},
],
});
await generator.initialize();
expect(Object.keys((await generator.getIndex()).entries)).toMatchInlineSnapshot(`
Array [
"a--story-one",
]
`);
expect(logger.warn).not.toHaveBeenCalled();
});
});
});
describe('sorting', () => {
it('runs a user-defined sort function', async () => {
const storiesSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/docs2/*.mdx',
options
);
const generator = new StoryIndexGenerator([docsSpecifier, storiesSpecifier], options);
await generator.initialize();
(getStorySortParameter as jest.Mock).mockReturnValueOnce({
order: ['docs2', 'D', 'B', 'nested', 'A', 'second-nested', 'first-nested/deeply'],
});
expect(Object.keys((await generator.getIndex()).entries)).toMatchInlineSnapshot(`
Array [
"docs2-yabbadabbadooo--docs",
"d--story-one",
"b--story-one",
"nested-button--story-one",
"a--metaof",
"a--second-docs",
"a--story-one",
"second-nested-g--story-one",
"componentreference--docs",
"notitle--docs",
"h--story-one",
"first-nested-deeply-f--story-one",
]
`);
});
});
describe('caching', () => {
describe('no invalidation', () => {
it('does not extract csf files a second time', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
loadCsfMock.mockClear();
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
await generator.getIndex();
expect(loadCsfMock).toHaveBeenCalledTimes(7);
loadCsfMock.mockClear();
await generator.getIndex();
expect(loadCsfMock).not.toHaveBeenCalled();
});
it('does not extract docs files a second time', async () => {
const storiesSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/A.stories.(ts|js|mjs|jsx)',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/docs2/*.mdx',
options
);
const generator = new StoryIndexGenerator([storiesSpecifier, docsSpecifier], options);
await generator.initialize();
await generator.getIndex();
expect(toId).toHaveBeenCalledTimes(6);
toIdMock.mockClear();
await generator.getIndex();
expect(toId).not.toHaveBeenCalled();
});
it('does not call the sort function a second time', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
const sortFn = jest.fn();
getStorySortParameterMock.mockReturnValue(sortFn);
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
await generator.getIndex();
expect(sortFn).toHaveBeenCalled();
sortFn.mockClear();
await generator.getIndex();
expect(sortFn).not.toHaveBeenCalled();
});
});
describe('file changed', () => {
it('calls extract csf file for just the one file', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
loadCsfMock.mockClear();
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
await generator.getIndex();
expect(loadCsfMock).toHaveBeenCalledTimes(7);
generator.invalidate(specifier, './src/B.stories.ts', false);
loadCsfMock.mockClear();
await generator.getIndex();
expect(loadCsfMock).toHaveBeenCalledTimes(1);
});
it('calls extract docs file for just the one file', async () => {
const storiesSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/A.stories.(ts|js|mjs|jsx)',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/docs2/*.mdx',
options
);
const generator = new StoryIndexGenerator([storiesSpecifier, docsSpecifier], options);
await generator.initialize();
await generator.getIndex();
expect(toId).toHaveBeenCalledTimes(6);
generator.invalidate(docsSpecifier, './src/docs2/Title.mdx', false);
toIdMock.mockClear();
await generator.getIndex();
expect(toId).toHaveBeenCalledTimes(1);
});
it('calls extract for a csf file and any of its docs dependents', async () => {
const storiesSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/A.stories.(ts|js|mjs|jsx)',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/docs2/*.mdx',
options
);
const generator = new StoryIndexGenerator([storiesSpecifier, docsSpecifier], options);
await generator.initialize();
await generator.getIndex();
expect(toId).toHaveBeenCalledTimes(6);
generator.invalidate(storiesSpecifier, './src/A.stories.js', false);
toIdMock.mockClear();
await generator.getIndex();
expect(toId).toHaveBeenCalledTimes(3);
});
it('does call the sort function a second time', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
const sortFn = jest.fn();
getStorySortParameterMock.mockReturnValue(sortFn);
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
await generator.getIndex();
expect(sortFn).toHaveBeenCalled();
generator.invalidate(specifier, './src/B.stories.ts', false);
sortFn.mockClear();
await generator.getIndex();
expect(sortFn).toHaveBeenCalled();
});
});
describe('file removed', () => {
it('does not extract csf files a second time', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
loadCsfMock.mockClear();
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
await generator.getIndex();
expect(loadCsfMock).toHaveBeenCalledTimes(7);
generator.invalidate(specifier, './src/B.stories.ts', true);
loadCsfMock.mockClear();
await generator.getIndex();
expect(loadCsfMock).not.toHaveBeenCalled();
});
it('does call the sort function a second time', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
const sortFn = jest.fn();
getStorySortParameterMock.mockReturnValue(sortFn);
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
await generator.getIndex();
expect(sortFn).toHaveBeenCalled();
generator.invalidate(specifier, './src/B.stories.ts', true);
sortFn.mockClear();
await generator.getIndex();
expect(sortFn).toHaveBeenCalled();
});
it('does not include the deleted stories in results', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
loadCsfMock.mockClear();
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
await generator.getIndex();
expect(loadCsfMock).toHaveBeenCalledTimes(7);
generator.invalidate(specifier, './src/B.stories.ts', true);
expect(Object.keys((await generator.getIndex()).entries)).not.toContain('b--story-one');
});
it('does not include the deleted docs in results', async () => {
const storiesSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/A.stories.(ts|js|mjs|jsx)',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/docs2/*.mdx',
options
);
const generator = new StoryIndexGenerator([docsSpecifier, storiesSpecifier], options);
await generator.initialize();
await generator.getIndex();
expect(toId).toHaveBeenCalledTimes(6);
expect(Object.keys((await generator.getIndex()).entries)).toContain('notitle--docs');
generator.invalidate(docsSpecifier, './src/docs2/NoTitle.mdx', true);
expect(Object.keys((await generator.getIndex()).entries)).not.toContain('notitle--docs');
});
it('cleans up properly on dependent docs deletion', async () => {
const storiesSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/A.stories.(ts|js|mjs|jsx)',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/docs2/*.mdx',
options
);
const generator = new StoryIndexGenerator([docsSpecifier, storiesSpecifier], options);
await generator.initialize();
await generator.getIndex();
expect(toId).toHaveBeenCalledTimes(6);
expect(Object.keys((await generator.getIndex()).entries)).toContain('a--metaof');
generator.invalidate(docsSpecifier, './src/docs2/MetaOf.mdx', true);
expect(Object.keys((await generator.getIndex()).entries)).not.toContain('a--metaof');
// this will throw if MetaOf is not removed from A's dependents
generator.invalidate(storiesSpecifier, './src/A.stories.js', false);
});
});
});
});
|
832 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-server/src | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils/StoryIndexGenerator.test.ts | /* eslint-disable @typescript-eslint/no-shadow */
/// <reference types="@types/jest" />;
/**
* @jest-environment node
*/
import path from 'path';
// @ts-expect-error -- cannot find declaration file
import { createStoriesMdxIndexer } from '@storybook/addon-docs/preset';
import { normalizeStoriesEntry } from '@storybook/core-common';
import type { NormalizedStoriesSpecifier, StoryIndexEntry } from '@storybook/types';
import { readCsf, getStorySortParameter } from '@storybook/csf-tools';
import { toId } from '@storybook/csf';
import { logger, once } from '@storybook/node-logger';
import type { StoryIndexGeneratorOptions } from './StoryIndexGenerator';
import { StoryIndexGenerator } from './StoryIndexGenerator';
import { csfIndexer } from '../presets/common-preset';
jest.mock('@storybook/csf', () => {
const csf = jest.requireActual('@storybook/csf');
return {
...csf,
toId: jest.fn(csf.toId),
};
});
jest.mock('@storybook/node-logger');
const toIdMock = toId as jest.Mock<ReturnType<typeof toId>>;
jest.mock('@storybook/csf-tools', () => {
const csfTools = jest.requireActual('@storybook/csf-tools');
return {
...csfTools,
readCsf: jest.fn(csfTools.readCsf),
getStorySortParameter: jest.fn(csfTools.getStorySortParameter),
};
});
const readCsfMock = readCsf as jest.Mock<ReturnType<typeof readCsf>>;
const getStorySortParameterMock = getStorySortParameter as jest.Mock<
ReturnType<typeof getStorySortParameter>
>;
const options: StoryIndexGeneratorOptions = {
configDir: path.join(__dirname, '__mockdata__'),
workingDir: path.join(__dirname, '__mockdata__'),
storyIndexers: [],
indexers: [csfIndexer, createStoriesMdxIndexer(false)],
storiesV2Compatibility: false,
storyStoreV7: true,
docs: { defaultName: 'docs', autodocs: false },
};
describe('StoryIndexGenerator', () => {
beforeEach(() => {
jest.mocked(logger.warn).mockClear();
jest.mocked(once.warn).mockClear();
});
describe('extraction', () => {
const storiesSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/A.stories.(ts|js|mjs|jsx)',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/docs2/*.mdx',
options
);
describe('single file specifier', () => {
it('extracts stories from the right files', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/A.stories.js',
options
);
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"name": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
"type": "story",
},
},
"v": 4,
}
`);
});
});
describe('single file .story specifier', () => {
it('extracts stories from the right files', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/F.story.ts',
options
);
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"f--story-one": Object {
"id": "f--story-one",
"importPath": "./src/F.story.ts",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "F",
"type": "story",
},
},
"v": 4,
}
`);
});
});
describe('no prefix stories specifier', () => {
it('extracts stories from the right files', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/stories.ts',
options
);
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"stories--story-one": Object {
"id": "stories--story-one",
"importPath": "./src/stories.ts",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "stories",
"type": "story",
},
},
"v": 4,
}
`);
});
});
describe('non-recursive specifier', () => {
it('extracts stories from the right files', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/*/*.stories.(ts|js|mjs|jsx)',
options
);
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"nested-button--story-one": Object {
"id": "nested-button--story-one",
"importPath": "./src/nested/Button.stories.ts",
"name": "Story One",
"tags": Array [
"component-tag",
"story",
],
"title": "nested/Button",
"type": "story",
},
"second-nested-g--story-one": Object {
"id": "second-nested-g--story-one",
"importPath": "./src/second-nested/G.stories.ts",
"name": "Story One",
"tags": Array [
"story",
],
"title": "second-nested/G",
"type": "story",
},
},
"v": 4,
}
`);
});
});
describe('recursive specifier', () => {
it('extracts stories from the right files', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"name": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
"type": "story",
},
"b--story-one": Object {
"id": "b--story-one",
"importPath": "./src/B.stories.ts",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "B",
"type": "story",
},
"d--story-one": Object {
"id": "d--story-one",
"importPath": "./src/D.stories.jsx",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "D",
"type": "story",
},
"first-nested-deeply-f--story-one": Object {
"id": "first-nested-deeply-f--story-one",
"importPath": "./src/first-nested/deeply/F.stories.js",
"name": "Story One",
"tags": Array [
"story",
],
"title": "first-nested/deeply/F",
"type": "story",
},
"h--story-one": Object {
"id": "h--story-one",
"importPath": "./src/H.stories.mjs",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "H",
"type": "story",
},
"nested-button--story-one": Object {
"id": "nested-button--story-one",
"importPath": "./src/nested/Button.stories.ts",
"name": "Story One",
"tags": Array [
"component-tag",
"story",
],
"title": "nested/Button",
"type": "story",
},
"second-nested-g--story-one": Object {
"id": "second-nested-g--story-one",
"importPath": "./src/second-nested/G.stories.ts",
"name": "Story One",
"tags": Array [
"story",
],
"title": "second-nested/G",
"type": "story",
},
},
"v": 4,
}
`);
});
});
describe('mdx tagged components', () => {
it('adds docs entry with docs enabled', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/nested/Page.stories.mdx',
options
);
const generator = new StoryIndexGenerator([specifier], {
...options,
});
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"page--docs": Object {
"id": "page--docs",
"importPath": "./src/nested/Page.stories.mdx",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"stories-mdx",
"docs",
],
"title": "Page",
"type": "docs",
},
"page--story-one": Object {
"id": "page--story-one",
"importPath": "./src/nested/Page.stories.mdx",
"name": "StoryOne",
"tags": Array [
"stories-mdx",
"story",
],
"title": "Page",
"type": "story",
},
},
"v": 4,
}
`);
});
});
describe('autodocs', () => {
const autodocsOptions = {
...options,
docs: { ...options.docs, autodocs: 'tag' as const },
};
it('generates an entry per CSF file with the autodocs tag', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
const generator = new StoryIndexGenerator([specifier], autodocsOptions);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"name": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
"type": "story",
},
"b--docs": Object {
"id": "b--docs",
"importPath": "./src/B.stories.ts",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"autodocs",
"docs",
],
"title": "B",
"type": "docs",
},
"b--story-one": Object {
"id": "b--story-one",
"importPath": "./src/B.stories.ts",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "B",
"type": "story",
},
"d--docs": Object {
"id": "d--docs",
"importPath": "./src/D.stories.jsx",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"autodocs",
"docs",
],
"title": "D",
"type": "docs",
},
"d--story-one": Object {
"id": "d--story-one",
"importPath": "./src/D.stories.jsx",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "D",
"type": "story",
},
"first-nested-deeply-f--story-one": Object {
"id": "first-nested-deeply-f--story-one",
"importPath": "./src/first-nested/deeply/F.stories.js",
"name": "Story One",
"tags": Array [
"story",
],
"title": "first-nested/deeply/F",
"type": "story",
},
"h--docs": Object {
"id": "h--docs",
"importPath": "./src/H.stories.mjs",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"autodocs",
"docs",
],
"title": "H",
"type": "docs",
},
"h--story-one": Object {
"id": "h--story-one",
"importPath": "./src/H.stories.mjs",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "H",
"type": "story",
},
"nested-button--story-one": Object {
"id": "nested-button--story-one",
"importPath": "./src/nested/Button.stories.ts",
"name": "Story One",
"tags": Array [
"component-tag",
"story",
],
"title": "nested/Button",
"type": "story",
},
"second-nested-g--story-one": Object {
"id": "second-nested-g--story-one",
"importPath": "./src/second-nested/G.stories.ts",
"name": "Story One",
"tags": Array [
"story",
],
"title": "second-nested/G",
"type": "story",
},
},
"v": 4,
}
`);
});
const autodocsTrueOptions = {
...autodocsOptions,
docs: {
...autodocsOptions.docs,
autodocs: true,
},
};
it('generates an entry for every CSF file when docsOptions.autodocs = true', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
const generator = new StoryIndexGenerator([specifier], autodocsTrueOptions);
await generator.initialize();
expect(Object.keys((await generator.getIndex()).entries)).toMatchInlineSnapshot(`
Array [
"a--docs",
"a--story-one",
"b--docs",
"b--story-one",
"d--docs",
"d--story-one",
"h--docs",
"h--story-one",
"first-nested-deeply-f--docs",
"first-nested-deeply-f--story-one",
"nested-button--docs",
"nested-button--story-one",
"second-nested-g--docs",
"second-nested-g--story-one",
]
`);
});
it('adds the autodocs tag to the autogenerated docs entries', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
const generator = new StoryIndexGenerator([specifier], autodocsTrueOptions);
await generator.initialize();
const index = await generator.getIndex();
expect(index.entries['first-nested-deeply-f--docs'].tags).toEqual(
expect.arrayContaining(['autodocs'])
);
});
it('throws an error if you attach a named MetaOf entry which clashes with a tagged autodocs entry', async () => {
const csfSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/B.stories.ts',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/MetaOfClashingDefaultName.mdx',
options
);
const generator = new StoryIndexGenerator([csfSpecifier, docsSpecifier], autodocsOptions);
await generator.initialize();
await expect(generator.getIndex()).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unable to index ./errors/MetaOfClashingDefaultName.mdx,./src/B.stories.ts"`
);
});
it('throws an error if you attach a unnamed MetaOf entry with the same name as the CSF file that clashes with a tagged autodocs entry', async () => {
const csfSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/B.stories.ts',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/B.mdx',
options
);
const generator = new StoryIndexGenerator([csfSpecifier, docsSpecifier], autodocsOptions);
await generator.initialize();
await expect(generator.getIndex()).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unable to index ./errors/B.mdx,./src/B.stories.ts"`
);
});
it('allows you to create a second unnamed MetaOf entry that does not clash with autodocs', async () => {
const csfSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/B.stories.ts',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/MetaOfNoName.mdx',
options
);
const generator = new StoryIndexGenerator([csfSpecifier, docsSpecifier], autodocsOptions);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"b--docs": Object {
"id": "b--docs",
"importPath": "./src/B.stories.ts",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"autodocs",
"docs",
],
"title": "B",
"type": "docs",
},
"b--metaofnoname": Object {
"id": "b--metaofnoname",
"importPath": "./errors/MetaOfNoName.mdx",
"name": "MetaOfNoName",
"storiesImports": Array [
"./src/B.stories.ts",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "B",
"type": "docs",
},
"b--story-one": Object {
"id": "b--story-one",
"importPath": "./src/B.stories.ts",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "B",
"type": "story",
},
},
"v": 4,
}
`);
});
it('allows you to create a second MetaOf entry with a different name to autodocs', async () => {
const csfSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/B.stories.ts',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/MetaOfName.mdx',
options
);
const generator = new StoryIndexGenerator([csfSpecifier, docsSpecifier], autodocsOptions);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"b--docs": Object {
"id": "b--docs",
"importPath": "./src/B.stories.ts",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"autodocs",
"docs",
],
"title": "B",
"type": "docs",
},
"b--name": Object {
"id": "b--name",
"importPath": "./errors/MetaOfName.mdx",
"name": "name",
"storiesImports": Array [
"./src/B.stories.ts",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "B",
"type": "docs",
},
"b--story-one": Object {
"id": "b--story-one",
"importPath": "./src/B.stories.ts",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "B",
"type": "story",
},
},
"v": 4,
}
`);
});
it('allows you to override autodocs with MetaOf if it is automatic', async () => {
const csfSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/A.stories.js',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/A.mdx',
options
);
const generator = new StoryIndexGenerator(
[csfSpecifier, docsSpecifier],
autodocsTrueOptions
);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"a--docs": Object {
"id": "a--docs",
"importPath": "./errors/A.mdx",
"name": "docs",
"storiesImports": Array [
"./src/A.stories.js",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "A",
"type": "docs",
},
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"name": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
"type": "story",
},
},
"v": 4,
}
`);
});
it('generates a combined entry if there are two stories files for the same title', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./duplicate/*.stories.(ts|js|mjs|jsx)',
options
);
const generator = new StoryIndexGenerator([specifier], autodocsOptions);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"duplicate-a--docs": Object {
"id": "duplicate-a--docs",
"importPath": "./duplicate/A.stories.js",
"name": "docs",
"storiesImports": Array [
"./duplicate/SecondA.stories.js",
],
"tags": Array [
"autodocs",
"docs",
],
"title": "duplicate/A",
"type": "docs",
},
"duplicate-a--story-one": Object {
"id": "duplicate-a--story-one",
"importPath": "./duplicate/A.stories.js",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "duplicate/A",
"type": "story",
},
"duplicate-a--story-two": Object {
"id": "duplicate-a--story-two",
"importPath": "./duplicate/SecondA.stories.js",
"name": "Story Two",
"tags": Array [
"autodocs",
"story",
],
"title": "duplicate/A",
"type": "story",
},
},
"v": 4,
}
`);
});
// https://github.com/storybookjs/storybook/issues/19142
it('does not generate a docs page entry if there are no stories in the CSF file', async () => {
const csfSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/NoStories.stories.ts',
options
);
const generator = new StoryIndexGenerator([csfSpecifier], autodocsOptions);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {},
"v": 4,
}
`);
});
it('prioritizes using the component id over meta.title for generating its id, if provided. (autodocs)', async () => {
const csfSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./docs-id-generation/A.stories.jsx',
options
);
const generator = new StoryIndexGenerator([csfSpecifier], autodocsOptions);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"my-component-a--docs": Object {
"id": "my-component-a--docs",
"importPath": "./docs-id-generation/A.stories.jsx",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"autodocs",
"docs",
],
"title": "A",
"type": "docs",
},
"my-component-a--story-one": Object {
"id": "my-component-a--story-one",
"importPath": "./docs-id-generation/A.stories.jsx",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "A",
"type": "story",
},
},
"v": 4,
}
`);
});
});
describe('docs specifier', () => {
it('creates correct docs entries', async () => {
const generator = new StoryIndexGenerator([storiesSpecifier, docsSpecifier], options);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"a--metaof": Object {
"id": "a--metaof",
"importPath": "./src/docs2/MetaOf.mdx",
"name": "MetaOf",
"storiesImports": Array [
"./src/A.stories.js",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "A",
"type": "docs",
},
"a--second-docs": Object {
"id": "a--second-docs",
"importPath": "./src/docs2/SecondMetaOf.mdx",
"name": "Second Docs",
"storiesImports": Array [
"./src/A.stories.js",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "A",
"type": "docs",
},
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"name": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
"type": "story",
},
"componentreference--docs": Object {
"id": "componentreference--docs",
"importPath": "./src/docs2/ComponentReference.mdx",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "ComponentReference",
"type": "docs",
},
"docs2-yabbadabbadooo--docs": Object {
"id": "docs2-yabbadabbadooo--docs",
"importPath": "./src/docs2/Title.mdx",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "docs2/Yabbadabbadooo",
"type": "docs",
},
"notitle--docs": Object {
"id": "notitle--docs",
"importPath": "./src/docs2/NoTitle.mdx",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "NoTitle",
"type": "docs",
},
},
"v": 4,
}
`);
});
it('does not append title prefix if meta references a CSF file', async () => {
const generator = new StoryIndexGenerator(
[
storiesSpecifier,
normalizeStoriesEntry(
{ directory: './src/docs2', files: '**/*.mdx', titlePrefix: 'titlePrefix' },
options
),
],
options
);
await generator.initialize();
// NOTE: `toMatchInlineSnapshot` on objects sorts the keys, but in actuality, they are
// not sorted by default.
expect(Object.values((await generator.getIndex()).entries).map((e) => e.title))
.toMatchInlineSnapshot(`
Array [
"A",
"titlePrefix/ComponentReference",
"A",
"titlePrefix/NoTitle",
"A",
"titlePrefix/docs2/Yabbadabbadooo",
]
`);
});
it('Allows you to override default name for docs files', async () => {
const generator = new StoryIndexGenerator([storiesSpecifier, docsSpecifier], {
...options,
docs: {
...options.docs,
defaultName: 'Info',
},
});
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"a--metaof": Object {
"id": "a--metaof",
"importPath": "./src/docs2/MetaOf.mdx",
"name": "MetaOf",
"storiesImports": Array [
"./src/A.stories.js",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "A",
"type": "docs",
},
"a--second-docs": Object {
"id": "a--second-docs",
"importPath": "./src/docs2/SecondMetaOf.mdx",
"name": "Second Docs",
"storiesImports": Array [
"./src/A.stories.js",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "A",
"type": "docs",
},
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"name": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
"type": "story",
},
"componentreference--info": Object {
"id": "componentreference--info",
"importPath": "./src/docs2/ComponentReference.mdx",
"name": "Info",
"storiesImports": Array [],
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "ComponentReference",
"type": "docs",
},
"docs2-yabbadabbadooo--info": Object {
"id": "docs2-yabbadabbadooo--info",
"importPath": "./src/docs2/Title.mdx",
"name": "Info",
"storiesImports": Array [],
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "docs2/Yabbadabbadooo",
"type": "docs",
},
"notitle--info": Object {
"id": "notitle--info",
"importPath": "./src/docs2/NoTitle.mdx",
"name": "Info",
"storiesImports": Array [],
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "NoTitle",
"type": "docs",
},
},
"v": 4,
}
`);
});
it('pulls the attached story file to the front of the list', async () => {
const generator = new StoryIndexGenerator(
[
normalizeStoriesEntry('./src/A.stories.js', options),
normalizeStoriesEntry('./src/B.stories.ts', options),
normalizeStoriesEntry('./complex/TwoStoryReferences.mdx', options),
],
options
);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"name": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
"type": "story",
},
"b--story-one": Object {
"id": "b--story-one",
"importPath": "./src/B.stories.ts",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "B",
"type": "story",
},
"b--twostoryreferences": Object {
"id": "b--twostoryreferences",
"importPath": "./complex/TwoStoryReferences.mdx",
"name": "TwoStoryReferences",
"storiesImports": Array [
"./src/B.stories.ts",
"./src/A.stories.js",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "B",
"type": "docs",
},
},
"v": 4,
}
`);
});
it('prioritizes using the component id over meta.title for generating its id, if provided. (mdx docs)', async () => {
const csfSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./docs-id-generation/B.stories.jsx',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./docs-id-generation/B.docs.mdx',
options
);
const generator = new StoryIndexGenerator([csfSpecifier, docsSpecifier], options);
await generator.initialize();
expect(await generator.getIndex()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"my-component-b--docs": Object {
"id": "my-component-b--docs",
"importPath": "./docs-id-generation/B.docs.mdx",
"name": "docs",
"storiesImports": Array [
"./docs-id-generation/B.stories.jsx",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "B",
"type": "docs",
},
"my-component-b--story-one": Object {
"id": "my-component-b--story-one",
"importPath": "./docs-id-generation/B.stories.jsx",
"name": "Story One",
"tags": Array [
"story",
],
"title": "B",
"type": "story",
},
},
"v": 4,
}
`);
});
});
describe('errors', () => {
it('when docs dependencies are missing', async () => {
const generator = new StoryIndexGenerator(
[normalizeStoriesEntry('./src/docs2/MetaOf.mdx', options)],
options
);
await generator.initialize();
await expect(() => generator.getIndex()).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unable to index ./src/docs2/MetaOf.mdx"`
);
});
});
describe('warnings', () => {
it('when entries do not match any files', async () => {
const generator = new StoryIndexGenerator(
[normalizeStoriesEntry('./src/docs2/wrong.js', options)],
options
);
await generator.initialize();
await generator.getIndex();
expect(once.warn).toHaveBeenCalledTimes(1);
const logMessage = jest.mocked(once.warn).mock.calls[0][0];
expect(logMessage).toContain(`No story files found for the specified pattern`);
});
});
describe('duplicates', () => {
it('errors when two MDX entries reference the same CSF file without a name', async () => {
const docsErrorSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/**/A.mdx',
options
);
const generator = new StoryIndexGenerator(
[storiesSpecifier, docsSpecifier, docsErrorSpecifier],
options
);
await generator.initialize();
await expect(generator.getIndex()).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unable to index ./errors/A.mdx,./errors/duplicate/A.mdx"`
);
});
it('errors when a MDX entry has the same name as a story', async () => {
const docsErrorSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/MetaOfClashingName.mdx',
options
);
const generator = new StoryIndexGenerator(
[storiesSpecifier, docsSpecifier, docsErrorSpecifier],
options
);
await generator.initialize();
await expect(generator.getIndex()).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unable to index ./src/A.stories.js,./errors/MetaOfClashingName.mdx"`
);
});
it('errors when a story has the default docs name', async () => {
const docsErrorSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./errors/A.mdx',
options
);
const generator = new StoryIndexGenerator(
[storiesSpecifier, docsSpecifier, docsErrorSpecifier],
{
...options,
docs: { ...options.docs, defaultName: 'Story One' },
}
);
await generator.initialize();
await expect(generator.getIndex()).rejects.toThrowErrorMatchingInlineSnapshot(
`"Unable to index ./src/A.stories.js,./errors/A.mdx"`
);
});
it('errors when two duplicate stories exists, with duplicated entries details', async () => {
const generator = new StoryIndexGenerator([storiesSpecifier, docsSpecifier], {
...options,
});
await generator.initialize();
const mockEntry: StoryIndexEntry = {
id: 'StoryId',
name: 'StoryName',
title: 'ComponentTitle',
importPath: 'Path',
type: 'story',
};
expect(() => {
generator.chooseDuplicate(mockEntry, { ...mockEntry, importPath: 'DifferentPath' });
}).toThrowErrorMatchingInlineSnapshot(`"Duplicate stories with id: StoryId"`);
});
it('DOES NOT error when the same MDX file matches two specifiers', async () => {
const generator = new StoryIndexGenerator(
[storiesSpecifier, docsSpecifier, docsSpecifier],
options
);
await generator.initialize();
expect(Object.keys((await generator.getIndex()).entries)).toMatchInlineSnapshot(`
Array [
"a--story-one",
"componentreference--docs",
"a--metaof",
"notitle--docs",
"a--second-docs",
"docs2-yabbadabbadooo--docs",
]
`);
expect(logger.warn).not.toHaveBeenCalled();
});
it('DOES NOT throw when the same CSF file matches two specifiers', async () => {
const generator = new StoryIndexGenerator([storiesSpecifier, storiesSpecifier], {
...options,
});
await generator.initialize();
expect(Object.keys((await generator.getIndex()).entries)).toMatchInlineSnapshot(`
Array [
"a--story-one",
]
`);
expect(logger.warn).not.toHaveBeenCalled();
});
});
});
describe('sorting', () => {
it('runs a user-defined sort function', async () => {
const storiesSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/docs2/*.mdx',
options
);
const generator = new StoryIndexGenerator([docsSpecifier, storiesSpecifier], options);
await generator.initialize();
getStorySortParameterMock.mockReturnValueOnce({
order: ['docs2', 'D', 'B', 'nested', 'A', 'second-nested', 'first-nested/deeply'],
});
expect(Object.keys((await generator.getIndex()).entries)).toMatchInlineSnapshot(`
Array [
"docs2-yabbadabbadooo--docs",
"d--story-one",
"b--story-one",
"nested-button--story-one",
"a--metaof",
"a--second-docs",
"a--story-one",
"second-nested-g--story-one",
"componentreference--docs",
"notitle--docs",
"h--story-one",
"first-nested-deeply-f--story-one",
]
`);
});
});
describe('caching', () => {
describe('no invalidation', () => {
it('does not extract csf files a second time', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
readCsfMock.mockClear();
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
await generator.getIndex();
expect(readCsfMock).toHaveBeenCalledTimes(7);
readCsfMock.mockClear();
await generator.getIndex();
expect(readCsfMock).not.toHaveBeenCalled();
});
it('does not extract docs files a second time', async () => {
const storiesSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/A.stories.(ts|js|mjs|jsx)',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/docs2/*.mdx',
options
);
const generator = new StoryIndexGenerator([storiesSpecifier, docsSpecifier], options);
await generator.initialize();
await generator.getIndex();
expect(toId).toHaveBeenCalledTimes(6);
toIdMock.mockClear();
await generator.getIndex();
expect(toId).not.toHaveBeenCalled();
});
it('does not call the sort function a second time', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
const sortFn = jest.fn();
getStorySortParameterMock.mockReturnValue(sortFn);
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
await generator.getIndex();
expect(sortFn).toHaveBeenCalled();
sortFn.mockClear();
await generator.getIndex();
expect(sortFn).not.toHaveBeenCalled();
});
});
describe('file changed', () => {
it('calls extract csf file for just the one file', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
readCsfMock.mockClear();
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
await generator.getIndex();
expect(readCsfMock).toHaveBeenCalledTimes(7);
generator.invalidate(specifier, './src/B.stories.ts', false);
readCsfMock.mockClear();
await generator.getIndex();
expect(readCsfMock).toHaveBeenCalledTimes(1);
});
it('calls extract docs file for just the one file', async () => {
const storiesSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/A.stories.(ts|js|mjs|jsx)',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/docs2/*.mdx',
options
);
const generator = new StoryIndexGenerator([storiesSpecifier, docsSpecifier], options);
await generator.initialize();
await generator.getIndex();
expect(toId).toHaveBeenCalledTimes(6);
generator.invalidate(docsSpecifier, './src/docs2/Title.mdx', false);
toIdMock.mockClear();
await generator.getIndex();
expect(toId).toHaveBeenCalledTimes(1);
});
it('calls extract for a csf file and any of its docs dependents', async () => {
const storiesSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/A.stories.(ts|js|mjs|jsx)',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/docs2/*.mdx',
options
);
const generator = new StoryIndexGenerator([storiesSpecifier, docsSpecifier], options);
await generator.initialize();
await generator.getIndex();
expect(toId).toHaveBeenCalledTimes(6);
generator.invalidate(storiesSpecifier, './src/A.stories.js', false);
toIdMock.mockClear();
await generator.getIndex();
expect(toId).toHaveBeenCalledTimes(3);
});
it('does call the sort function a second time', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
const sortFn = jest.fn();
getStorySortParameterMock.mockReturnValue(sortFn);
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
await generator.getIndex();
expect(sortFn).toHaveBeenCalled();
generator.invalidate(specifier, './src/B.stories.ts', false);
sortFn.mockClear();
await generator.getIndex();
expect(sortFn).toHaveBeenCalled();
});
});
describe('file removed', () => {
it('does not extract csf files a second time', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
readCsfMock.mockClear();
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
await generator.getIndex();
expect(readCsfMock).toHaveBeenCalledTimes(7);
generator.invalidate(specifier, './src/B.stories.ts', true);
readCsfMock.mockClear();
await generator.getIndex();
expect(readCsfMock).not.toHaveBeenCalled();
});
it('does call the sort function a second time', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
const sortFn = jest.fn();
getStorySortParameterMock.mockReturnValue(sortFn);
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
await generator.getIndex();
expect(sortFn).toHaveBeenCalled();
generator.invalidate(specifier, './src/B.stories.ts', true);
sortFn.mockClear();
await generator.getIndex();
expect(sortFn).toHaveBeenCalled();
});
it('does not include the deleted stories in results', async () => {
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/**/*.stories.(ts|js|mjs|jsx)',
options
);
readCsfMock.mockClear();
const generator = new StoryIndexGenerator([specifier], options);
await generator.initialize();
await generator.getIndex();
expect(readCsfMock).toHaveBeenCalledTimes(7);
generator.invalidate(specifier, './src/B.stories.ts', true);
expect(Object.keys((await generator.getIndex()).entries)).not.toContain('b--story-one');
});
it('does not include the deleted docs in results', async () => {
const storiesSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/A.stories.(ts|js|mjs|jsx)',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/docs2/*.mdx',
options
);
const generator = new StoryIndexGenerator([docsSpecifier, storiesSpecifier], options);
await generator.initialize();
await generator.getIndex();
expect(toId).toHaveBeenCalledTimes(6);
expect(Object.keys((await generator.getIndex()).entries)).toContain('notitle--docs');
generator.invalidate(docsSpecifier, './src/docs2/NoTitle.mdx', true);
expect(Object.keys((await generator.getIndex()).entries)).not.toContain('notitle--docs');
});
it('cleans up properly on dependent docs deletion', async () => {
const storiesSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/A.stories.(ts|js|mjs|jsx)',
options
);
const docsSpecifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(
'./src/docs2/*.mdx',
options
);
const generator = new StoryIndexGenerator([docsSpecifier, storiesSpecifier], options);
await generator.initialize();
await generator.getIndex();
expect(toId).toHaveBeenCalledTimes(6);
expect(Object.keys((await generator.getIndex()).entries)).toContain('a--metaof');
generator.invalidate(docsSpecifier, './src/docs2/MetaOf.mdx', true);
expect(Object.keys((await generator.getIndex()).entries)).not.toContain('a--metaof');
// this will throw if MetaOf is not removed from A's dependents
generator.invalidate(storiesSpecifier, './src/A.stories.js', false);
});
});
});
});
|
851 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-server/src | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils/server-address.test.ts | import detectPort from 'detect-port';
import { getServerAddresses, getServerPort, getServerChannelUrl } from './server-address';
jest.mock('ip');
jest.mock('detect-port');
jest.mock('@storybook/node-logger');
describe('getServerAddresses', () => {
const port = 3000;
const host = 'localhost';
const proto = 'http';
it('should return server addresses without initial path by default', () => {
const expectedAddress = `${proto}://localhost:${port}/`;
const expectedNetworkAddress = `${proto}://${host}:${port}/`;
const result = getServerAddresses(port, host, proto);
expect(result.address).toBe(expectedAddress);
expect(result.networkAddress).toBe(expectedNetworkAddress);
});
it('should return server addresses with initial path', () => {
const initialPath = '/foo/bar';
const expectedAddress = `${proto}://localhost:${port}/?path=/foo/bar`;
const expectedNetworkAddress = `${proto}://${host}:${port}/?path=/foo/bar`;
const result = getServerAddresses(port, host, proto, initialPath);
expect(result.address).toBe(expectedAddress);
expect(result.networkAddress).toBe(expectedNetworkAddress);
});
it('should return server addresses with initial path and add slash if missing', () => {
const initialPath = 'foo/bar';
const expectedAddress = `${proto}://localhost:${port}/?path=/foo/bar`;
const expectedNetworkAddress = `${proto}://${host}:${port}/?path=/foo/bar`;
const result = getServerAddresses(port, host, proto, initialPath);
expect(result.address).toBe(expectedAddress);
expect(result.networkAddress).toBe(expectedNetworkAddress);
});
});
describe('getServerPort', () => {
const port = 3000;
it('should resolve with a free port', async () => {
const expectedFreePort = 4000;
(detectPort as jest.Mock).mockResolvedValue(expectedFreePort);
const result = await getServerPort(port);
expect(result).toBe(expectedFreePort);
});
});
describe('getServerChannelUrl', () => {
const port = 3000;
it('should return WebSocket URL with HTTP', () => {
const options = { https: false };
const expectedUrl = `ws://localhost:${port}/storybook-server-channel`;
const result = getServerChannelUrl(port, options);
expect(result).toBe(expectedUrl);
});
it('should return WebSocket URL with HTTPS', () => {
const options = { https: true };
const expectedUrl = `wss://localhost:${port}/storybook-server-channel`;
const result = getServerChannelUrl(port, options);
expect(result).toBe(expectedUrl);
});
});
|
855 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-server/src | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils/stories-json.test.ts | /// <reference types="@types/jest" />;
import type { Router, Request, Response } from 'express';
import Watchpack from 'watchpack';
import path from 'path';
import debounce from 'lodash/debounce.js';
// @ts-expect-error -- cannot find declaration file
import { createStoriesMdxIndexer } from '@storybook/addon-docs/preset';
import { STORY_INDEX_INVALIDATED } from '@storybook/core-events';
import type { StoryIndex } from '@storybook/types';
import { normalizeStoriesEntry } from '@storybook/core-common';
import { useStoriesJson, DEBOUNCE, convertToIndexV3 } from './stories-json';
import type { ServerChannel } from './get-server-channel';
import type { StoryIndexGeneratorOptions } from './StoryIndexGenerator';
import { StoryIndexGenerator } from './StoryIndexGenerator';
import { csfIndexer } from '../presets/common-preset';
jest.mock('watchpack');
jest.mock('lodash/debounce');
jest.mock('@storybook/node-logger');
const workingDir = path.join(__dirname, '__mockdata__');
const normalizedStories = [
normalizeStoriesEntry(
{
titlePrefix: '',
directory: './src',
files: '**/*.stories.@(ts|js|mjs|jsx)',
},
{ workingDir, configDir: workingDir }
),
normalizeStoriesEntry(
{
titlePrefix: '',
directory: './src',
files: '**/*.mdx',
},
{ workingDir, configDir: workingDir }
),
];
const getInitializedStoryIndexGenerator = async (
overrides: any = {},
inputNormalizedStories = normalizedStories
) => {
const options: StoryIndexGeneratorOptions = {
storyIndexers: [],
indexers: [csfIndexer, createStoriesMdxIndexer(false)],
configDir: workingDir,
workingDir,
storiesV2Compatibility: false,
storyStoreV7: true,
docs: { defaultName: 'docs', autodocs: false },
...overrides,
};
const generator = new StoryIndexGenerator(inputNormalizedStories, options);
await generator.initialize();
return generator;
};
describe('useStoriesJson', () => {
const use = jest.fn();
const router: Router = { use } as any;
const send = jest.fn();
const write = jest.fn();
const response: Response = {
header: jest.fn(),
send,
status: jest.fn(),
setHeader: jest.fn(),
flushHeaders: jest.fn(),
write,
flush: jest.fn(),
end: jest.fn(),
on: jest.fn(),
} as any;
beforeEach(async () => {
use.mockClear();
send.mockClear();
write.mockClear();
(debounce as jest.Mock).mockImplementation((cb) => cb);
});
const request: Request = {
headers: { accept: 'application/json' },
} as any;
describe('JSON endpoint', () => {
it('scans and extracts index', async () => {
const mockServerChannel = { emit: jest.fn() } as any as ServerChannel;
useStoriesJson({
router,
serverChannel: mockServerChannel,
workingDir,
normalizedStories,
initializedStoryIndexGenerator: getInitializedStoryIndexGenerator(),
});
expect(use).toHaveBeenCalledTimes(2);
const route = use.mock.calls[0][1];
await route(request, response);
expect(send).toHaveBeenCalledTimes(1);
expect(JSON.parse(send.mock.calls[0][0])).toMatchInlineSnapshot(`
Object {
"entries": Object {
"a--metaof": Object {
"id": "a--metaof",
"importPath": "./src/docs2/MetaOf.mdx",
"name": "MetaOf",
"storiesImports": Array [
"./src/A.stories.js",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "A",
"type": "docs",
},
"a--second-docs": Object {
"id": "a--second-docs",
"importPath": "./src/docs2/SecondMetaOf.mdx",
"name": "Second Docs",
"storiesImports": Array [
"./src/A.stories.js",
],
"tags": Array [
"attached-mdx",
"docs",
],
"title": "A",
"type": "docs",
},
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"name": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
"type": "story",
},
"b--story-one": Object {
"id": "b--story-one",
"importPath": "./src/B.stories.ts",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "B",
"type": "story",
},
"d--story-one": Object {
"id": "d--story-one",
"importPath": "./src/D.stories.jsx",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "D",
"type": "story",
},
"docs2-componentreference--docs": Object {
"id": "docs2-componentreference--docs",
"importPath": "./src/docs2/ComponentReference.mdx",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "docs2/ComponentReference",
"type": "docs",
},
"docs2-notitle--docs": Object {
"id": "docs2-notitle--docs",
"importPath": "./src/docs2/NoTitle.mdx",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "docs2/NoTitle",
"type": "docs",
},
"docs2-yabbadabbadooo--docs": Object {
"id": "docs2-yabbadabbadooo--docs",
"importPath": "./src/docs2/Title.mdx",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "docs2/Yabbadabbadooo",
"type": "docs",
},
"first-nested-deeply-f--story-one": Object {
"id": "first-nested-deeply-f--story-one",
"importPath": "./src/first-nested/deeply/F.stories.js",
"name": "Story One",
"tags": Array [
"story",
],
"title": "first-nested/deeply/F",
"type": "story",
},
"h--story-one": Object {
"id": "h--story-one",
"importPath": "./src/H.stories.mjs",
"name": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "H",
"type": "story",
},
"nested-button--story-one": Object {
"id": "nested-button--story-one",
"importPath": "./src/nested/Button.stories.ts",
"name": "Story One",
"tags": Array [
"component-tag",
"story",
],
"title": "nested/Button",
"type": "story",
},
"nested-page--docs": Object {
"id": "nested-page--docs",
"importPath": "./src/nested/Page.stories.mdx",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"stories-mdx",
"docs",
],
"title": "nested/Page",
"type": "docs",
},
"nested-page--story-one": Object {
"id": "nested-page--story-one",
"importPath": "./src/nested/Page.stories.mdx",
"name": "StoryOne",
"tags": Array [
"stories-mdx",
"story",
],
"title": "nested/Page",
"type": "story",
},
"second-nested-g--story-one": Object {
"id": "second-nested-g--story-one",
"importPath": "./src/second-nested/G.stories.ts",
"name": "Story One",
"tags": Array [
"story",
],
"title": "second-nested/G",
"type": "story",
},
},
"v": 4,
}
`);
});
it('scans and extracts stories v3', async () => {
const mockServerChannel = { emit: jest.fn() } as any as ServerChannel;
useStoriesJson({
router,
initializedStoryIndexGenerator: getInitializedStoryIndexGenerator(),
workingDir,
serverChannel: mockServerChannel,
normalizedStories,
});
expect(use).toHaveBeenCalledTimes(2);
const route = use.mock.calls[1][1];
await route(request, response);
expect(send).toHaveBeenCalledTimes(1);
expect(JSON.parse(send.mock.calls[0][0])).toMatchInlineSnapshot(`
Object {
"stories": Object {
"a--metaof": Object {
"id": "a--metaof",
"importPath": "./src/docs2/MetaOf.mdx",
"kind": "A",
"name": "MetaOf",
"parameters": Object {
"__id": "a--metaof",
"docsOnly": true,
"fileName": "./src/docs2/MetaOf.mdx",
},
"storiesImports": Array [
"./src/A.stories.js",
],
"story": "MetaOf",
"tags": Array [
"attached-mdx",
"docs",
],
"title": "A",
},
"a--second-docs": Object {
"id": "a--second-docs",
"importPath": "./src/docs2/SecondMetaOf.mdx",
"kind": "A",
"name": "Second Docs",
"parameters": Object {
"__id": "a--second-docs",
"docsOnly": true,
"fileName": "./src/docs2/SecondMetaOf.mdx",
},
"storiesImports": Array [
"./src/A.stories.js",
],
"story": "Second Docs",
"tags": Array [
"attached-mdx",
"docs",
],
"title": "A",
},
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"kind": "A",
"name": "Story One",
"parameters": Object {
"__id": "a--story-one",
"docsOnly": false,
"fileName": "./src/A.stories.js",
},
"story": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
},
"b--story-one": Object {
"id": "b--story-one",
"importPath": "./src/B.stories.ts",
"kind": "B",
"name": "Story One",
"parameters": Object {
"__id": "b--story-one",
"docsOnly": false,
"fileName": "./src/B.stories.ts",
},
"story": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "B",
},
"d--story-one": Object {
"id": "d--story-one",
"importPath": "./src/D.stories.jsx",
"kind": "D",
"name": "Story One",
"parameters": Object {
"__id": "d--story-one",
"docsOnly": false,
"fileName": "./src/D.stories.jsx",
},
"story": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "D",
},
"docs2-componentreference--docs": Object {
"id": "docs2-componentreference--docs",
"importPath": "./src/docs2/ComponentReference.mdx",
"kind": "docs2/ComponentReference",
"name": "docs",
"parameters": Object {
"__id": "docs2-componentreference--docs",
"docsOnly": true,
"fileName": "./src/docs2/ComponentReference.mdx",
},
"storiesImports": Array [],
"story": "docs",
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "docs2/ComponentReference",
},
"docs2-notitle--docs": Object {
"id": "docs2-notitle--docs",
"importPath": "./src/docs2/NoTitle.mdx",
"kind": "docs2/NoTitle",
"name": "docs",
"parameters": Object {
"__id": "docs2-notitle--docs",
"docsOnly": true,
"fileName": "./src/docs2/NoTitle.mdx",
},
"storiesImports": Array [],
"story": "docs",
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "docs2/NoTitle",
},
"docs2-yabbadabbadooo--docs": Object {
"id": "docs2-yabbadabbadooo--docs",
"importPath": "./src/docs2/Title.mdx",
"kind": "docs2/Yabbadabbadooo",
"name": "docs",
"parameters": Object {
"__id": "docs2-yabbadabbadooo--docs",
"docsOnly": true,
"fileName": "./src/docs2/Title.mdx",
},
"storiesImports": Array [],
"story": "docs",
"tags": Array [
"unattached-mdx",
"docs",
],
"title": "docs2/Yabbadabbadooo",
},
"first-nested-deeply-f--story-one": Object {
"id": "first-nested-deeply-f--story-one",
"importPath": "./src/first-nested/deeply/F.stories.js",
"kind": "first-nested/deeply/F",
"name": "Story One",
"parameters": Object {
"__id": "first-nested-deeply-f--story-one",
"docsOnly": false,
"fileName": "./src/first-nested/deeply/F.stories.js",
},
"story": "Story One",
"tags": Array [
"story",
],
"title": "first-nested/deeply/F",
},
"h--story-one": Object {
"id": "h--story-one",
"importPath": "./src/H.stories.mjs",
"kind": "H",
"name": "Story One",
"parameters": Object {
"__id": "h--story-one",
"docsOnly": false,
"fileName": "./src/H.stories.mjs",
},
"story": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "H",
},
"nested-button--story-one": Object {
"id": "nested-button--story-one",
"importPath": "./src/nested/Button.stories.ts",
"kind": "nested/Button",
"name": "Story One",
"parameters": Object {
"__id": "nested-button--story-one",
"docsOnly": false,
"fileName": "./src/nested/Button.stories.ts",
},
"story": "Story One",
"tags": Array [
"component-tag",
"story",
],
"title": "nested/Button",
},
"nested-page--docs": Object {
"id": "nested-page--docs",
"importPath": "./src/nested/Page.stories.mdx",
"kind": "nested/Page",
"name": "docs",
"parameters": Object {
"__id": "nested-page--docs",
"docsOnly": true,
"fileName": "./src/nested/Page.stories.mdx",
},
"storiesImports": Array [],
"story": "docs",
"tags": Array [
"stories-mdx",
"docs",
],
"title": "nested/Page",
},
"nested-page--story-one": Object {
"id": "nested-page--story-one",
"importPath": "./src/nested/Page.stories.mdx",
"kind": "nested/Page",
"name": "StoryOne",
"parameters": Object {
"__id": "nested-page--story-one",
"docsOnly": false,
"fileName": "./src/nested/Page.stories.mdx",
},
"story": "StoryOne",
"tags": Array [
"stories-mdx",
"story",
],
"title": "nested/Page",
},
"second-nested-g--story-one": Object {
"id": "second-nested-g--story-one",
"importPath": "./src/second-nested/G.stories.ts",
"kind": "second-nested/G",
"name": "Story One",
"parameters": Object {
"__id": "second-nested-g--story-one",
"docsOnly": false,
"fileName": "./src/second-nested/G.stories.ts",
},
"story": "Story One",
"tags": Array [
"story",
],
"title": "second-nested/G",
},
},
"v": 3,
}
`);
});
it('scans and extracts stories v2', async () => {
const mockServerChannel = { emit: jest.fn() } as any as ServerChannel;
useStoriesJson({
router,
initializedStoryIndexGenerator: getInitializedStoryIndexGenerator({
storiesV2Compatibility: true,
}),
workingDir,
serverChannel: mockServerChannel,
normalizedStories,
});
expect(use).toHaveBeenCalledTimes(2);
const route = use.mock.calls[1][1];
await route(request, response);
expect(send).toHaveBeenCalledTimes(1);
expect(JSON.parse(send.mock.calls[0][0])).toMatchInlineSnapshot(`
Object {
"stories": Object {
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"kind": "A",
"name": "Story One",
"parameters": Object {
"__id": "a--story-one",
"docsOnly": false,
"fileName": "./src/A.stories.js",
},
"story": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
},
"b--story-one": Object {
"id": "b--story-one",
"importPath": "./src/B.stories.ts",
"kind": "B",
"name": "Story One",
"parameters": Object {
"__id": "b--story-one",
"docsOnly": false,
"fileName": "./src/B.stories.ts",
},
"story": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "B",
},
"d--story-one": Object {
"id": "d--story-one",
"importPath": "./src/D.stories.jsx",
"kind": "D",
"name": "Story One",
"parameters": Object {
"__id": "d--story-one",
"docsOnly": false,
"fileName": "./src/D.stories.jsx",
},
"story": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "D",
},
"first-nested-deeply-f--story-one": Object {
"id": "first-nested-deeply-f--story-one",
"importPath": "./src/first-nested/deeply/F.stories.js",
"kind": "first-nested/deeply/F",
"name": "Story One",
"parameters": Object {
"__id": "first-nested-deeply-f--story-one",
"docsOnly": false,
"fileName": "./src/first-nested/deeply/F.stories.js",
},
"story": "Story One",
"tags": Array [
"story",
],
"title": "first-nested/deeply/F",
},
"h--story-one": Object {
"id": "h--story-one",
"importPath": "./src/H.stories.mjs",
"kind": "H",
"name": "Story One",
"parameters": Object {
"__id": "h--story-one",
"docsOnly": false,
"fileName": "./src/H.stories.mjs",
},
"story": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "H",
},
"nested-button--story-one": Object {
"id": "nested-button--story-one",
"importPath": "./src/nested/Button.stories.ts",
"kind": "nested/Button",
"name": "Story One",
"parameters": Object {
"__id": "nested-button--story-one",
"docsOnly": false,
"fileName": "./src/nested/Button.stories.ts",
},
"story": "Story One",
"tags": Array [
"component-tag",
"story",
],
"title": "nested/Button",
},
"nested-page--story-one": Object {
"id": "nested-page--story-one",
"importPath": "./src/nested/Page.stories.mdx",
"kind": "nested/Page",
"name": "StoryOne",
"parameters": Object {
"__id": "nested-page--story-one",
"docsOnly": false,
"fileName": "./src/nested/Page.stories.mdx",
},
"story": "StoryOne",
"tags": Array [
"stories-mdx",
"story",
],
"title": "nested/Page",
},
"second-nested-g--story-one": Object {
"id": "second-nested-g--story-one",
"importPath": "./src/second-nested/G.stories.ts",
"kind": "second-nested/G",
"name": "Story One",
"parameters": Object {
"__id": "second-nested-g--story-one",
"docsOnly": false,
"fileName": "./src/second-nested/G.stories.ts",
},
"story": "Story One",
"tags": Array [
"story",
],
"title": "second-nested/G",
},
},
"v": 3,
}
`);
});
it('disallows .mdx files without storyStoreV7', async () => {
const mockServerChannel = { emit: jest.fn() } as any as ServerChannel;
useStoriesJson({
router,
initializedStoryIndexGenerator: getInitializedStoryIndexGenerator({
storyStoreV7: false,
}),
workingDir,
serverChannel: mockServerChannel,
normalizedStories,
});
expect(use).toHaveBeenCalledTimes(2);
const route = use.mock.calls[1][1];
await route(request, response);
expect(send).toHaveBeenCalledTimes(1);
expect(send.mock.calls[0][0]).toMatchInlineSnapshot(`
"Unable to index files:
- ./src/docs2/ComponentReference.mdx: Invariant failed: You cannot use \`.mdx\` files without using \`storyStoreV7\`.
- ./src/docs2/MetaOf.mdx: Invariant failed: You cannot use \`.mdx\` files without using \`storyStoreV7\`.
- ./src/docs2/NoTitle.mdx: Invariant failed: You cannot use \`.mdx\` files without using \`storyStoreV7\`.
- ./src/docs2/SecondMetaOf.mdx: Invariant failed: You cannot use \`.mdx\` files without using \`storyStoreV7\`.
- ./src/docs2/Template.mdx: Invariant failed: You cannot use \`.mdx\` files without using \`storyStoreV7\`.
- ./src/docs2/Title.mdx: Invariant failed: You cannot use \`.mdx\` files without using \`storyStoreV7\`."
`);
});
it('allows disabling storyStoreV7 if no .mdx files are used', async () => {
const mockServerChannel = { emit: jest.fn() } as any as ServerChannel;
useStoriesJson({
router,
initializedStoryIndexGenerator: getInitializedStoryIndexGenerator(
{ storyStoreV7: false },
normalizedStories.slice(0, 1)
),
workingDir,
serverChannel: mockServerChannel,
normalizedStories,
});
expect(use).toHaveBeenCalledTimes(2);
const route = use.mock.calls[1][1];
await route(request, response);
expect(send).toHaveBeenCalledTimes(1);
expect(JSON.parse(send.mock.calls[0][0])).toMatchInlineSnapshot(`
Object {
"stories": Object {
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"kind": "A",
"name": "Story One",
"parameters": Object {
"__id": "a--story-one",
"docsOnly": false,
"fileName": "./src/A.stories.js",
},
"story": "Story One",
"tags": Array [
"component-tag",
"story-tag",
"story",
],
"title": "A",
},
"b--story-one": Object {
"id": "b--story-one",
"importPath": "./src/B.stories.ts",
"kind": "B",
"name": "Story One",
"parameters": Object {
"__id": "b--story-one",
"docsOnly": false,
"fileName": "./src/B.stories.ts",
},
"story": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "B",
},
"d--story-one": Object {
"id": "d--story-one",
"importPath": "./src/D.stories.jsx",
"kind": "D",
"name": "Story One",
"parameters": Object {
"__id": "d--story-one",
"docsOnly": false,
"fileName": "./src/D.stories.jsx",
},
"story": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "D",
},
"first-nested-deeply-f--story-one": Object {
"id": "first-nested-deeply-f--story-one",
"importPath": "./src/first-nested/deeply/F.stories.js",
"kind": "first-nested/deeply/F",
"name": "Story One",
"parameters": Object {
"__id": "first-nested-deeply-f--story-one",
"docsOnly": false,
"fileName": "./src/first-nested/deeply/F.stories.js",
},
"story": "Story One",
"tags": Array [
"story",
],
"title": "first-nested/deeply/F",
},
"h--story-one": Object {
"id": "h--story-one",
"importPath": "./src/H.stories.mjs",
"kind": "H",
"name": "Story One",
"parameters": Object {
"__id": "h--story-one",
"docsOnly": false,
"fileName": "./src/H.stories.mjs",
},
"story": "Story One",
"tags": Array [
"autodocs",
"story",
],
"title": "H",
},
"nested-button--story-one": Object {
"id": "nested-button--story-one",
"importPath": "./src/nested/Button.stories.ts",
"kind": "nested/Button",
"name": "Story One",
"parameters": Object {
"__id": "nested-button--story-one",
"docsOnly": false,
"fileName": "./src/nested/Button.stories.ts",
},
"story": "Story One",
"tags": Array [
"component-tag",
"story",
],
"title": "nested/Button",
},
"second-nested-g--story-one": Object {
"id": "second-nested-g--story-one",
"importPath": "./src/second-nested/G.stories.ts",
"kind": "second-nested/G",
"name": "Story One",
"parameters": Object {
"__id": "second-nested-g--story-one",
"docsOnly": false,
"fileName": "./src/second-nested/G.stories.ts",
},
"story": "Story One",
"tags": Array [
"story",
],
"title": "second-nested/G",
},
},
"v": 3,
}
`);
});
it('can handle simultaneous access', async () => {
const mockServerChannel = { emit: jest.fn() } as any as ServerChannel;
useStoriesJson({
router,
serverChannel: mockServerChannel,
workingDir,
normalizedStories,
initializedStoryIndexGenerator: getInitializedStoryIndexGenerator(),
});
expect(use).toHaveBeenCalledTimes(2);
const route = use.mock.calls[0][1];
const firstPromise = route(request, response);
const secondResponse = { ...response, send: jest.fn(), status: jest.fn() };
const secondPromise = route(request, secondResponse);
await Promise.all([firstPromise, secondPromise]);
expect(send).toHaveBeenCalledTimes(1);
expect(response.status).not.toEqual(500);
expect(secondResponse.send).toHaveBeenCalledTimes(1);
expect(secondResponse.status).not.toEqual(500);
});
});
describe('SSE endpoint', () => {
beforeEach(() => {
use.mockClear();
send.mockClear();
});
it('sends invalidate events', async () => {
const mockServerChannel = { emit: jest.fn() } as any as ServerChannel;
useStoriesJson({
router,
serverChannel: mockServerChannel,
workingDir,
normalizedStories,
initializedStoryIndexGenerator: getInitializedStoryIndexGenerator(),
});
expect(use).toHaveBeenCalledTimes(2);
const route = use.mock.calls[0][1];
await route(request, response);
expect(write).not.toHaveBeenCalled();
expect(Watchpack).toHaveBeenCalledTimes(1);
const watcher = Watchpack.mock.instances[0];
expect(watcher.watch).toHaveBeenCalledWith({ directories: ['./src'] });
expect(watcher.on).toHaveBeenCalledTimes(2);
const onChange = watcher.on.mock.calls[0][1];
await onChange('src/nested/Button.stories.ts');
expect(mockServerChannel.emit).toHaveBeenCalledTimes(1);
expect(mockServerChannel.emit).toHaveBeenCalledWith(STORY_INDEX_INVALIDATED);
});
it('only sends one invalidation when multiple event listeners are listening', async () => {
const mockServerChannel = { emit: jest.fn() } as any as ServerChannel;
useStoriesJson({
router,
serverChannel: mockServerChannel,
workingDir,
normalizedStories,
initializedStoryIndexGenerator: getInitializedStoryIndexGenerator(),
});
expect(use).toHaveBeenCalledTimes(2);
const route = use.mock.calls[0][1];
// Don't wait for the first request here before starting the second
await Promise.all([
route(request, response),
route(request, { ...response, write: jest.fn() }),
]);
expect(write).not.toHaveBeenCalled();
expect(Watchpack).toHaveBeenCalledTimes(1);
const watcher = Watchpack.mock.instances[0];
expect(watcher.watch).toHaveBeenCalledWith({ directories: ['./src'] });
expect(watcher.on).toHaveBeenCalledTimes(2);
const onChange = watcher.on.mock.calls[0][1];
await onChange('src/nested/Button.stories.ts');
expect(mockServerChannel.emit).toHaveBeenCalledTimes(1);
expect(mockServerChannel.emit).toHaveBeenCalledWith(STORY_INDEX_INVALIDATED);
});
it('debounces invalidation events', async () => {
(debounce as jest.Mock).mockImplementation(jest.requireActual('lodash/debounce.js') as any);
const mockServerChannel = { emit: jest.fn() } as any as ServerChannel;
useStoriesJson({
router,
serverChannel: mockServerChannel,
workingDir,
normalizedStories,
initializedStoryIndexGenerator: getInitializedStoryIndexGenerator(),
});
expect(use).toHaveBeenCalledTimes(2);
const route = use.mock.calls[0][1];
await route(request, response);
expect(write).not.toHaveBeenCalled();
expect(Watchpack).toHaveBeenCalledTimes(1);
const watcher = Watchpack.mock.instances[0];
expect(watcher.watch).toHaveBeenCalledWith({ directories: ['./src'] });
expect(watcher.on).toHaveBeenCalledTimes(2);
const onChange = watcher.on.mock.calls[0][1];
await onChange('src/nested/Button.stories.ts');
await onChange('src/nested/Button.stories.ts');
await onChange('src/nested/Button.stories.ts');
await onChange('src/nested/Button.stories.ts');
await onChange('src/nested/Button.stories.ts');
expect(mockServerChannel.emit).toHaveBeenCalledTimes(1);
expect(mockServerChannel.emit).toHaveBeenCalledWith(STORY_INDEX_INVALIDATED);
await new Promise((r) => setTimeout(r, 2 * DEBOUNCE));
expect(mockServerChannel.emit).toHaveBeenCalledTimes(2);
});
});
});
describe('convertToIndexV3', () => {
it('converts v7 index.json to v6 stories.json', () => {
const indexJson: StoryIndex = {
v: 4,
entries: {
'a--docs': {
id: 'a--docs',
importPath: './src/docs2/MetaOf.mdx',
name: 'docs',
storiesImports: ['./src/A.stories.js'],
title: 'A',
type: 'docs',
},
'a--story-one': {
id: 'a--story-one',
importPath: './src/A.stories.js',
name: 'Story One',
title: 'A',
type: 'story',
},
'b--story-one': {
id: 'b--story-one',
importPath: './src/B.stories.ts',
name: 'Story One',
title: 'B',
type: 'story',
},
},
};
expect(convertToIndexV3(indexJson)).toMatchInlineSnapshot(`
Object {
"stories": Object {
"a--docs": Object {
"id": "a--docs",
"importPath": "./src/docs2/MetaOf.mdx",
"kind": "A",
"name": "docs",
"parameters": Object {
"__id": "a--docs",
"docsOnly": true,
"fileName": "./src/docs2/MetaOf.mdx",
},
"storiesImports": Array [
"./src/A.stories.js",
],
"story": "docs",
"title": "A",
},
"a--story-one": Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"kind": "A",
"name": "Story One",
"parameters": Object {
"__id": "a--story-one",
"docsOnly": false,
"fileName": "./src/A.stories.js",
},
"story": "Story One",
"title": "A",
},
"b--story-one": Object {
"id": "b--story-one",
"importPath": "./src/B.stories.ts",
"kind": "B",
"name": "Story One",
"parameters": Object {
"__id": "b--story-one",
"docsOnly": false,
"fileName": "./src/B.stories.ts",
},
"story": "Story One",
"title": "B",
},
},
"v": 3,
}
`);
});
});
|
857 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-server/src | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils/summarizeIndex.test.ts | import { isPageStory, summarizeIndex } from './summarizeIndex';
describe('isPageStory', () => {
describe('true positives', () => {
it.each(['pages/login', 'screens/login', 'components/LoginPage', 'components/LoginScreen'])(
'%s',
(title) => {
expect(isPageStory(title)).toBe(true);
}
);
});
describe('false positives', () => {
it.each([
'components/PagerStatus',
'components/DefectScreener',
'addons/docs/docspage/autoplay',
])('%s', (title) => {
expect(isPageStory(title)).toBe(true);
});
});
describe('true negatives', () => {
it.each(['atoms/Button', 'components/Slider'])('%s', (title) => {
expect(isPageStory(title)).toBe(false);
});
});
describe('false negatives', () => {
it.each(['flows/login', 'login-flow/forgot password'])('%s', (title) => {
expect(isPageStory(title)).toBe(false);
});
});
});
describe('summarizeIndex', () => {
it('example stories', () => {
expect(
summarizeIndex({
v: 4,
entries: {
'example-introduction--docs': {
id: 'example-introduction--docs',
title: 'Example/Introduction',
name: 'Docs',
importPath: './src/stories/Introduction.mdx',
storiesImports: [],
type: 'docs',
tags: ['docs'],
},
'example-button--docs': {
id: 'example-button--docs',
title: 'Example/Button',
name: 'Docs',
importPath: './src/stories/Button.stories.ts',
type: 'docs',
tags: ['autodocs', 'docs'],
storiesImports: [],
},
'example-button--primary': {
id: 'example-button--primary',
title: 'Example/Button',
name: 'Primary',
importPath: './src/stories/Button.stories.ts',
tags: ['autodocs', 'story'],
type: 'story',
},
'example-button--secondary': {
id: 'example-button--secondary',
title: 'Example/Button',
name: 'Secondary',
importPath: './src/stories/Button.stories.ts',
tags: ['autodocs', 'story'],
type: 'story',
},
'example-button--large': {
id: 'example-button--large',
title: 'Example/Button',
name: 'Large',
importPath: './src/stories/Button.stories.ts',
tags: ['autodocs', 'story'],
type: 'story',
},
'example-button--small': {
id: 'example-button--small',
title: 'Example/Button',
name: 'Small',
importPath: './src/stories/Button.stories.ts',
tags: ['autodocs', 'story'],
type: 'story',
},
'example-header--docs': {
id: 'example-header--docs',
title: 'Example/Header',
name: 'Docs',
importPath: './src/stories/Header.stories.ts',
type: 'docs',
tags: ['autodocs', 'docs'],
storiesImports: [],
},
'example-header--logged-in': {
id: 'example-header--logged-in',
title: 'Example/Header',
name: 'Logged In',
importPath: './src/stories/Header.stories.ts',
tags: ['autodocs', 'story'],
type: 'story',
},
'example-header--logged-out': {
id: 'example-header--logged-out',
title: 'Example/Header',
name: 'Logged Out',
importPath: './src/stories/Header.stories.ts',
tags: ['autodocs', 'story'],
type: 'story',
},
'example-page--logged-out': {
id: 'example-page--logged-out',
title: 'Example/Page',
name: 'Logged Out',
importPath: './src/stories/Page.stories.ts',
tags: ['story'],
type: 'story',
},
'example-page--logged-in': {
id: 'example-page--logged-in',
title: 'Example/Page',
name: 'Logged In',
importPath: './src/stories/Page.stories.ts',
tags: ['play-fn', 'story'],
type: 'story',
},
},
})
).toMatchInlineSnapshot(`
Object {
"autodocsCount": 0,
"componentCount": 0,
"exampleDocsCount": 3,
"exampleStoryCount": 8,
"mdxCount": 0,
"onboardingDocsCount": 0,
"onboardingStoryCount": 0,
"pageStoryCount": 0,
"playStoryCount": 0,
"storiesMdxCount": 0,
"storyCount": 0,
"version": 4,
}
`);
});
it('onboarding stories', () => {
expect(
summarizeIndex({
v: 4,
entries: {
'example-introduction--docs': {
id: 'example-introduction--docs',
title: 'Example/Introduction',
name: 'Docs',
importPath: './src/stories/Introduction.mdx',
storiesImports: [],
type: 'docs',
tags: ['docs'],
},
'example-button--docs': {
id: 'example-button--docs',
title: 'Example/Button',
name: 'Docs',
importPath: './src/stories/Button.stories.ts',
type: 'docs',
tags: ['autodocs', 'docs'],
storiesImports: [],
},
'example-button--primary': {
id: 'example-button--primary',
title: 'Example/Button',
name: 'Primary',
importPath: './src/stories/Button.stories.ts',
tags: ['autodocs', 'story'],
type: 'story',
},
'example-button--warning': {
id: 'example-button--warning',
title: 'Example/Button',
name: 'Warning',
importPath: './src/stories/Button.stories.ts',
tags: ['autodocs', 'story'],
type: 'story',
},
},
})
).toMatchInlineSnapshot(`
Object {
"autodocsCount": 0,
"componentCount": 0,
"exampleDocsCount": 2,
"exampleStoryCount": 1,
"mdxCount": 0,
"onboardingDocsCount": 0,
"onboardingStoryCount": 1,
"pageStoryCount": 0,
"playStoryCount": 0,
"storiesMdxCount": 0,
"storyCount": 0,
"version": 4,
}
`);
});
it('user stories', () => {
expect(
summarizeIndex({
v: 4,
entries: {
'stories-renderers-react-errors--story-contains-unrenderable': {
id: 'stories-renderers-react-errors--story-contains-unrenderable',
title: 'stories/renderers/react/errors',
name: 'Story Contains Unrenderable',
importPath: './src/stories/renderers/react/errors.stories.tsx',
tags: ['story'],
type: 'story',
},
'stories-renderers-react-hooks--basic': {
id: 'stories-renderers-react-hooks--basic',
title: 'stories/renderers/react/hooks',
name: 'Basic',
importPath: './src/stories/renderers/react/hooks.stories.tsx',
tags: ['story'],
type: 'story',
},
'stories-renderers-react-js-argtypes--js-class-component': {
id: 'stories-renderers-react-js-argtypes--js-class-component',
title: 'stories/renderers/react/js-argtypes',
name: 'Js Class Component',
importPath: './src/stories/renderers/react/js-argtypes.stories.jsx',
tags: ['story'],
type: 'story',
},
'stories-renderers-react-js-argtypes--js-function-component': {
id: 'stories-renderers-react-js-argtypes--js-function-component',
title: 'stories/renderers/react/js-argtypes',
name: 'Js Function Component',
importPath: './src/stories/renderers/react/js-argtypes.stories.jsx',
tags: ['story'],
type: 'story',
},
},
})
).toMatchInlineSnapshot(`
Object {
"autodocsCount": 0,
"componentCount": 3,
"exampleDocsCount": 0,
"exampleStoryCount": 0,
"mdxCount": 0,
"onboardingDocsCount": 0,
"onboardingStoryCount": 0,
"pageStoryCount": 0,
"playStoryCount": 0,
"storiesMdxCount": 0,
"storyCount": 4,
"version": 4,
}
`);
});
it('pages', () => {
expect(
summarizeIndex({
v: 4,
entries: {
'example-page--logged-out': {
id: 'example-page--logged-out',
title: 'Example/Page',
name: 'Logged Out',
importPath: './src/stories/Page.stories.ts',
tags: ['story'],
type: 'story',
},
'example-page--logged-in': {
id: 'example-page--logged-in',
title: 'Example/Page',
name: 'Logged In',
importPath: './src/stories/Page.stories.ts',
tags: ['play-fn', 'story'],
type: 'story',
},
'addons-docs-docspage-autoplay--docs': {
id: 'addons-docs-docspage-autoplay--docs',
title: 'addons/docs/docspage/autoplay',
name: 'Docs',
importPath: './template-stories/addons/docs/docspage/autoplay.stories.ts',
type: 'docs',
tags: ['autodocs', 'docs'],
storiesImports: [],
},
'addons-docs-docspage-autoplay--no-autoplay': {
id: 'addons-docs-docspage-autoplay--no-autoplay',
title: 'addons/docs/docspage/autoplay',
name: 'No Autoplay',
importPath: './template-stories/addons/docs/docspage/autoplay.stories.ts',
tags: ['play-fn', 'story'],
type: 'story',
},
},
})
).toMatchInlineSnapshot(`
Object {
"autodocsCount": 1,
"componentCount": 1,
"exampleDocsCount": 0,
"exampleStoryCount": 2,
"mdxCount": 0,
"onboardingDocsCount": 0,
"onboardingStoryCount": 0,
"pageStoryCount": 1,
"playStoryCount": 1,
"storiesMdxCount": 0,
"storyCount": 1,
"version": 4,
}
`);
});
it('storiesMdx', () => {
expect(
summarizeIndex({
v: 4,
entries: {
'stories-renderers-react-react-mdx--docs': {
id: 'stories-renderers-react-react-mdx--docs',
title: 'stories/renderers/react/react-mdx',
name: 'Docs',
importPath: './src/stories/renderers/react/react-mdx.stories.mdx',
type: 'docs',
tags: ['stories-mdx', 'docs'],
storiesImports: [],
},
'stories-renderers-react-react-mdx--primary': {
id: 'stories-renderers-react-react-mdx--primary',
title: 'stories/renderers/react/react-mdx',
name: 'Primary',
importPath: './src/stories/renderers/react/react-mdx.stories.mdx',
tags: ['stories-mdx', 'story'],
type: 'story',
},
'stories-renderers-react-react-mdx--secondary': {
id: 'stories-renderers-react-react-mdx--secondary',
title: 'stories/renderers/react/react-mdx',
name: 'Secondary',
importPath: './src/stories/renderers/react/react-mdx.stories.mdx',
tags: ['stories-mdx', 'story'],
type: 'story',
},
'stories-renderers-react-react-mdx--from-template': {
id: 'stories-renderers-react-react-mdx--from-template',
title: 'stories/renderers/react/react-mdx',
name: 'From Template',
importPath: './src/stories/renderers/react/react-mdx.stories.mdx',
tags: ['stories-mdx', 'story'],
type: 'story',
},
},
})
).toMatchInlineSnapshot(`
Object {
"autodocsCount": 0,
"componentCount": 1,
"exampleDocsCount": 0,
"exampleStoryCount": 0,
"mdxCount": 0,
"onboardingDocsCount": 0,
"onboardingStoryCount": 0,
"pageStoryCount": 0,
"playStoryCount": 0,
"storiesMdxCount": 1,
"storyCount": 3,
"version": 4,
}
`);
});
it('autodocs', () => {
expect(
summarizeIndex({
v: 4,
entries: {
'example-button--docs': {
id: 'example-button--docs',
title: 'Example/Button',
name: 'Docs',
importPath: './src/stories/Button.stories.ts',
type: 'docs',
tags: ['autodocs', 'docs'],
storiesImports: [],
},
'example-button--large': {
id: 'example-button--large',
title: 'Example/Button',
name: 'Large',
importPath: './src/stories/Button.stories.ts',
tags: ['autodocs', 'story'],
type: 'story',
},
'example-button--small': {
id: 'example-button--small',
title: 'Example/Button',
name: 'Small',
importPath: './src/stories/Button.stories.ts',
tags: ['autodocs', 'story'],
type: 'story',
},
'lib-preview-api-shortcuts--docs': {
id: 'lib-preview-api-shortcuts--docs',
title: 'lib/preview-api/shortcuts',
name: 'Docs',
importPath: './template-stories/lib/preview-api/shortcuts.stories.ts',
type: 'docs',
tags: ['autodocs', 'docs'],
storiesImports: [],
},
},
})
).toMatchInlineSnapshot(`
Object {
"autodocsCount": 1,
"componentCount": 0,
"exampleDocsCount": 1,
"exampleStoryCount": 2,
"mdxCount": 0,
"onboardingDocsCount": 0,
"onboardingStoryCount": 0,
"pageStoryCount": 0,
"playStoryCount": 0,
"storiesMdxCount": 0,
"storyCount": 0,
"version": 4,
}
`);
});
it('mdx', () => {
expect(
summarizeIndex({
v: 4,
entries: {
'example-introduction--docs': {
id: 'example-introduction--docs',
title: 'Example/Introduction',
name: 'Docs',
importPath: './src/stories/Introduction.mdx',
storiesImports: [],
type: 'docs',
tags: ['docs'],
},
'addons-docs-docs2-notitle--docs': {
id: 'addons-docs-docs2-notitle--docs',
title: 'addons/docs/docs2/NoTitle',
name: 'Docs',
importPath: './template-stories/addons/docs/docs2/NoTitle.mdx',
storiesImports: [],
type: 'docs',
tags: ['docs'],
},
'addons-docs-yabbadabbadooo--docs': {
id: 'addons-docs-yabbadabbadooo--docs',
title: 'addons/docs/Yabbadabbadooo',
name: 'Docs',
importPath: './template-stories/addons/docs/docs2/Title.mdx',
storiesImports: [],
type: 'docs',
tags: ['docs'],
},
},
})
).toMatchInlineSnapshot(`
Object {
"autodocsCount": 0,
"componentCount": 0,
"exampleDocsCount": 1,
"exampleStoryCount": 0,
"mdxCount": 2,
"onboardingDocsCount": 0,
"onboardingStoryCount": 0,
"pageStoryCount": 0,
"playStoryCount": 0,
"storiesMdxCount": 0,
"storyCount": 0,
"version": 4,
}
`);
});
});
|
862 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-server/src | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils/watch-story-specifiers.test.ts | import { normalizeStoriesEntry } from '@storybook/core-common';
import path from 'path';
import Watchpack from 'watchpack';
import { watchStorySpecifiers } from './watch-story-specifiers';
jest.mock('watchpack');
describe('watchStorySpecifiers', () => {
const workingDir = path.join(__dirname, '__mockdata__');
const options = {
configDir: path.join(workingDir, '.storybook'),
workingDir,
};
let close: () => void;
afterEach(() => close?.());
it('watches basic globs', async () => {
const specifier = normalizeStoriesEntry('../src/**/*.stories.@(ts|js)', options);
const onInvalidate = jest.fn();
close = watchStorySpecifiers([specifier], { workingDir }, onInvalidate);
expect(Watchpack).toHaveBeenCalledTimes(1);
const watcher = Watchpack.mock.instances[0];
expect(watcher.watch).toHaveBeenCalledWith({ directories: ['./src'] });
expect(watcher.on).toHaveBeenCalledTimes(2);
const onChange = watcher.on.mock.calls[0][1];
const onRemove = watcher.on.mock.calls[1][1];
// File changed, matching
onInvalidate.mockClear();
await onChange('src/nested/Button.stories.ts', 1234);
expect(onInvalidate).toHaveBeenCalledWith(specifier, `./src/nested/Button.stories.ts`, false);
// File changed, NOT matching
onInvalidate.mockClear();
await onChange('src/nested/Button.ts', 1234);
expect(onInvalidate).not.toHaveBeenCalled();
// File removed, matching
onInvalidate.mockClear();
await onRemove('src/nested/Button.stories.ts');
expect(onInvalidate).toHaveBeenCalledWith(specifier, `./src/nested/Button.stories.ts`, true);
// File removed, NOT matching
onInvalidate.mockClear();
await onRemove('src/nested/Button.ts');
expect(onInvalidate).not.toHaveBeenCalled();
// File moved out, matching
onInvalidate.mockClear();
await onChange('src/nested/Button.stories.ts', null);
expect(onInvalidate).toHaveBeenCalledWith(specifier, `./src/nested/Button.stories.ts`, true);
// File renamed, matching
onInvalidate.mockClear();
await onChange('src/nested/Button.stories.ts', null);
await onChange('src/nested/Button-2.stories.ts', 1234);
expect(onInvalidate).toHaveBeenCalledWith(specifier, `./src/nested/Button.stories.ts`, true);
expect(onInvalidate).toHaveBeenCalledWith(specifier, `./src/nested/Button-2.stories.ts`, false);
});
it('scans directories when they are added', async () => {
const specifier = normalizeStoriesEntry('../src/**/*.stories.@(ts|js)', options);
const onInvalidate = jest.fn();
close = watchStorySpecifiers([specifier], { workingDir }, onInvalidate);
expect(Watchpack).toHaveBeenCalledTimes(1);
const watcher = Watchpack.mock.instances[0];
expect(watcher.watch).toHaveBeenCalledWith({ directories: ['./src'] });
expect(watcher.on).toHaveBeenCalledTimes(2);
const onChange = watcher.on.mock.calls[0][1];
onInvalidate.mockClear();
await onChange('src/nested', 1234);
expect(onInvalidate).toHaveBeenCalledWith(specifier, `./src/nested/Button.stories.ts`, false);
});
it('watches single file globs', async () => {
const specifier = normalizeStoriesEntry('../src/nested/Button.stories.mdx', options);
const onInvalidate = jest.fn();
close = watchStorySpecifiers([specifier], { workingDir }, onInvalidate);
expect(Watchpack).toHaveBeenCalledTimes(1);
const watcher = Watchpack.mock.instances[0];
expect(watcher.watch).toHaveBeenCalledWith({ directories: ['./src/nested'] });
expect(watcher.on).toHaveBeenCalledTimes(2);
const onChange = watcher.on.mock.calls[0][1];
const onRemove = watcher.on.mock.calls[1][1];
// File changed, matching
onInvalidate.mockClear();
await onChange('src/nested/Button.stories.mdx', 1234);
expect(onInvalidate).toHaveBeenCalledWith(specifier, `./src/nested/Button.stories.mdx`, false);
// File changed, NOT matching
onInvalidate.mockClear();
await onChange('src/nested/Button.mdx', 1234);
expect(onInvalidate).not.toHaveBeenCalled();
// File removed, matching
onInvalidate.mockClear();
await onRemove('src/nested/Button.stories.mdx');
expect(onInvalidate).toHaveBeenCalledWith(specifier, `./src/nested/Button.stories.mdx`, true);
// File removed, NOT matching
onInvalidate.mockClear();
await onRemove('src/nested/Button.mdx');
expect(onInvalidate).not.toHaveBeenCalled();
// File moved out, matching
onInvalidate.mockClear();
await onChange('src/nested/Button.stories.mdx', null);
expect(onInvalidate).toHaveBeenCalledWith(specifier, `./src/nested/Button.stories.mdx`, true);
});
it('multiplexes between two specifiers on the same directory', async () => {
const globSpecifier = normalizeStoriesEntry('../src/**/*.stories.@(ts|js)', options);
const fileSpecifier = normalizeStoriesEntry('../src/nested/Button.stories.mdx', options);
const onInvalidate = jest.fn();
close = watchStorySpecifiers([globSpecifier, fileSpecifier], { workingDir }, onInvalidate);
expect(Watchpack).toHaveBeenCalledTimes(1);
const watcher = Watchpack.mock.instances[0];
expect(watcher.watch).toHaveBeenCalledWith({ directories: ['./src', './src/nested'] });
expect(watcher.on).toHaveBeenCalledTimes(2);
const onChange = watcher.on.mock.calls[0][1];
onInvalidate.mockClear();
await onChange('src/nested/Button.stories.ts', 1234);
expect(onInvalidate).toHaveBeenCalledWith(
globSpecifier,
`./src/nested/Button.stories.ts`,
false
);
onInvalidate.mockClear();
await onChange('src/nested/Button.stories.mdx', 1234);
expect(onInvalidate).toHaveBeenCalledWith(
fileSpecifier,
`./src/nested/Button.stories.mdx`,
false
);
});
});
|
902 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils/__tests__/IndexingError.test.ts | import { IndexingError, MultipleIndexingError } from '../IndexingError';
it('formats single file errors', () => {
const error = new IndexingError('parse error', ['./stories/File.stories.ts']);
expect(error.toString()).toMatchInlineSnapshot(`"./stories/File.stories.ts: parse error"`);
});
it('formats multi file errors', () => {
const error = new IndexingError('Duplicate stories', [
'./stories/File.stories.ts',
'/path/to/other/File.stories.ts',
]);
expect(error.toString()).toMatchInlineSnapshot(
`"./stories/File.stories.ts,/path/to/other/File.stories.ts: Duplicate stories"`
);
});
describe('formatIndexingErrors', () => {
it('formats one error with trace', () => {
const stack = `Error: parse error
at Object.<anonymous> (/user/storybookjs/storybook/code/lib/core-server/src/utils/__tests__/IndexingError.test.ts:26:25)
at Promise.then.completed (/user/storybookjs/storybook/code/node_modules/jest-circus/build/utils.js:293:28)
at new Promise (<anonymous>)`;
const error = new IndexingError('parse error', ['./stories/File.stories.ts'], stack);
const multiError = new MultipleIndexingError([error]);
expect(multiError.toString()).toMatchInlineSnapshot(`
"Unable to index ./stories/File.stories.ts:
Error: parse error
at Object.<anonymous> (/user/storybookjs/storybook/code/lib/core-server/src/utils/__tests__/IndexingError.test.ts:26:25)
at Promise.then.completed (/user/storybookjs/storybook/code/node_modules/jest-circus/build/utils.js:293:28)
at new Promise (<anonymous>)"
`);
});
it('formats multiple errors without trace', () => {
const errors = [0, 1, 2].map((index) => {
return new IndexingError('parse error', [`./stories/File-${index}.stories.ts`]);
});
const multiError = new MultipleIndexingError(errors);
expect(multiError.toString()).toMatchInlineSnapshot(`
"Unable to index files:
- ./stories/File-0.stories.ts: parse error
- ./stories/File-1.stories.ts: parse error
- ./stories/File-2.stories.ts: parse error"
`);
});
});
|
903 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils/__tests__/autoName.test.ts | import { autoName } from '../autoName';
it('pulls name from named MDX files', () => {
expect(autoName('Conventions.mdx', 'Button.stories.mdx', 'Docs')).toEqual('Conventions');
});
it('falls back for default named MDX files', () => {
expect(autoName('Button.mdx', 'Button.stories.mdx', 'Docs')).toEqual('Docs');
});
|
904 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils/__tests__/index-extraction.test.ts | /// <reference types="@types/jest" />;
/**
* @jest-environment node
*/
import path from 'path';
import { normalizeStoriesEntry } from '@storybook/core-common';
import type { NormalizedStoriesSpecifier } from '@storybook/types';
import type { StoryIndexGeneratorOptions } from '../StoryIndexGenerator';
import { AUTODOCS_TAG, STORIES_MDX_TAG, StoryIndexGenerator } from '../StoryIndexGenerator';
jest.mock('@storybook/node-logger');
const options: StoryIndexGeneratorOptions = {
configDir: path.join(__dirname, '..', '__mockdata__'),
workingDir: path.join(__dirname, '..', '__mockdata__'),
storyIndexers: [],
indexers: [],
storiesV2Compatibility: false,
storyStoreV7: true,
docs: { defaultName: 'docs', autodocs: false },
};
describe('story extraction', () => {
it('extracts stories from full indexer inputs', async () => {
const relativePath = './src/A.stories.js';
const absolutePath = path.join(options.workingDir, relativePath);
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(relativePath, options);
const generator = new StoryIndexGenerator([specifier], {
...options,
indexers: [
{
test: /\.stories\.(m?js|ts)x?$/,
createIndex: async (fileName) => [
// properties identical to the auto-generated ones, eg. 'StoryOne' -> 'Story One'
{
type: 'story',
importPath: fileName,
exportName: 'StoryOne',
name: 'Story One',
title: 'A',
metaId: 'a',
tags: ['story-tag-from-indexer'],
__id: 'a--story-one',
},
// properties different from the auto-generated ones, eg. 'StoryOne' -> 'Another Story Name'
{
type: 'story',
importPath: fileName,
exportName: 'StoryOne',
name: 'Another Story Name',
title: 'Custom Title',
metaId: 'custom-id',
tags: ['story-tag-from-indexer'],
__id: 'some-fully-custom-id',
},
],
},
],
});
const result = await generator.extractStories(specifier, absolutePath);
expect(result).toMatchInlineSnapshot(`
Object {
"dependents": Array [],
"entries": Array [
Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"metaId": "a",
"name": "Story One",
"tags": Array [
"story-tag-from-indexer",
"story",
],
"title": "A",
"type": "story",
},
Object {
"id": "some-fully-custom-id",
"importPath": "./src/A.stories.js",
"metaId": "custom-id",
"name": "Another Story Name",
"tags": Array [
"story-tag-from-indexer",
"story",
],
"title": "Custom Title",
"type": "story",
},
],
"type": "stories",
}
`);
});
it('extracts stories from minimal indexer inputs', async () => {
const relativePath = './src/first-nested/deeply/F.stories.js';
const absolutePath = path.join(options.workingDir, relativePath);
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(relativePath, options);
const generator = new StoryIndexGenerator([specifier], {
...options,
indexers: [
{
test: /\.stories\.(m?js|ts)x?$/,
createIndex: async (fileName) => [
{
exportName: 'StoryOne',
importPath: fileName,
type: 'story',
},
],
},
],
});
const result = await generator.extractStories(specifier, absolutePath);
expect(result).toMatchInlineSnapshot(`
Object {
"dependents": Array [],
"entries": Array [
Object {
"id": "f--story-one",
"importPath": "./src/first-nested/deeply/F.stories.js",
"metaId": undefined,
"name": "Story One",
"tags": Array [
"story",
],
"title": "F",
"type": "story",
},
],
"type": "stories",
}
`);
});
it('auto-generates title from indexer inputs without title', async () => {
const relativePath = './src/first-nested/deeply/F.stories.js';
const absolutePath = path.join(options.workingDir, relativePath);
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(relativePath, options);
const generator = new StoryIndexGenerator([specifier], {
...options,
indexers: [
{
test: /\.stories\.(m?js|ts)x?$/,
createIndex: async (fileName) => [
{
exportName: 'StoryOne',
__id: 'a--story-one',
name: 'Story One',
metaId: 'a',
tags: ['story-tag-from-indexer'],
importPath: fileName,
type: 'story',
},
],
},
],
});
const result = await generator.extractStories(specifier, absolutePath);
expect(result).toMatchInlineSnapshot(`
Object {
"dependents": Array [],
"entries": Array [
Object {
"id": "a--story-one",
"importPath": "./src/first-nested/deeply/F.stories.js",
"metaId": "a",
"name": "Story One",
"tags": Array [
"story-tag-from-indexer",
"story",
],
"title": "F",
"type": "story",
},
],
"type": "stories",
}
`);
});
it('auto-generates name from indexer inputs without name', async () => {
const relativePath = './src/A.stories.js';
const absolutePath = path.join(options.workingDir, relativePath);
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(relativePath, options);
const generator = new StoryIndexGenerator([specifier], {
...options,
indexers: [
{
test: /\.stories\.(m?js|ts)x?$/,
createIndex: async (fileName) => [
{
exportName: 'StoryOne',
__id: 'a--story-one',
title: 'A',
metaId: 'a',
tags: ['story-tag-from-indexer'],
importPath: fileName,
type: 'story',
},
],
},
],
});
const result = await generator.extractStories(specifier, absolutePath);
expect(result).toMatchInlineSnapshot(`
Object {
"dependents": Array [],
"entries": Array [
Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"metaId": "a",
"name": "Story One",
"tags": Array [
"story-tag-from-indexer",
"story",
],
"title": "A",
"type": "story",
},
],
"type": "stories",
}
`);
});
it('auto-generates id', async () => {
const relativePath = './src/A.stories.js';
const absolutePath = path.join(options.workingDir, relativePath);
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(relativePath, options);
const generator = new StoryIndexGenerator([specifier], {
...options,
indexers: [
{
test: /\.stories\.(m?js|ts)x?$/,
createIndex: async (fileName) => [
// exportName + title -> id
{
exportName: 'StoryOne',
name: 'Story One',
title: 'A',
tags: ['story-tag-from-indexer'],
importPath: fileName,
type: 'story',
},
// exportName + custom title (ignoring custom name) -> id
{
exportName: 'StoryTwo',
name: 'Custom Name For Second Story',
title: 'Custom Title',
tags: ['story-tag-from-indexer'],
importPath: fileName,
type: 'story',
},
// exportName + custom metaId (ignoring custom title and name) -> id
{
exportName: 'StoryThree',
metaId: 'custom-meta-id',
title: 'Custom Title',
tags: ['story-tag-from-indexer'],
importPath: fileName,
type: 'story',
},
],
},
],
});
const result = await generator.extractStories(specifier, absolutePath);
expect(result).toMatchInlineSnapshot(`
Object {
"dependents": Array [],
"entries": Array [
Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"metaId": undefined,
"name": "Story One",
"tags": Array [
"story-tag-from-indexer",
"story",
],
"title": "A",
"type": "story",
},
Object {
"id": "custom-title--story-two",
"importPath": "./src/A.stories.js",
"metaId": undefined,
"name": "Custom Name For Second Story",
"tags": Array [
"story-tag-from-indexer",
"story",
],
"title": "Custom Title",
"type": "story",
},
Object {
"id": "custom-meta-id--story-three",
"importPath": "./src/A.stories.js",
"metaId": "custom-meta-id",
"name": "Story Three",
"tags": Array [
"story-tag-from-indexer",
"story",
],
"title": "Custom Title",
"type": "story",
},
],
"type": "stories",
}
`);
});
it('auto-generates id, title and name from exportName input', async () => {
const relativePath = './src/A.stories.js';
const absolutePath = path.join(options.workingDir, relativePath);
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(relativePath, options);
const generator = new StoryIndexGenerator([specifier], {
...options,
indexers: [
{
test: /\.stories\.(m?js|ts)x?$/,
createIndex: async (fileName) => [
{
exportName: 'StoryOne',
tags: ['story-tag-from-indexer'],
importPath: fileName,
type: 'story',
},
],
},
],
});
const result = await generator.extractStories(specifier, absolutePath);
expect(result).toMatchInlineSnapshot(`
Object {
"dependents": Array [],
"entries": Array [
Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"metaId": undefined,
"name": "Story One",
"tags": Array [
"story-tag-from-indexer",
"story",
],
"title": "A",
"type": "story",
},
],
"type": "stories",
}
`);
});
});
describe('docs entries from story extraction', () => {
it('adds docs entry when autodocs is globally enabled', async () => {
const relativePath = './src/A.stories.js';
const absolutePath = path.join(options.workingDir, relativePath);
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(relativePath, options);
const generator = new StoryIndexGenerator([specifier], {
...options,
docs: { defaultName: 'docs', autodocs: true },
indexers: [
{
test: /\.stories\.(m?js|ts)x?$/,
createIndex: async (fileName) => [
{
exportName: 'StoryOne',
__id: 'a--story-one',
name: 'Story One',
title: 'A',
tags: ['story-tag-from-indexer'],
importPath: fileName,
type: 'story',
},
],
},
],
});
const result = await generator.extractStories(specifier, absolutePath);
expect(result).toMatchInlineSnapshot(`
Object {
"dependents": Array [],
"entries": Array [
Object {
"id": "a--docs",
"importPath": "./src/A.stories.js",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"story-tag-from-indexer",
"docs",
"autodocs",
],
"title": "A",
"type": "docs",
},
Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"metaId": undefined,
"name": "Story One",
"tags": Array [
"story-tag-from-indexer",
"story",
],
"title": "A",
"type": "story",
},
],
"type": "stories",
}
`);
});
it(`adds docs entry when autodocs is "tag" and an entry has the "${AUTODOCS_TAG}" tag`, async () => {
const relativePath = './src/A.stories.js';
const absolutePath = path.join(options.workingDir, relativePath);
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(relativePath, options);
const generator = new StoryIndexGenerator([specifier], {
...options,
docs: { defaultName: 'docs', autodocs: 'tag' },
indexers: [
{
test: /\.stories\.(m?js|ts)x?$/,
createIndex: async (fileName) => [
{
exportName: 'StoryOne',
__id: 'a--story-one',
name: 'Story One',
title: 'A',
tags: [AUTODOCS_TAG, 'story-tag-from-indexer'],
importPath: fileName,
type: 'story',
},
],
},
],
});
const result = await generator.extractStories(specifier, absolutePath);
expect(result).toMatchInlineSnapshot(`
Object {
"dependents": Array [],
"entries": Array [
Object {
"id": "a--docs",
"importPath": "./src/A.stories.js",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"autodocs",
"story-tag-from-indexer",
"docs",
],
"title": "A",
"type": "docs",
},
Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"metaId": undefined,
"name": "Story One",
"tags": Array [
"autodocs",
"story-tag-from-indexer",
"story",
],
"title": "A",
"type": "story",
},
],
"type": "stories",
}
`);
});
it(`DOES NOT adds docs entry when autodocs is false and an entry has the "${AUTODOCS_TAG}" tag`, async () => {
const relativePath = './src/A.stories.js';
const absolutePath = path.join(options.workingDir, relativePath);
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(relativePath, options);
const generator = new StoryIndexGenerator([specifier], {
...options,
docs: { defaultName: 'docs', autodocs: false },
indexers: [
{
test: /\.stories\.(m?js|ts)x?$/,
createIndex: async (fileName) => [
{
exportName: 'StoryOne',
__id: 'a--story-one',
name: 'Story One',
title: 'A',
tags: [AUTODOCS_TAG, 'story-tag-from-indexer'],
importPath: fileName,
type: 'story',
},
],
},
],
});
const result = await generator.extractStories(specifier, absolutePath);
expect(result).toMatchInlineSnapshot(`
Object {
"dependents": Array [],
"entries": Array [
Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"metaId": undefined,
"name": "Story One",
"tags": Array [
"autodocs",
"story-tag-from-indexer",
"story",
],
"title": "A",
"type": "story",
},
],
"type": "stories",
}
`);
});
it(`adds docs entry when an entry has the "${STORIES_MDX_TAG}" tag`, async () => {
const relativePath = './src/A.stories.js';
const absolutePath = path.join(options.workingDir, relativePath);
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(relativePath, options);
const generator = new StoryIndexGenerator([specifier], {
...options,
docs: { defaultName: 'docs', autodocs: false },
indexers: [
{
test: /\.stories\.(m?js|ts)x?$/,
createIndex: async (fileName) => [
{
exportName: 'StoryOne',
__id: 'a--story-one',
name: 'Story One',
title: 'A',
tags: [STORIES_MDX_TAG, 'story-tag-from-indexer'],
importPath: fileName,
type: 'story',
},
],
},
],
});
const result = await generator.extractStories(specifier, absolutePath);
expect(result).toMatchInlineSnapshot(`
Object {
"dependents": Array [],
"entries": Array [
Object {
"id": "a--docs",
"importPath": "./src/A.stories.js",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"stories-mdx",
"story-tag-from-indexer",
"docs",
],
"title": "A",
"type": "docs",
},
Object {
"id": "a--story-one",
"importPath": "./src/A.stories.js",
"metaId": undefined,
"name": "Story One",
"tags": Array [
"stories-mdx",
"story-tag-from-indexer",
"story",
],
"title": "A",
"type": "story",
},
],
"type": "stories",
}
`);
});
it(`Only adds a docs entry and not a story entry when an input has the "docsOnly" tag`, async () => {
const relativePath = './src/nested/Page.stories.mdx';
const absolutePath = path.join(options.workingDir, relativePath);
const specifier: NormalizedStoriesSpecifier = normalizeStoriesEntry(relativePath, options);
const generator = new StoryIndexGenerator([specifier], {
...options,
docs: { defaultName: 'docs', autodocs: false },
indexers: [
{
test: /\.stories\.mdx?$/,
createIndex: async (fileName) => [
{
exportName: '__page',
__id: 'page--page',
name: 'Page',
title: 'Page',
tags: [STORIES_MDX_TAG, 'stories-mdx-docsOnly'],
importPath: fileName,
type: 'story',
},
],
},
],
});
const result = await generator.extractStories(specifier, absolutePath);
expect(result).toMatchInlineSnapshot(`
Object {
"dependents": Array [],
"entries": Array [
Object {
"id": "page--docs",
"importPath": "./src/nested/Page.stories.mdx",
"name": "docs",
"storiesImports": Array [],
"tags": Array [
"stories-mdx",
"stories-mdx-docsOnly",
"docs",
],
"title": "Page",
"type": "docs",
},
],
"type": "stories",
}
`);
});
});
|
905 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts | import { glob as globlOriginal } from 'glob';
import { type StoriesEntry } from '@storybook/types';
import { normalizeStoriesEntry } from '@storybook/core-common';
import { join } from 'path';
import slash from 'slash';
import { removeMDXEntries } from '../remove-mdx-entries';
const glob = globlOriginal as jest.MockedFunction<typeof globlOriginal>;
const configDir = '/configDir/';
const workingDir = '/';
jest.mock('glob', () => ({ glob: jest.fn() }));
const createList = (list: { entry: StoriesEntry; result: string[] }[]) => {
return list.reduce<Record<string, { result: string[]; entry: StoriesEntry }>>(
(acc, { entry, result }) => {
const { directory, files } = normalizeStoriesEntry(entry, {
configDir,
workingDir,
});
acc[slash(join('/', directory, files))] = { result, entry };
return acc;
},
{}
);
};
const createGlobMock = (input: ReturnType<typeof createList>) => {
return async (k: string | string[]) => {
if (Array.isArray(k)) {
throw new Error('do not pass an array to glob during tests');
}
if (input[slash(k)]) {
return input[slash(k)]?.result;
}
throw new Error('can not find key in input');
};
};
test('empty', async () => {
const list = createList([]);
glob.mockImplementation(createGlobMock(list));
await expect(() => removeMDXEntries(Object.keys(list), { configDir })).rejects
.toThrowErrorMatchingInlineSnapshot(`
"Storybook could not index your stories.
Your main configuration somehow does not contain a 'stories' field, or it resolved to an empty array.
Please check your main configuration file and make sure it exports a 'stories' field that is not an empty array.
More info: https://storybook.js.org/docs/react/faq#can-i-have-a-storybook-with-no-local-stories
"
`);
});
test('minimal', async () => {
const list = createList([{ entry: '*.js', result: [] }]);
glob.mockImplementation(createGlobMock(list));
const result = await removeMDXEntries(
Object.values(list).map((e) => e.entry),
{ configDir }
);
expect(result).toMatchInlineSnapshot(`
Array [
Object {
"directory": ".",
"files": "*.js",
"titlePrefix": "",
},
]
`);
});
test('multiple', async () => {
const list = createList([
{ entry: '*.ts', result: [] },
{ entry: '*.js', result: [] },
]);
glob.mockImplementation(createGlobMock(list));
const result = await removeMDXEntries(
Object.values(list).map((e) => e.entry),
{ configDir }
);
expect(result).toMatchInlineSnapshot(`
Array [
Object {
"directory": ".",
"files": "*.ts",
"titlePrefix": "",
},
Object {
"directory": ".",
"files": "*.js",
"titlePrefix": "",
},
]
`);
});
test('mdx but not matching any files', async () => {
const list = createList([
{ entry: '*.mdx', result: [] },
{ entry: '*.js', result: [] },
]);
glob.mockImplementation(createGlobMock(list));
const result = await removeMDXEntries(
Object.values(list).map((e) => e.entry),
{ configDir }
);
expect(result).toMatchInlineSnapshot(`
Array [
Object {
"directory": ".",
"files": "*.mdx",
"titlePrefix": "",
},
Object {
"directory": ".",
"files": "*.js",
"titlePrefix": "",
},
]
`);
});
test('removes entries that only yield mdx files', async () => {
const list = createList([
{ entry: '*.mdx', result: ['/configDir/my-file.mdx'] },
{ entry: '*.js', result: [] },
]);
glob.mockImplementation(createGlobMock(list));
const result = await removeMDXEntries(
Object.values(list).map((e) => e.entry),
{ configDir }
);
expect(result).toMatchInlineSnapshot(`
Array [
Object {
"directory": ".",
"files": "*.js",
"titlePrefix": "",
},
]
`);
});
test('expands entries that only yield mixed files', async () => {
const list = createList([
{ entry: '*.@(mdx|ts)', result: ['/configDir/my-file.mdx', '/configDir/my-file.ts'] },
{ entry: '*.js', result: [] },
]);
glob.mockImplementation(createGlobMock(list));
const result = await removeMDXEntries(
Object.values(list).map((e) => e.entry),
{ configDir }
);
expect(result).toMatchInlineSnapshot(`
Array [
Object {
"directory": ".",
"files": "**/my-file.ts",
"titlePrefix": "",
},
Object {
"directory": ".",
"files": "*.js",
"titlePrefix": "",
},
]
`);
});
test('passes titlePrefix', async () => {
const list = createList([
{
entry: { files: '*.@(mdx|ts)', directory: '.', titlePrefix: 'foo' },
result: ['/configDir/my-file.mdx', '/configDir/my-file.ts'],
},
]);
glob.mockImplementation(createGlobMock(list));
const result = await removeMDXEntries(
Object.values(list).map((e) => e.entry),
{ configDir }
);
expect(result).toMatchInlineSnapshot(`
Array [
Object {
"directory": ".",
"files": "**/my-file.ts",
"titlePrefix": "foo",
},
]
`);
});
test('expands to multiple entries', async () => {
const list = createList([
{
entry: { files: '*.@(mdx|ts)', directory: '.', titlePrefix: 'foo' },
result: [
'/configDir/my-file.mdx',
'/configDir/my-file1.ts',
'/configDir/my-file2.ts',
'/configDir/my-file3.ts',
],
},
]);
glob.mockImplementation(createGlobMock(list));
const result = await removeMDXEntries(
Object.values(list).map((e) => e.entry),
{ configDir }
);
expect(result).toMatchInlineSnapshot(`
Array [
Object {
"directory": ".",
"files": "**/my-file1.ts",
"titlePrefix": "foo",
},
Object {
"directory": ".",
"files": "**/my-file2.ts",
"titlePrefix": "foo",
},
Object {
"directory": ".",
"files": "**/my-file3.ts",
"titlePrefix": "foo",
},
]
`);
});
|
906 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils/__tests__/server-address.test.ts | import ip from 'ip';
import { getServerAddresses } from '../server-address';
jest.mock('ip');
const mockedIp = ip as jest.Mocked<typeof ip>;
describe('getServerAddresses', () => {
beforeEach(() => {
mockedIp.address.mockReturnValue('192.168.0.5');
});
it('builds addresses with a specified host', () => {
const { address, networkAddress } = getServerAddresses(9009, '192.168.89.89', 'http');
expect(address).toEqual('http://localhost:9009/');
expect(networkAddress).toEqual('http://192.168.89.89:9009/');
});
it('builds addresses with local IP when host is not specified', () => {
const { address, networkAddress } = getServerAddresses(9009, '', 'http');
expect(address).toEqual('http://localhost:9009/');
expect(networkAddress).toEqual('http://192.168.0.5:9009/');
});
});
|
907 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils/__tests__/server-channel.test.ts | import type { Server } from 'http';
import { Channel } from '@storybook/channels';
import { EventEmitter } from 'events';
import { stringify } from 'telejson';
import { getServerChannel, ServerChannelTransport } from '../get-server-channel';
describe('getServerChannel', () => {
test('should return a channel', () => {
const server = { on: jest.fn() } as any as Server;
const result = getServerChannel(server);
expect(result).toBeInstanceOf(Channel);
});
test('should attach to the http server', () => {
const server = { on: jest.fn() } as any as Server;
getServerChannel(server);
expect(server.on).toHaveBeenCalledWith('upgrade', expect.any(Function));
});
});
describe('ServerChannelTransport', () => {
test('parses simple JSON', () => {
const server = new EventEmitter() as any as Server;
const socket = new EventEmitter();
const transport = new ServerChannelTransport(server);
const handler = jest.fn();
transport.setHandler(handler);
// @ts-expect-error (an internal API)
transport.socket.emit('connection', socket);
socket.emit('message', '"hello"');
expect(handler).toHaveBeenCalledWith('hello');
});
test('parses object JSON', () => {
const server = new EventEmitter() as any as Server;
const socket = new EventEmitter();
const transport = new ServerChannelTransport(server);
const handler = jest.fn();
transport.setHandler(handler);
// @ts-expect-error (an internal API)
transport.socket.emit('connection', socket);
socket.emit('message', JSON.stringify({ type: 'hello' }));
expect(handler).toHaveBeenCalledWith({ type: 'hello' });
});
test('supports telejson cyclical data', () => {
const server = new EventEmitter() as any as Server;
const socket = new EventEmitter();
const transport = new ServerChannelTransport(server);
const handler = jest.fn();
transport.setHandler(handler);
// @ts-expect-error (an internal API)
transport.socket.emit('connection', socket);
const input: any = { a: 1 };
input.b = input;
socket.emit('message', stringify(input));
expect(handler.mock.calls[0][0]).toMatchInlineSnapshot(`
Object {
"a": 1,
"b": [Circular],
}
`);
});
test('skips telejson classes and functions in data', () => {
const server = new EventEmitter() as any as Server;
const socket = new EventEmitter();
const transport = new ServerChannelTransport(server);
const handler = jest.fn();
transport.setHandler(handler);
// @ts-expect-error (an internal API)
transport.socket.emit('connection', socket);
const input = { a() {}, b: class {} };
socket.emit('message', stringify(input));
expect(handler.mock.calls[0][0].a).toEqual(expect.any(String));
expect(handler.mock.calls[0][0].b).toEqual(expect.any(String));
});
});
|
908 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils | petrpan-code/storybookjs/storybook/code/lib/core-server/src/utils/__tests__/server-statics.test.ts | import fs from 'fs-extra';
import path from 'path';
import 'jest-os-detection';
import { parseStaticDir } from '../server-statics';
fs.pathExists = jest.fn().mockReturnValue(true);
describe('parseStaticDir', () => {
it('returns the static dir/path and default target', async () => {
await expect(parseStaticDir('public')).resolves.toEqual({
staticDir: './public',
staticPath: path.resolve('public'),
targetDir: './',
targetEndpoint: '/',
});
await expect(parseStaticDir('foo/bar')).resolves.toEqual({
staticDir: './foo/bar',
staticPath: path.resolve('foo/bar'),
targetDir: './',
targetEndpoint: '/',
});
});
it('returns the static dir/path and custom target', async () => {
await expect(parseStaticDir('public:/custom-endpoint')).resolves.toEqual({
staticDir: './public',
staticPath: path.resolve('public'),
targetDir: './custom-endpoint',
targetEndpoint: '/custom-endpoint',
});
await expect(parseStaticDir('foo/bar:/custom-endpoint')).resolves.toEqual({
staticDir: './foo/bar',
staticPath: path.resolve('foo/bar'),
targetDir: './custom-endpoint',
targetEndpoint: '/custom-endpoint',
});
});
it.skipWindows('supports absolute file paths - posix', async () => {
await expect(parseStaticDir('/foo/bar')).resolves.toEqual({
staticDir: '/foo/bar',
staticPath: '/foo/bar',
targetDir: './',
targetEndpoint: '/',
});
});
it.onWindows('supports absolute file paths - windows', async () => {
await expect(parseStaticDir('C:\\foo\\bar')).resolves.toEqual({
staticDir: path.resolve('C:\\foo\\bar'),
staticPath: path.resolve('C:\\foo\\bar'),
targetDir: './',
targetEndpoint: '/',
});
});
it.skipWindows('supports absolute file paths with custom endpoint - posix', async () => {
await expect(parseStaticDir('/foo/bar:/custom-endpoint')).resolves.toEqual({
staticDir: '/foo/bar',
staticPath: '/foo/bar',
targetDir: './custom-endpoint',
targetEndpoint: '/custom-endpoint',
});
});
it.onWindows('supports absolute file paths with custom endpoint - windows', async () => {
await expect(parseStaticDir('C:\\foo\\bar:/custom-endpoint')).resolves.toEqual({
staticDir: expect.any(String), // can't test this properly on unix
staticPath: path.resolve('C:\\foo\\bar'),
targetDir: './custom-endpoint',
targetEndpoint: '/custom-endpoint',
});
await expect(parseStaticDir('C:\\foo\\bar:\\custom-endpoint')).resolves.toEqual({
staticDir: expect.any(String), // can't test this properly on unix
staticPath: path.resolve('C:\\foo\\bar'),
targetDir: './custom-endpoint',
targetEndpoint: '/custom-endpoint',
});
});
it('pins relative endpoint at root', async () => {
const normal = await parseStaticDir('public:relative-endpoint');
expect(normal.targetEndpoint).toBe('/relative-endpoint');
const windows = await parseStaticDir('C:\\public:relative-endpoint');
expect(windows.targetEndpoint).toBe('/relative-endpoint');
});
it('checks that the path exists', async () => {
fs.pathExists = jest.fn().mockReturnValueOnce(false);
await expect(parseStaticDir('nonexistent')).rejects.toThrow(path.resolve('nonexistent'));
});
});
|
915 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-webpack | petrpan-code/storybookjs/storybook/code/lib/core-webpack/src/importPipeline.test.ts | import { importPipeline } from './importPipeline';
const createGate = (): [Promise<any | undefined>, (_?: any) => void] => {
let openGate = (_?: any) => {};
const gate = new Promise<any | undefined>((resolve) => {
openGate = resolve;
});
return [gate, openGate];
};
it('passes through to passed importFn on serial calls', async () => {
const pipeline = importPipeline();
const importFn = jest.fn();
importFn.mockResolvedValueOnce('r1');
expect(await pipeline(() => importFn('i1'))).toEqual('r1');
expect(importFn).toHaveBeenCalledTimes(1);
expect(importFn).toHaveBeenCalledWith('i1');
importFn.mockResolvedValueOnce('r2');
expect(await pipeline(() => importFn('i2'))).toEqual('r2');
expect(importFn).toHaveBeenCalledTimes(2);
expect(importFn).toHaveBeenCalledWith('i2');
});
it('blocks on parallel calls', async () => {
const pipeline = importPipeline();
const [firstGate, openFirstGate] = createGate();
const importFn = jest
.fn()
.mockImplementationOnce(() => firstGate)
.mockResolvedValueOnce('r2');
const firstPromise = pipeline(() => importFn('i1'));
// We need to await promise resolution to get the block setup
await new Promise((r) => r(null));
const secondPromise = pipeline(() => importFn('i2'));
expect(importFn).toHaveBeenCalledTimes(1);
expect(importFn).toHaveBeenCalledWith('i1');
openFirstGate('r1');
expect(await firstPromise).toEqual('r1');
// We need to await promise resolution to get past the block
await new Promise((r) => r(null));
expect(importFn).toHaveBeenCalledTimes(2);
expect(importFn).toHaveBeenCalledWith('i2');
expect(await secondPromise).toEqual('r2');
});
it('dispatches all queued calls on opening', async () => {
const pipeline = importPipeline();
const [firstGate, openFirstGate] = createGate();
const importFn = jest
.fn()
.mockImplementationOnce(() => firstGate)
.mockResolvedValueOnce('r2')
.mockResolvedValueOnce('r3');
const firstPromise = pipeline(() => importFn('i1'));
// We need to await promise resolution to get the block setup
await new Promise((r) => r(null));
const secondPromise = pipeline(() => importFn('i2'));
// We need to await promise resolution to get the block setup
await new Promise((r) => r(null));
const thirdPromise = pipeline(() => importFn('i3'));
expect(importFn).toHaveBeenCalledTimes(1);
expect(importFn).toHaveBeenCalledWith('i1');
openFirstGate('r1');
expect(await firstPromise).toEqual('r1');
// We need to await promise resolution to get past the block
await new Promise((r) => r(null));
expect(importFn).toHaveBeenCalledTimes(3);
expect(importFn).toHaveBeenCalledWith('i2');
expect(importFn).toHaveBeenCalledWith('i3');
expect(await secondPromise).toEqual('r2');
expect(await thirdPromise).toEqual('r3');
});
it('blocks sequentially on parallel calls', async () => {
const pipeline = importPipeline();
const [firstGate, openFirstGate] = createGate();
const [secondGate, openSecondGate] = createGate();
const importFn = jest
.fn()
.mockImplementationOnce(() => firstGate)
.mockImplementationOnce(() => secondGate)
.mockResolvedValueOnce('r3');
const firstPromise = pipeline(() => importFn('i1'));
// We need to await promise resolution to get the block setup
await new Promise((r) => r(null));
const secondPromise = pipeline(() => importFn('i2'));
expect(importFn).toHaveBeenCalledTimes(1);
expect(importFn).toHaveBeenCalledWith('i1');
openFirstGate('r1');
expect(await firstPromise).toEqual('r1');
// We need to await promise resolution to get past the block, and set up the new one
await new Promise((r) => r(null));
const thirdPromise = pipeline(() => importFn('i3'));
expect(importFn).toHaveBeenCalledTimes(2);
expect(importFn).toHaveBeenCalledWith('i2');
openSecondGate('r2');
expect(await secondPromise).toEqual('r2');
// We need to await promise resolution to get past the block
await new Promise((r) => r(null));
expect(await thirdPromise).toEqual('r3');
});
|
919 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-webpack | petrpan-code/storybookjs/storybook/code/lib/core-webpack/src/merge-webpack-config.test.ts | import type { Configuration } from 'webpack';
import { mergeConfigs } from './merge-webpack-config';
const config: Configuration = {
devtool: 'source-map',
entry: {
bundle: 'index.js',
},
output: {
filename: '[name].js',
},
module: {
rules: [{ use: 'r1' }, { use: 'r2' }],
},
// @ts-expect-errors For snapshot readability purposes `plugins` attribute doesn't match the correct type
plugins: ['p1', 'p2'],
resolve: {
enforceExtension: true,
extensions: ['.js', '.json'],
alias: {
A1: 'src/B1',
A2: 'src/B2',
},
},
optimization: {
splitChunks: {
chunks: 'all',
},
runtimeChunk: true,
},
};
describe('mergeConfigs', () => {
it('merges two full configs in one', () => {
const customConfig: Configuration = {
profile: true,
entry: {
bundle: 'should_not_be_merged.js',
},
output: {
filename: 'should_not_be_merged.js',
},
module: {
noParse: /jquery|lodash/,
rules: [{ use: 'r3' }, { use: 'r4' }],
},
// @ts-expect-errors For snapshot readability purposes `plugins` attribute doesn't match the correct type
plugins: ['p3', 'p4'],
resolve: {
enforceExtension: false,
extensions: ['.ts', '.tsx'],
alias: {
A3: 'src/B3',
A4: 'src/B4',
},
},
optimization: {
// @ts-expect-errors For snapshot readability purposes `minimizer` attribute doesn't match the correct type
minimizer: ['banana'],
},
};
const result = mergeConfigs(config, customConfig);
expect(result).toMatchSnapshot();
});
it('merges partial custom config', () => {
const customConfig: Configuration = {
// @ts-expect-errors For snapshot readability purposes `plugins` attribute doesn't match the correct type
plugins: ['p3'],
resolve: {
extensions: ['.ts', '.tsx'],
},
};
const result = mergeConfigs(config, customConfig);
expect(result).toMatchSnapshot();
});
it('merges successfully if custom config is empty', () => {
const customConfig = {};
const result = mergeConfigs(config, customConfig);
expect(result).toMatchSnapshot();
});
});
|
921 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-webpack | petrpan-code/storybookjs/storybook/code/lib/core-webpack/src/to-importFn.test.ts | import { normalizeStoriesEntry } from '@storybook/core-common';
import { webpackIncludeRegexp } from './to-importFn';
const testCases: [string, string[], string[]][] = [
[
'**/*.stories.tsx',
[
'/Users/user/code/.storybook/Icon.stories.tsx',
'/Users/user/code/.storybook/stories/Icon.stories.tsx',
'/Users/user/code/.storybook/stories/components/Icon.stories.tsx',
],
[
'/Users/user/code/.storybook/stories.tsx',
'/Users/user/code/.storybook/Icon.stories.ts',
'/Users/user/code/.storybook/Icon.stories.js',
'/Users/user/code/.storybook/src/components/stories.tsx',
'/Users/user/code/.storybook/src/components/Icon.stories/stories.tsx',
'/Users/user/code/.storybook/src/components/Icon.stories.ts',
'/Users/user/code/.storybook/src/components/Icon.stories.js',
'/Users/user/code/src/components/Icon.stories.tsx',
],
],
[
'./**/*.stories.tsx',
[
'/Users/user/code/.storybook/Icon.stories.tsx',
'/Users/user/code/.storybook/stories/Icon.stories.tsx',
'/Users/user/code/.storybook/stories/components/Icon.stories.tsx',
],
[
'/Users/user/code/.storybook/stories.tsx',
'/Users/user/code/.storybook/Icon.stories.ts',
'/Users/user/code/.storybook/Icon.stories.js',
'/Users/user/code/.storybook/src/components/stories.tsx',
'/Users/user/code/.storybook/src/components/Icon.stories/stories.tsx',
'/Users/user/code/.storybook/src/components/Icon.stories.ts',
'/Users/user/code/.storybook/src/components/Icon.stories.js',
'/Users/user/code/src/components/Icon.stories.tsx',
],
],
[
'../**/*.stories.tsx',
[
'/Users/user/code/.storybook/Icon.stories.tsx',
'/Users/user/code/Icon.stories.tsx',
'/Users/user/code/src/Icon.stories.tsx',
'/Users/user/code/src/components/Icon.stories.tsx',
'/Users/user/code/src/components/Icon.stories/Icon.stories.tsx',
],
[
'/Users/user/code/.storybook/stories.tsx',
'/Users/user/code/stories.tsx',
'/Users/user/code/Icon.stories.ts',
'/Users/user/code/Icon.stories.js',
'/Users/user/code/src/components/stories.tsx',
'/Users/user/code/src/components/Icon.stories/stories.tsx',
'/Users/user/code/src/components/Icon.stories.ts',
'/Users/user/code/src/components/Icon.stories.js',
],
],
[
'../src',
[],
[
'/Users/user/code/Icon.stories.tsx',
'/Users/user/code/src/Icon.stories.tsx',
'/Users/user/code/src/components/Icon.stories.tsx',
'/Users/user/code/src/components/Icon.stories/Icon.stories.tsx',
'/Users/user/code/stories.tsx',
'/Users/user/code/Icon.stories.ts',
'/Users/user/code/Icon.stories.js',
'/Users/user/code/src/components/stories.tsx',
'/Users/user/code/src/components/Icon.stories/stories.tsx',
'/Users/user/code/src/components/Icon.stories.ts',
'/Users/user/code/src/components/Icon.stories.js',
],
],
[
'../src/*',
['/Users/user/code/src/Icon.stories.tsx'],
[
'/Users/user/code/Icon.stories.tsx',
'/Users/user/code/src/components/Icon.stories.tsx',
'/Users/user/code/src/components/Icon.stories/Icon.stories.tsx',
'/Users/user/code/stories.tsx',
'/Users/user/code/Icon.stories.ts',
'/Users/user/code/Icon.stories.js',
'/Users/user/code/src/components/stories.tsx',
'/Users/user/code/src/components/Icon.stories/stories.tsx',
'/Users/user/code/src/components/Icon.stories.ts',
'/Users/user/code/src/components/Icon.stories.js',
],
],
[
'./stories/**/*.stories.tsx',
[
'/Users/user/code/.storybook/stories/Icon.stories.tsx',
'/Users/user/code/.storybook/stories/components/Icon.stories.tsx',
'/Users/user/code/.storybook/stories/components/Icon.stories/Icon.stories.tsx',
],
[
'/Users/user/code/Icon.stories.tsx',
'/Users/user/code/stories.tsx',
'/Users/user/code/Icon.stories.ts',
'/Users/user/code/Icon.stories.js',
'/Users/user/code/stories/components/stories.tsx',
'/Users/user/code/stories/components/Icon.stories/stories.tsx',
'/Users/user/code/stories/components/Icon.stories.ts',
'/Users/user/code/stories/components/Icon.stories.js',
],
],
[
'../src/**/*.stories.tsx',
[
'/Users/user/code/src/Icon.stories.tsx',
'/Users/user/code/src/components/Icon.stories.tsx',
'/Users/user/code/src/components/Icon.stories/Icon.stories.tsx',
],
[
'/Users/user/code/.storybook/Icon.stories.tsx',
// Although it would make sense for these three files to fail to match the `importFn()`,
// because we are limited to matching on the RHS of the path (from 'src' onwards, basically)
// we cannot avoid matching things inside the config dir in such situations.
// '/Users/user/code/.storybook/src/Icon.stories.tsx',
// '/Users/user/code/.storybook/src/components/Icon.stories.tsx',
// '/Users/user/code/.storybook/src/components/Icon.stories/Icon.stories.tsx',
'/Users/user/code/Icon.stories.tsx',
'/Users/user/code/stories.tsx',
'/Users/user/code/Icon.stories.ts',
'/Users/user/code/Icon.stories.js',
'/Users/user/code/src/components/stories.tsx',
'/Users/user/code/src/components/Icon.stories/stories.tsx',
'/Users/user/code/src/components/Icon.stories.ts',
'/Users/user/code/src/components/Icon.stories.js',
],
],
[
'../../src/**/*.stories.tsx',
[
'/Users/user/code/src/Icon.stories.tsx',
'/Users/user/code/src/components/Icon.stories.tsx',
'/Users/user/code/src/components/Icon.stories/Icon.stories.tsx',
],
[
'/Users/user/code/Icon.stories.tsx',
'/Users/user/code/stories.tsx',
'/Users/user/code/Icon.stories.ts',
'/Users/user/code/Icon.stories.js',
'/Users/user/code/src/components/stories.tsx',
'/Users/user/code/src/components/Icon.stories/stories.tsx',
'/Users/user/code/src/components/Icon.stories.ts',
'/Users/user/code/src/components/Icon.stories.js',
],
],
[
'./../../src/**/*.stories.tsx',
[
'/Users/user/code/src/Icon.stories.tsx',
'/Users/user/code/src/components/Icon.stories.tsx',
'/Users/user/code/src/components/Icon.stories/Icon.stories.tsx',
],
[
'/Users/user/code/Icon.stories.tsx',
'/Users/user/code/stories.tsx',
'/Users/user/code/Icon.stories.ts',
'/Users/user/code/Icon.stories.js',
'/Users/user/code/src/components/stories.tsx',
'/Users/user/code/src/components/Icon.stories/stories.tsx',
'/Users/user/code/src/components/Icon.stories.ts',
'/Users/user/code/src/components/Icon.stories.js',
],
],
[
'./Introduction.stories.tsx',
['/Users/user/code/.storybook/Introduction.stories.tsx'],
[
'/Users/user/code/Introduction.stories.tsx',
'/Users/user/code/src/Introduction.stories.tsx',
'/Users/user/code/src/Introduction.tsx',
],
],
[
'Introduction.stories.tsx',
['/Users/user/code/.storybook/Introduction.stories.tsx'],
[
'/Users/user/code/Introduction.stories.tsx',
'/Users/user/code/src/Introduction.stories.tsx',
'/Users/user/code/src/Introduction.tsx',
],
],
];
describe('toImportFn - webpackIncludeRegexp', () => {
it.each(testCases)('matches only suitable paths - %s', (glob, validPaths, invalidPaths) => {
const regex = webpackIncludeRegexp(
normalizeStoriesEntry(glob, {
configDir: '/Users/user/code/.storybook',
workingDir: '/Users/user/code/',
})
);
const isNotMatchedForValidPaths = validPaths.filter(
(absolutePath) => !regex.test(absolutePath)
);
const isMatchedForInvalidPaths = invalidPaths.filter(
(absolutePath) => !!regex.test(absolutePath)
);
expect(isNotMatchedForValidPaths).toEqual([]);
expect(isMatchedForInvalidPaths).toEqual([]);
});
});
|
923 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-webpack | petrpan-code/storybookjs/storybook/code/lib/core-webpack/src/to-require-context.test.ts | import path from 'path';
import { normalizeStoriesEntry } from '@storybook/core-common';
import { toRequireContext } from './to-require-context';
const testCases = [
{
glob: '**/*.stories.tsx',
recursive: true,
validPaths: [
'./Icon.stories.tsx',
'./src/Icon.stories.tsx',
'./src/components/Icon.stories.tsx',
'./src/components/Icon.stories/Icon.stories.tsx',
],
invalidPaths: [
'./stories.tsx',
'./Icon.stories.ts',
'./Icon.stories.js',
'./src/components/stories.tsx',
'./src/components/Icon.stories/stories.tsx',
'./src/components/Icon.stories.ts',
'./src/components/Icon.stories.js',
],
},
{
glob: 'src',
recursive: false,
validPaths: [],
invalidPaths: [
'./Icon.stories.tsx',
'./src/Icon.stories.tsx',
'./src/components/Icon.stories.tsx',
'./src/components/Icon.stories/Icon.stories.tsx',
'./stories.tsx',
'./Icon.stories.ts',
'./Icon.stories.js',
'./src/components/stories.tsx',
'./src/components/Icon.stories/stories.tsx',
'./src/components/Icon.stories.ts',
'./src/components/Icon.stories.js',
],
},
{
glob: 'src/*',
recursive: false,
validPaths: ['./src/Icon.stories.tsx'],
invalidPaths: [
'./Icon.stories.tsx',
'./src/components/Icon.stories.tsx',
'./src/components/Icon.stories/Icon.stories.tsx',
'./stories.tsx',
'./Icon.stories.ts',
'./Icon.stories.js',
'./src/components/stories.tsx',
'./src/components/Icon.stories/stories.tsx',
'./src/components/Icon.stories.ts',
'./src/components/Icon.stories.js',
],
},
// INVALID GLOB
{
glob: '../src/stories/**/*.stories.(js|mdx)',
recursive: true,
validPaths: [
'../src/stories/components/Icon.stories.js',
'../src/stories/Icon.stories.js',
'../src/stories/Icon.stories.mdx',
'../src/stories/components/Icon/Icon.stories.js',
'../src/stories/components/Icon.stories/Icon.stories.mdx',
],
invalidPaths: [
'./stories.js',
'./src/stories/Icon.stories.js',
'./Icon.stories.js',
'../src/Icon.stories.mdx',
'../src/stories/components/Icon/Icon.stories.ts',
'../src/stories/components/Icon/Icon.mdx',
],
},
{
glob: 'dirname/../stories/*.stories.*',
recursive: false,
validPaths: [
'./dirname/../stories/App.stories.js',
'./dirname/../stories/addon-centered.stories.js',
],
invalidPaths: ['./dirname/../stories.js', './dirname/../App.stories.js'],
},
{
glob: '../src/stories/**/@(*.stories.js|*.stories.mdx)',
recursive: true,
validPaths: [
'../src/stories/components/Icon.stories.js',
'../src/stories/Icon.stories.js',
'../src/stories/Icon.stories.mdx',
'../src/stories/components/Icon/Icon.stories.js',
'../src/stories/components/Icon.stories/Icon.stories.mdx',
],
invalidPaths: [
'./stories.js',
'./src/stories/Icon.stories.js',
'./Icon.stories.js',
'../src/Icon.stories.mdx',
'../src/stories/components/Icon/Icon.stories.ts',
'../src/stories/components/Icon/Icon.mdx',
],
},
{
glob: '../src/stories/**/*.stories.+(js|mdx)',
recursive: true,
validPaths: [
'../src/stories/components/Icon.stories.js',
'../src/stories/Icon.stories.js',
'../src/stories/Icon.stories.mdx',
'../src/stories/components/Icon/Icon.stories.js',
'../src/stories/components/Icon.stories/Icon.stories.mdx',
],
invalidPaths: [
'./stories.js',
'./src/stories/Icon.stories.js',
'./Icon.stories.js',
'../src/Icon.stories.mdx',
'../src/stories/components/Icon/Icon.stories.ts',
'../src/stories/components/Icon/Icon.mdx',
],
},
{
glob: '../src/stories/**/*.stories.*(js|mdx)',
recursive: true,
validPaths: [
'../src/stories/components/Icon.stories.js',
'../src/stories/Icon.stories.js',
'../src/stories/Icon.stories.mdx',
'../src/stories/components/Icon/Icon.stories.js',
'../src/stories/components/Icon.stories/Icon.stories.mdx',
],
invalidPaths: [
'./stories.js',
'./src/stories/Icon.stories.js',
'./Icon.stories.js',
'../src/Icon.stories.mdx',
'../src/stories/components/Icon/Icon.stories.ts',
'../src/stories/components/Icon/Icon.mdx',
],
},
{
glob: '../src/stories/components/Icon.stories.js',
recursive: false,
validPaths: ['../src/stories/components/Icon.stories.js'],
invalidPaths: [
'../src/Icon.stories.mdx',
'../src/stories/components/Icon.stories/Icon.stories.mdx',
'../src/stories/components/Icon/Icon.mdx',
'../src/stories/components/Icon/Icon.stories.js',
'../src/stories/components/Icon/Icon.stories.ts',
'../src/stories/Icon.stories.js',
'../src/stories/Icon.stories.mdx',
'./Icon.stories.js',
'./src/stories/Icon.stories.js',
'./stories.js',
],
},
// DUMB GLOB
{
glob: '../src/stories/**/*.stories.[tj]sx',
recursive: true,
validPaths: [
'../src/stories/components/Icon.stories.jsx',
'../src/stories/Icon.stories.jsx',
'../src/stories/Icon.stories.tsx',
'../src/stories/components/Icon/Icon.stories.jsx',
'../src/stories/components/Icon.stories/Icon.stories.tsx',
],
invalidPaths: [
'./stories.jsx',
'./src/stories/Icon.stories.jsx',
'./Icon.stories.jsx',
'../src/Icon.stories.tsx',
'../src/stories/components/Icon/Icon.stories.ts',
'../src/stories/components/Icon/Icon.tsx',
],
},
{
glob: '../components/*.stories.js',
recursive: false,
validPaths: ['../components/Icon.stories.js'],
invalidPaths: [
'../components/icon/node_modules/icon/Icon.stories.js',
'./stories.js',
'./src/stories/Icon.stories.js',
'./Icon.stories.js',
'../src/Icon.stories.mdx',
'../src/stories/components/Icon/Icon.stories.ts',
'../src/stories/components/Icon/Icon.mdx',
],
},
{
glob: '../components/*/*.stories.js',
recursive: true,
validPaths: ['../components/icon/Icon.stories.js'],
invalidPaths: [
'../components/icon/node_modules/icon/Icon.stories.js',
'./stories.js',
'./src/stories/Icon.stories.js',
'./Icon.stories.js',
'../src/Icon.stories.mdx',
'../src/stories/components/Icon/Icon.stories.ts',
'../src/stories/components/Icon/Icon.mdx',
],
},
{
glob: '../components/*/*/*.stories.js',
recursive: true,
validPaths: ['../components/basics/icon/Icon.stories.js'],
invalidPaths: [
'../components/icon/node_modules/icon/Icon.stories.js',
'./stories.js',
'./src/stories/Icon.stories.js',
'./Icon.stories.js',
'../src/Icon.stories.mdx',
'../components/icon/Icon.stories.js',
'../components/basics/simple/icon/Icon.stories.js',
'../src/stories/components/Icon/Icon.stories.ts',
'../src/stories/components/Icon/Icon.mdx',
],
},
{
glob: '../components/*/stories/*.js',
recursive: true,
validPaths: ['../components/icon/stories/Icon.js'],
invalidPaths: [
'../components/icon/node_modules/icon/stories/Icon.js',
'./stories.js',
'./src/stories/Icon.stories.js',
'./Icon.stories.js',
'../src/Icon.stories.mdx',
'../src/stories/components/Icon/Icon.stories.ts',
'../src/stories/components/Icon/Icon.mdx',
],
},
// Patterns before the **, see:
// - https://github.com/storybookjs/storybook/issues/17038
// - https://github.com/storybookjs/storybook/issues/16964
// - https://github.com/storybookjs/storybook/issues/16924
{
glob: '../{dir1,dir2}/**/*.stories.js',
recursive: true,
validPaths: [
'../dir1/Icon.stories.js',
'../dir1/nested/Icon.stories.js',
'../dir2/Icon.stories.js',
'../dir2/nested/Icon.stories.js',
],
invalidPaths: ['../dir3/Icon.stories.js', '../dir3/nested/Icon.stories.js'],
},
];
describe('toRequireContext', () => {
testCases.forEach(({ glob, recursive, validPaths, invalidPaths }) => {
it(`matches only suitable paths - ${glob}`, () => {
const {
path: base,
recursive: willRecurse,
match,
} = toRequireContext(
normalizeStoriesEntry(glob, { configDir: '/path', workingDir: '/path' })
);
const regex = new RegExp(match);
function isMatched(filePath: string) {
const relativePath = `./${path.relative(base, filePath)}`;
const baseIncluded = filePath.includes(base);
const matched = regex.test(relativePath);
// console.log(filePath, relativePath, regex, matched);
return baseIncluded && matched;
}
const isNotMatchedForValidPaths = validPaths.filter((filePath) => !isMatched(filePath));
const isMatchedForInvalidPaths = invalidPaths.filter((filePath) => !!isMatched(filePath));
expect(isNotMatchedForValidPaths).toEqual([]);
expect(isMatchedForInvalidPaths).toEqual([]);
expect(willRecurse).toEqual(recursive);
});
});
});
|
927 | 0 | petrpan-code/storybookjs/storybook/code/lib/core-webpack/src | petrpan-code/storybookjs/storybook/code/lib/core-webpack/src/__snapshots__/merge-webpack-config.test.ts.snap | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`mergeConfigs merges partial custom config 1`] = `
Object {
"devtool": "source-map",
"entry": Object {
"bundle": "index.js",
},
"module": Object {
"rules": Array [
Object {
"use": "r1",
},
Object {
"use": "r2",
},
],
},
"optimization": Object {
"runtimeChunk": true,
"splitChunks": Object {
"chunks": "all",
},
},
"output": Object {
"filename": "[name].js",
},
"plugins": Array [
"p1",
"p2",
"p3",
],
"resolve": Object {
"alias": Object {
"A1": "src/B1",
"A2": "src/B2",
},
"enforceExtension": true,
"extensions": Array [
".js",
".json",
".ts",
".tsx",
],
},
}
`;
exports[`mergeConfigs merges successfully if custom config is empty 1`] = `
Object {
"devtool": "source-map",
"entry": Object {
"bundle": "index.js",
},
"module": Object {
"rules": Array [
Object {
"use": "r1",
},
Object {
"use": "r2",
},
],
},
"optimization": Object {
"runtimeChunk": true,
"splitChunks": Object {
"chunks": "all",
},
},
"output": Object {
"filename": "[name].js",
},
"plugins": Array [
"p1",
"p2",
],
"resolve": Object {
"alias": Object {
"A1": "src/B1",
"A2": "src/B2",
},
"enforceExtension": true,
"extensions": Array [
".js",
".json",
],
},
}
`;
exports[`mergeConfigs merges two full configs in one 1`] = `
Object {
"devtool": "source-map",
"entry": Object {
"bundle": "index.js",
},
"module": Object {
"noParse": /jquery\\|lodash/,
"rules": Array [
Object {
"use": "r1",
},
Object {
"use": "r2",
},
Object {
"use": "r3",
},
Object {
"use": "r4",
},
],
},
"optimization": Object {
"minimizer": Array [
"banana",
],
"runtimeChunk": true,
"splitChunks": Object {
"chunks": "all",
},
},
"output": Object {
"filename": "[name].js",
},
"plugins": Array [
"p1",
"p2",
"p3",
"p4",
],
"profile": true,
"resolve": Object {
"alias": Object {
"A1": "src/B1",
"A2": "src/B2",
"A3": "src/B3",
"A4": "src/B4",
},
"enforceExtension": false,
"extensions": Array [
".js",
".json",
".ts",
".tsx",
],
},
}
`;
|
941 | 0 | petrpan-code/storybookjs/storybook/code/lib/csf-tools | petrpan-code/storybookjs/storybook/code/lib/csf-tools/src/ConfigFile.test.ts | /// <reference types="@types/jest" />;
import { dedent } from 'ts-dedent';
import { loadConfig, printConfig } from './ConfigFile';
import { babelPrint } from './babelParse';
expect.addSnapshotSerializer({
print: (val: any) => val,
test: (val) => true,
});
const getField = (path: string[], source: string) => {
const config = loadConfig(source).parse();
return config.getFieldValue(path);
};
const setField = (path: string[], value: any, source: string) => {
const config = loadConfig(source).parse();
config.setFieldValue(path, value);
return printConfig(config).code;
};
const appendToArray = (path: string[], value: any, source: string) => {
const config = loadConfig(source).parse();
config.appendValueToArray(path, value);
return printConfig(config).code;
};
const removeField = (path: string[], source: string) => {
const config = loadConfig(source).parse();
config.removeField(path);
return printConfig(config).code;
};
describe('ConfigFile', () => {
describe('getField', () => {
describe('named exports', () => {
it('missing export', () => {
expect(
getField(
['core', 'builder'],
dedent`
export const foo = { builder: 'webpack5' }
`
)
).toBeUndefined();
});
it('missing field', () => {
expect(
getField(
['core', 'builder'],
dedent`
export const core = { foo: 'webpack5' }
`
)
).toBeUndefined();
});
it('found scalar', () => {
expect(
getField(
['core', 'builder'],
dedent`
export const core = { builder: 'webpack5' }
`
)
).toEqual('webpack5');
});
it('found object', () => {
expect(
getField(
['core', 'builder'],
dedent`
export const core = { builder: { name: 'webpack5' } }
`
)
).toEqual({ name: 'webpack5' });
});
it('variable ref export', () => {
expect(
getField(
['core', 'builder'],
dedent`
const coreVar = { builder: 'webpack5' };
export const core = coreVar;
`
)
).toEqual('webpack5');
});
it('variable export', () => {
expect(
getField(
['core', 'builder'],
dedent`
const coreVar = { builder: 'webpack5' };
export const core = coreVar;
`
)
).toEqual('webpack5');
});
});
describe('module exports', () => {
it('missing export', () => {
expect(
getField(
['core', 'builder'],
dedent`
module.exports = { foo: { builder: 'webpack5' } }
`
)
).toBeUndefined();
});
it('found scalar', () => {
expect(
getField(
['core', 'builder'],
dedent`
module.exports = { core: { builder: 'webpack5' } }
`
)
).toEqual('webpack5');
});
it('variable ref export', () => {
expect(
getField(
['core', 'builder'],
dedent`
const core = { builder: 'webpack5' };
module.exports = { core };
`
)
).toEqual('webpack5');
});
it('variable rename', () => {
expect(
getField(
['core', 'builder'],
dedent`
const coreVar = { builder: 'webpack5' };
module.exports = { core: coreVar };
`
)
).toEqual('webpack5');
});
it('variable exports', () => {
expect(
getField(
['stories'],
dedent`
import type { StorybookConfig } from '@storybook/react-webpack5';
const config: StorybookConfig = {
stories: [{ directory: '../src', titlePrefix: 'Demo' }],
}
module.exports = config;
`
)
).toEqual([{ directory: '../src', titlePrefix: 'Demo' }]);
});
});
describe('default export', () => {
it('missing export', () => {
expect(
getField(
['core', 'builder'],
dedent`
export default { foo: { builder: 'webpack5' } }
`
)
).toBeUndefined();
});
it('found scalar', () => {
expect(
getField(
['core', 'builder'],
dedent`
export default { core: { builder: 'webpack5' } }
`
)
).toEqual('webpack5');
});
it('variable ref export', () => {
expect(
getField(
['core', 'builder'],
dedent`
const core = { builder: 'webpack5' };
export default { core };
`
)
).toEqual('webpack5');
});
it('variable rename', () => {
expect(
getField(
['core', 'builder'],
dedent`
const coreVar = { builder: 'webpack5' };
export default { core: coreVar };
`
)
).toEqual('webpack5');
});
it('variable exports', () => {
expect(
getField(
['stories'],
dedent`
import type { StorybookConfig } from '@storybook/react-webpack5';
const config: StorybookConfig = {
stories: [{ directory: '../src', titlePrefix: 'Demo' }],
}
export default config;
`
)
).toEqual([{ directory: '../src', titlePrefix: 'Demo' }]);
});
});
});
describe('setField', () => {
describe('named exports', () => {
it('missing export', () => {
expect(
setField(
['core', 'builder'],
'webpack5',
dedent`
export const addons = [];
`
)
).toMatchInlineSnapshot(`
export const addons = [];
export const core = {
builder: "webpack5"
};
`);
});
it('missing field', () => {
expect(
setField(
['core', 'builder'],
'webpack5',
dedent`
export const core = { foo: 'bar' };
`
)
).toMatchInlineSnapshot(`
export const core = {
foo: 'bar',
builder: 'webpack5'
};
`);
});
it('found scalar', () => {
expect(
setField(
['core', 'builder'],
'webpack5',
dedent`
export const core = { builder: 'webpack4' };
`
)
).toMatchInlineSnapshot(`export const core = { builder: 'webpack5' };`);
});
it('found top-level scalar', () => {
expect(
setField(
['foo'],
'baz',
dedent`
export const foo = 'bar';
`
)
).toMatchInlineSnapshot(`export const foo = 'baz';`);
});
it('found object', () => {
expect(
setField(
['core', 'builder'],
{ name: 'webpack5' },
dedent`
export const core = { builder: { name: 'webpack4' } };
`
)
).toMatchInlineSnapshot(`
export const core = { builder: {
name: 'webpack5'
} };
`);
});
it('variable export', () => {
expect(
setField(
['core', 'builder'],
'webpack5',
dedent`
const coreVar = { builder: 'webpack4' };
export const core = coreVar;
`
)
).toMatchInlineSnapshot(`
const coreVar = { builder: 'webpack5' };
export const core = coreVar;
`);
});
});
describe('module exports', () => {
it('missing export', () => {
expect(
setField(
['core', 'builder'],
'webpack5',
dedent`
module.exports = { addons: [] };
`
)
).toMatchInlineSnapshot(`
module.exports = {
addons: [],
core: {
builder: "webpack5"
}
};
`);
});
it('missing field', () => {
expect(
setField(
['core', 'builder'],
'webpack5',
dedent`
module.exports = { core: { foo: 'bar' }};
`
)
).toMatchInlineSnapshot(`
module.exports = { core: {
foo: 'bar',
builder: 'webpack5'
}};
`);
});
it('found scalar', () => {
expect(
setField(
['core', 'builder'],
'webpack5',
dedent`
module.exports = { core: { builder: 'webpack4' } };
`
)
).toMatchInlineSnapshot(`module.exports = { core: { builder: 'webpack5' } };`);
});
});
describe('default export', () => {
it('missing export', () => {
expect(
setField(
['core', 'builder'],
'webpack5',
dedent`
export default { addons: [] };
`
)
).toMatchInlineSnapshot(`
export default {
addons: [],
core: {
builder: "webpack5"
}
};
`);
});
it('missing field', () => {
expect(
setField(
['core', 'builder'],
'webpack5',
dedent`
export default { core: { foo: 'bar' }};
`
)
).toMatchInlineSnapshot(`
export default { core: {
foo: 'bar',
builder: 'webpack5'
}};
`);
});
it('found scalar', () => {
expect(
setField(
['core', 'builder'],
'webpack5',
dedent`
export default { core: { builder: 'webpack4' } };
`
)
).toMatchInlineSnapshot(`export default { core: { builder: 'webpack5' } };`);
});
});
describe('quotes', () => {
it('no quotes', () => {
expect(setField(['foo', 'bar'], 'baz', '')).toMatchInlineSnapshot(`
export const foo = {
bar: "baz"
};
`);
});
it('more single quotes', () => {
expect(setField(['foo', 'bar'], 'baz', `export const stories = ['a', 'b', "c"]`))
.toMatchInlineSnapshot(`
export const stories = ['a', 'b', "c"]
export const foo = {
bar: 'baz'
};
`);
});
it('more double quotes', () => {
expect(setField(['foo', 'bar'], 'baz', `export const stories = ['a', "b", "c"]`))
.toMatchInlineSnapshot(`
export const stories = ['a', "b", "c"]
export const foo = {
bar: "baz"
};
`);
});
});
});
describe('appendToArray', () => {
it('missing export', () => {
expect(
appendToArray(
['addons'],
'docs',
dedent`
export default { core: { builder: 'webpack5' } };
`
)
).toMatchInlineSnapshot(`
export default {
core: { builder: 'webpack5' },
addons: ['docs']
};
`);
});
it('found scalar', () => {
expect(() =>
appendToArray(
['addons'],
'docs',
dedent`
export default { addons: 5 };
`
)
).toThrowErrorMatchingInlineSnapshot(`Expected array at 'addons', got 'NumericLiteral'`);
});
it('array of simple values', () => {
expect(
appendToArray(
['addons'],
'docs',
dedent`
export default { addons: ['a11y', 'viewport'] };
`
)
).toMatchInlineSnapshot(`export default { addons: ['a11y', 'viewport', 'docs'] };`);
});
it('array of complex values', () => {
expect(
appendToArray(
['addons'],
'docs',
dedent`
export default { addons: [require.resolve('a11y'), someVariable] };
`
)
).toMatchInlineSnapshot(
`export default { addons: [require.resolve('a11y'), someVariable, 'docs'] };`
);
});
});
describe('removeField', () => {
describe('named exports', () => {
it('missing export', () => {
expect(
removeField(
['core', 'builder'],
dedent`
export const addons = [];
`
)
).toMatchInlineSnapshot(`export const addons = [];`);
});
it('missing field', () => {
expect(
removeField(
['core', 'builder'],
dedent`
export const core = { foo: 'bar' };
`
)
).toMatchInlineSnapshot(`export const core = { foo: 'bar' };`);
});
it('found scalar', () => {
expect(
removeField(
['core', 'builder'],
dedent`
export const core = { builder: 'webpack4' };
`
)
).toMatchInlineSnapshot(`export const core = {};`);
});
it('found object', () => {
expect(
removeField(
['core', 'builder'],
dedent`
export const core = { builder: { name: 'webpack4' } };
`
)
).toMatchInlineSnapshot(`export const core = {};`);
});
it('nested object', () => {
expect(
removeField(
['core', 'builder', 'name'],
dedent`
export const core = { builder: { name: 'webpack4' } };
`
)
).toMatchInlineSnapshot(`export const core = { builder: {} };`);
});
it('string literal key', () => {
expect(
removeField(
['core', 'builder'],
dedent`
export const core = { 'builder': 'webpack4' };
`
)
).toMatchInlineSnapshot(`export const core = {};`);
});
it('variable export', () => {
expect(
removeField(
['core', 'builder'],
dedent`
const coreVar = { builder: 'webpack4' };
export const core = coreVar;
`
)
).toMatchInlineSnapshot(`
const coreVar = {};
export const core = coreVar;
`);
});
it('root export variable', () => {
expect(
removeField(
['core'],
dedent`
export const core = { builder: { name: 'webpack4' } };
export const addons = [];
`
)
).toMatchInlineSnapshot(`export const addons = [];`);
});
});
describe('module exports', () => {
it('missing export', () => {
expect(
removeField(
['core', 'builder'],
dedent`
module.exports = { addons: [] };
`
)
).toMatchInlineSnapshot(`module.exports = { addons: [] };`);
});
it('missing field', () => {
expect(
removeField(
['core', 'builder'],
dedent`
module.exports = { core: { foo: 'bar' }};
`
)
).toMatchInlineSnapshot(`module.exports = { core: { foo: 'bar' }};`);
});
it('found scalar', () => {
expect(
removeField(
['core', 'builder'],
dedent`
module.exports = { core: { builder: 'webpack4' } };
`
)
).toMatchInlineSnapshot(`module.exports = { core: {} };`);
});
it('nested scalar', () => {
expect(
removeField(
['core', 'builder', 'name'],
dedent`
module.exports = { core: { builder: { name: 'webpack4' } } };
`
)
).toMatchInlineSnapshot(`module.exports = { core: { builder: {} } };`);
});
it('string literal key', () => {
expect(
removeField(
['core', 'builder'],
dedent`
module.exports = { 'core': { 'builder': 'webpack4' } };
`
)
).toMatchInlineSnapshot(`module.exports = { 'core': {} };`);
});
it('root property', () => {
expect(
removeField(
['core'],
dedent`
module.exports = { core: { builder: { name: 'webpack4' } }, addons: [] };
`
)
).toMatchInlineSnapshot(`
module.exports = {
addons: []
};
`);
});
});
describe('default export', () => {
it('missing export', () => {
expect(
removeField(
['core', 'builder'],
dedent`
export default { addons: [] };
`
)
).toMatchInlineSnapshot(`export default { addons: [] };`);
});
it('missing field', () => {
expect(
removeField(
['core', 'builder'],
dedent`
export default { core: { foo: 'bar' }};
`
)
).toMatchInlineSnapshot(`export default { core: { foo: 'bar' }};`);
});
it('found scalar', () => {
expect(
removeField(
['core', 'builder'],
dedent`
export default { core: { builder: 'webpack4' } };
`
)
).toMatchInlineSnapshot(`export default { core: {} };`);
});
it('nested scalar', () => {
expect(
removeField(
['core', 'builder', 'name'],
dedent`
export default { core: { builder: { name: 'webpack4' } } };
`
)
).toMatchInlineSnapshot(`export default { core: { builder: {} } };`);
});
it('string literal key', () => {
expect(
removeField(
['core', 'builder'],
dedent`
export default { 'core': { 'builder': 'webpack4' } };
`
)
).toMatchInlineSnapshot(`export default { 'core': {} };`);
});
it('root property', () => {
expect(
removeField(
['core'],
dedent`
export default { core: { builder: { name: 'webpack4' } }, addons: [] };
`
)
).toMatchInlineSnapshot(`
export default {
addons: []
};
`);
});
});
describe('quotes', () => {
it('no quotes', () => {
expect(setField(['foo', 'bar'], 'baz', '')).toMatchInlineSnapshot(`
export const foo = {
bar: "baz"
};
`);
});
it('more single quotes', () => {
expect(setField(['foo', 'bar'], 'baz', `export const stories = ['a', 'b', "c"]`))
.toMatchInlineSnapshot(`
export const stories = ['a', 'b', "c"]
export const foo = {
bar: 'baz'
};
`);
});
it('more double quotes', () => {
expect(setField(['foo', 'bar'], 'baz', `export const stories = ['a', "b", "c"]`))
.toMatchInlineSnapshot(`
export const stories = ['a', "b", "c"]
export const foo = {
bar: "baz"
};
`);
});
});
});
describe('config helpers', () => {
describe('getNameFromPath', () => {
it(`supports string literal node`, () => {
const source = dedent`
import type { StorybookConfig } from '@storybook/react-webpack5';
const config: StorybookConfig = {
framework: 'foo',
}
export default config;
`;
const config = loadConfig(source).parse();
expect(config.getNameFromPath(['framework'])).toEqual('foo');
});
describe('satisfies', () => {
it(`supports string literal node`, () => {
const source = dedent`
import type { StorybookConfig } from '@storybook/react-webpack5';
const config = {
framework: 'foo',
} satisfies StorybookConfig
export default config;
`;
const config = loadConfig(source).parse();
expect(config.getNameFromPath(['framework'])).toEqual('foo');
});
it(`supports string literal node without variables`, () => {
const source = dedent`
import type { StorybookConfig } from '@storybook/react-webpack5';
export default {
framework: 'foo',
} satisfies StorybookConfig;
`;
const config = loadConfig(source).parse();
expect(config.getNameFromPath(['framework'])).toEqual('foo');
});
it(`supports object expression node with name property`, () => {
const source = dedent`
import type { StorybookConfig } from '@storybook/react-webpack5';
const config = {
framework: { name: 'foo', options: { bar: require('baz') } },
"otherField": { "name": 'foo', options: { bar: require('baz') } },
} satisfies StorybookConfig
export default config;
`;
const config = loadConfig(source).parse();
expect(config.getNameFromPath(['framework'])).toEqual('foo');
expect(config.getNameFromPath(['otherField'])).toEqual('foo');
});
});
it(`supports object expression node with name property`, () => {
const source = dedent`
import type { StorybookConfig } from '@storybook/react-webpack5';
const config: StorybookConfig = {
framework: { name: 'foo', options: { bar: require('baz') } },
"otherField": { "name": 'foo', options: { bar: require('baz') } },
}
export default config;
`;
const config = loadConfig(source).parse();
expect(config.getNameFromPath(['framework'])).toEqual('foo');
expect(config.getNameFromPath(['otherField'])).toEqual('foo');
});
it(`returns undefined when accessing a field that does not exist`, () => {
const source = dedent`
import type { StorybookConfig } from '@storybook/react-webpack5';
const config: StorybookConfig = { }
export default config;
`;
const config = loadConfig(source).parse();
expect(config.getNameFromPath(['framework'])).toBeUndefined();
});
it(`throws an error when node is of unexpected type`, () => {
const source = dedent`
import type { StorybookConfig } from '@storybook/react-webpack5';
const config: StorybookConfig = {
framework: makesNoSense(),
}
export default config;
`;
const config = loadConfig(source).parse();
expect(() => config.getNameFromPath(['framework'])).toThrowError(
`The given node must be a string literal or an object expression with a "name" property that is a string literal.`
);
});
});
describe('getNamesFromPath', () => {
it(`supports an array with string literal and object expression with name property`, () => {
const source = dedent`
import type { StorybookConfig } from '@storybook/react-webpack5';
const config: StorybookConfig = {
addons: [
'foo',
{ name: 'bar', options: {} },
],
"otherField": [
"foo",
{ "name": 'bar', options: {} },
],
}
export default config;
`;
const config = loadConfig(source).parse();
expect(config.getNamesFromPath(['addons'])).toEqual(['foo', 'bar']);
expect(config.getNamesFromPath(['otherField'])).toEqual(['foo', 'bar']);
});
describe('satisfies', () => {
describe('default export', () => {
it(`supports an array with string literal and object expression with name property`, () => {
const source = dedent`
import type { StorybookConfig } from '@storybook/react-webpack5';
const config = {
addons: [
'foo',
{ name: 'bar', options: {} },
],
"otherField": [
"foo",
{ "name": 'bar', options: {} },
],
} satisfies StorybookConfig
export default config;
`;
const config = loadConfig(source).parse();
expect(config.getNamesFromPath(['addons'])).toEqual(['foo', 'bar']);
expect(config.getNamesFromPath(['otherField'])).toEqual(['foo', 'bar']);
});
it(`supports an array with string literal and object expression with name property without variable`, () => {
const source = dedent`
import type { StorybookConfig } from '@storybook/react-webpack5';
export default {
addons: [
'foo',
{ name: 'bar', options: {} },
],
"otherField": [
"foo",
{ "name": 'bar', options: {} },
],
} satisfies StorybookConfig;
`;
const config = loadConfig(source).parse();
expect(config.getNamesFromPath(['addons'])).toEqual(['foo', 'bar']);
expect(config.getNamesFromPath(['otherField'])).toEqual(['foo', 'bar']);
});
});
describe('module exports', () => {
it(`supports an array with string literal and object expression with name property`, () => {
const source = dedent`
import type { StorybookConfig } from '@storybook/react-webpack5';
const config = {
addons: [
'foo',
{ name: 'bar', options: {} },
],
"otherField": [
"foo",
{ "name": 'bar', options: {} },
],
} satisfies StorybookConfig
module.exports = config;
`;
const config = loadConfig(source).parse();
expect(config.getNamesFromPath(['addons'])).toEqual(['foo', 'bar']);
expect(config.getNamesFromPath(['otherField'])).toEqual(['foo', 'bar']);
});
it(`supports an array with string literal and object expression with name property without variable`, () => {
const source = dedent`
import type { StorybookConfig } from '@storybook/react-webpack5';
module.exports = {
addons: [
'foo',
{ name: 'bar', options: {} },
],
"otherField": [
"foo",
{ "name": 'bar', options: {} },
],
} satisfies StorybookConfig;
`;
const config = loadConfig(source).parse();
expect(config.getNamesFromPath(['addons'])).toEqual(['foo', 'bar']);
expect(config.getNamesFromPath(['otherField'])).toEqual(['foo', 'bar']);
});
});
});
});
it(`returns undefined when accessing a field that does not exist`, () => {
const source = dedent`
import type { StorybookConfig } from '@storybook/react-webpack5';
const config: StorybookConfig = { }
export default config;
`;
const config = loadConfig(source).parse();
expect(config.getNamesFromPath(['addons'])).toBeUndefined();
});
});
describe('setImport', () => {
it(`supports setting a default import for a field that does not exist`, () => {
const source = dedent`
const config: StorybookConfig = { };
export default config;
`;
const config = loadConfig(source).parse();
config.setImport('path', 'path');
// eslint-disable-next-line no-underscore-dangle
const parsed = babelPrint(config._ast);
expect(parsed).toMatchInlineSnapshot(`
import path from 'path';
const config: StorybookConfig = { };
export default config;
`);
});
it(`supports setting a default import for a field that does exist`, () => {
const source = dedent`
const config: StorybookConfig = { };
export default config;
`;
const config = loadConfig(source).parse();
config.setImport('path', 'path');
// eslint-disable-next-line no-underscore-dangle
const parsed = babelPrint(config._ast);
expect(parsed).toMatchInlineSnapshot(`
import path from 'path';
const config: StorybookConfig = { };
export default config;
`);
});
it(`supports setting a named import for a field that does not exist`, () => {
const source = dedent`
const config: StorybookConfig = { };
export default config;
`;
const config = loadConfig(source).parse();
config.setImport(['dirname'], 'path');
// eslint-disable-next-line no-underscore-dangle
const parsed = babelPrint(config._ast);
expect(parsed).toMatchInlineSnapshot(`
import { dirname } from 'path';
const config: StorybookConfig = { };
export default config;
`);
});
it(`supports setting a named import for a field where the source already exists`, () => {
const source = dedent`
import { dirname } from 'path';
const config: StorybookConfig = { };
export default config;
`;
const config = loadConfig(source).parse();
config.setImport(['dirname'], 'path');
// eslint-disable-next-line no-underscore-dangle
const parsed = babelPrint(config._ast);
expect(parsed).toMatchInlineSnapshot(`
import { dirname } from 'path';
const config: StorybookConfig = { };
export default config;
`);
});
});
describe('setRequireImport', () => {
it(`supports setting a default import for a field that does not exist`, () => {
const source = dedent`
const config: StorybookConfig = { };
export default config;
`;
const config = loadConfig(source).parse();
config.setRequireImport('path', 'path');
// eslint-disable-next-line no-underscore-dangle
const parsed = babelPrint(config._ast);
expect(parsed).toMatchInlineSnapshot(`
const path = require('path');
const config: StorybookConfig = { };
export default config;
`);
});
it(`supports setting a default import for a field that does exist`, () => {
const source = dedent`
const path = require('path');
const config: StorybookConfig = { };
export default config;
`;
const config = loadConfig(source).parse();
config.setRequireImport('path', 'path');
// eslint-disable-next-line no-underscore-dangle
const parsed = babelPrint(config._ast);
expect(parsed).toMatchInlineSnapshot(`
const path = require('path');
const config: StorybookConfig = { };
export default config;
`);
});
it(`supports setting a named import for a field that does not exist`, () => {
const source = dedent`
const config: StorybookConfig = { };
export default config;
`;
const config = loadConfig(source).parse();
config.setRequireImport(['dirname'], 'path');
// eslint-disable-next-line no-underscore-dangle
const parsed = babelPrint(config._ast);
expect(parsed).toMatchInlineSnapshot(`
const {
dirname,
} = require('path');
const config: StorybookConfig = { };
export default config;
`);
});
it(`supports setting a named import for a field where the source already exists`, () => {
const source = dedent`
const { dirname } = require('path');
const config: StorybookConfig = { };
export default config;
`;
const config = loadConfig(source).parse();
config.setRequireImport(['dirname', 'basename'], 'path');
// eslint-disable-next-line no-underscore-dangle
const parsed = babelPrint(config._ast);
expect(parsed).toMatchInlineSnapshot(`
const {
dirname,
basename,
} = require('path');
const config: StorybookConfig = { };
export default config;
`);
});
});
});
|
943 | 0 | petrpan-code/storybookjs/storybook/code/lib/csf-tools | petrpan-code/storybookjs/storybook/code/lib/csf-tools/src/CsfFile.test.ts | /// <reference types="@types/jest" />;
/* eslint-disable no-underscore-dangle */
import { dedent } from 'ts-dedent';
import yaml from 'js-yaml';
import { loadCsf } from './CsfFile';
expect.addSnapshotSerializer({
print: (val: any) => yaml.dump(val).trimEnd(),
test: (val) => typeof val !== 'string',
});
const makeTitle = (userTitle?: string) => {
return userTitle || 'Default Title';
};
const parse = (code: string, includeParameters?: boolean) => {
const { stories, meta } = loadCsf(code, { makeTitle }).parse();
const filtered = includeParameters ? stories : stories.map(({ parameters, ...rest }) => rest);
return { meta, stories: filtered };
};
//
describe('CsfFile', () => {
describe('basic', () => {
it('args stories', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar' };
export const A = () => {};
export const B = (args) => {};
`,
true
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--a
name: A
parameters:
__isArgsStory: false
__id: foo-bar--a
- id: foo-bar--b
name: B
parameters:
__isArgsStory: true
__id: foo-bar--b
`);
});
it('exported const stories', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar' };
const A = () => {};
const B = (args) => {};
export { A, B };
`,
true
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--a
name: A
parameters:
__id: foo-bar--a
- id: foo-bar--b
name: B
parameters:
__id: foo-bar--b
`);
});
it('underscores', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar' };
export const __Basic__ = () => {};
`,
true
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--basic
name: Basic
parameters:
__isArgsStory: false
__id: foo-bar--basic
`);
});
it('exclude stories', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar', excludeStories: ['B', 'C'] };
export const A = () => {};
export const B = (args) => {};
export const C = () => {};
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
excludeStories:
- B
- C
stories:
- id: foo-bar--a
name: A
`);
});
it('include stories', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar', includeStories: ['IncludeA'] };
export const SomeHelper = () => {};
export const IncludeA = () => {};
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
includeStories:
- IncludeA
stories:
- id: foo-bar--include-a
name: Include A
`);
});
it('storyName annotation', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar' };
export const A = () => {};
A.storyName = 'Some story';
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--a
name: Some story
`);
});
it('no title', () => {
expect(
parse(
dedent`
export default { component: 'foo' }
export const A = () => {};
export const B = () => {};
`
)
).toMatchInlineSnapshot(`
meta:
component: '''foo'''
title: Default Title
stories:
- id: default-title--a
name: A
- id: default-title--b
name: B
`);
});
it('custom component id', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar', id: 'custom-id' };
export const A = () => {};
export const B = () => {};
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
id: custom-id
stories:
- id: custom-id--a
name: A
- id: custom-id--b
name: B
`);
});
it('custom parameters.__id', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar', id: 'custom-meta-id' };
export const JustCustomMetaId = {};
export const CustomParemetersId = { parameters: { __id: 'custom-id' } };
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
id: custom-meta-id
stories:
- id: custom-meta-id--just-custom-meta-id
name: Just Custom Meta Id
- id: custom-id
name: Custom Paremeters Id
`);
});
it('typescript', () => {
expect(
parse(
dedent`
import type { Meta, StoryFn } from '@storybook/react';
type PropTypes = {};
export default { title: 'foo/bar/baz' } as Meta<PropTypes>;
export const A: StoryFn<PropTypes> = () => <>A</>;
export const B: StoryFn<PropTypes> = () => <>B</>;
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar/baz
stories:
- id: foo-bar-baz--a
name: A
- id: foo-bar-baz--b
name: B
`);
});
it('typescript satisfies', () => {
expect(
parse(
dedent`
import type { Meta, StoryFn, StoryObj } from '@storybook/react';
type PropTypes = {};
export default { title: 'foo/bar' } satisfies Meta<PropTypes>;
export const A = { name: 'AA' } satisfies StoryObj<PropTypes>;
export const B = ((args) => {}) satisfies StoryFn<PropTypes>;
`,
true
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--a
name: AA
parameters:
__isArgsStory: true
__id: foo-bar--a
- id: foo-bar--b
name: B
parameters:
__isArgsStory: true
__id: foo-bar--b
`);
});
it('typescript as', () => {
expect(
parse(
dedent`
import type { Meta, StoryFn, StoryObj } from '@storybook/react';
type PropTypes = {};
export default { title: 'foo/bar' } as Meta<PropTypes>;
export const A = { name: 'AA' } as StoryObj<PropTypes>;
export const B = ((args) => {}) as StoryFn<PropTypes>;
`,
true
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--a
name: AA
parameters:
__isArgsStory: true
__id: foo-bar--a
- id: foo-bar--b
name: B
parameters:
__isArgsStory: true
__id: foo-bar--b
`);
});
it('typescript meta var', () => {
expect(
parse(
dedent`
import type { Meta, StoryFn } from '@storybook/react';
type PropTypes = {};
const meta = { title: 'foo/bar/baz' } as Meta<PropTypes>;
export default meta;
export const A: StoryFn<PropTypes> = () => <>A</>;
export const B: StoryFn<PropTypes> = () => <>B</>;
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar/baz
stories:
- id: foo-bar-baz--a
name: A
- id: foo-bar-baz--b
name: B
`);
});
it('typescript satisfies meta var', () => {
expect(
parse(
dedent`
import type { Meta, StoryFn } from '@storybook/react';
type PropTypes = {};
const meta = { title: 'foo/bar/baz' } satisfies Meta<PropTypes>;
export default meta;
export const A: StoryFn<PropTypes> = () => <>A</>;
export const B: StoryFn<PropTypes> = () => <>B</>;
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar/baz
stories:
- id: foo-bar-baz--a
name: A
- id: foo-bar-baz--b
name: B
`);
});
it('component object', () => {
expect(
parse(
dedent`
export default { component: {} }
export const A = () => {};
export const B = () => {};
`
)
).toMatchInlineSnapshot(`
meta:
component: '{}'
title: Default Title
stories:
- id: default-title--a
name: A
- id: default-title--b
name: B
`);
});
it('template bind', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar' };
const Template = (args) => { };
export const A = Template.bind({});
A.args = { x: 1 };
`,
true
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--a
name: A
parameters:
__isArgsStory: true
__id: foo-bar--a
`);
});
it('meta variable', () => {
expect(
parse(
dedent`
const meta = { title: 'foo/bar' };
export default meta;
export const A = () => {}
`,
true
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--a
name: A
parameters:
__isArgsStory: false
__id: foo-bar--a
`);
});
it('docs-only story', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar' };
export const __page = () => {};
__page.parameters = { docsOnly: true };
`,
true
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--page
name: Page
parameters:
__isArgsStory: false
__id: foo-bar--page
docsOnly: true
`);
});
it('docs-only story with local vars', () => {
expect(
parse(
dedent`
export const TestControl = () => _jsx("p", {
children: "Hello"
});
export default { title: 'foo/bar', tags: ['stories-mdx'], includeStories: ["__page"] };
export const __page = () => {};
__page.parameters = { docsOnly: true };
`,
true
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
tags:
- stories-mdx
includeStories:
- __page
stories:
- id: foo-bar--page
name: Page
parameters:
__isArgsStory: false
__id: foo-bar--page
docsOnly: true
`);
});
it('title variable', () => {
expect(
parse(
dedent`
const title = 'foo/bar';
export default { title };
export const A = () => {};
export const B = (args) => {};
`,
true
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--a
name: A
parameters:
__isArgsStory: false
__id: foo-bar--a
- id: foo-bar--b
name: B
parameters:
__isArgsStory: true
__id: foo-bar--b
`);
});
it('re-exported stories', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar' };
export { default as A } from './A';
export { B } from './B';
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--a
name: A
- id: foo-bar--b
name: B
`);
});
it('named exports order', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar' };
export const A = () => {};
export const B = (args) => {};
export const __namedExportsOrder = ['B', 'A'];
`,
true
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--b
name: B
parameters:
__isArgsStory: true
__id: foo-bar--b
- id: foo-bar--a
name: A
parameters:
__isArgsStory: false
__id: foo-bar--a
`);
});
it('as default export', () => {
expect(
parse(
dedent`
const meta = { title: 'foo/bar' };
export const A = () => {};
export {
meta as default,
A
};
`,
true
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--a
name: A
parameters:
__id: foo-bar--a
`);
});
it('support for parameter decorators', () => {
expect(
parse(dedent`
import { Component, Input, Output, EventEmitter, Inject, HostBinding } from '@angular/core';
import { CHIP_COLOR } from './chip-color.token';
@Component({
selector: 'storybook-chip',
})
export class ChipComponent {
// The error occurs on the Inject decorator used on a parameter
constructor(@Inject(CHIP_COLOR) chipColor: string) {
this.backgroundColor = chipColor;
}
}
export default {
title: 'Chip',
}
`)
).toMatchInlineSnapshot(`
meta:
title: Chip
stories: []
`);
});
});
describe('error handling', () => {
it('no meta', () => {
expect(() =>
parse(
dedent`
export const A = () => {};
export const B = () => {};
`
)
).toThrow('CSF: missing default export');
});
it('bad meta', () => {
expect(() =>
parse(
dedent`
const foo = bar();
export default foo;
export const A = () => {};
export const B = () => {};
`
)
).toThrow('CSF: default export must be an object');
});
it('no metadata', () => {
expect(() =>
parse(
dedent`
export default { foo: '5' };
export const A = () => {};
export const B = () => {};
`
)
).toThrow('CSF: missing title/component');
});
it('dynamic titles', () => {
expect(() =>
parse(
dedent`
export default { title: 'foo' + 'bar' };
export const A = () => {};
`,
true
)
).toThrow('CSF: unexpected dynamic title');
});
it('storiesOf calls', () => {
expect(() =>
parse(
dedent`
import { storiesOf } from '@storybook/react';
export default { title: 'foo/bar' };
export const A = () => {};
storiesOf('foo').add('bar', () => <baz />);
`,
true
)
).toThrow('Unexpected `storiesOf` usage:');
});
it('function exports', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar' };
export function A() {}
export function B() {}
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--a
name: A
- id: foo-bar--b
name: B
`);
});
});
// NOTE: this does not have a public API, but we can still test it
describe('indexed annotations', () => {
it('meta annotations', () => {
const input = dedent`
export default { title: 'foo/bar', x: 1, y: 2 };
`;
const csf = loadCsf(input, { makeTitle }).parse();
expect(Object.keys(csf._metaAnnotations)).toEqual(['title', 'x', 'y']);
});
it('story annotations', () => {
const input = dedent`
export default { title: 'foo/bar' };
export const A = () => {};
A.x = 1;
A.y = 2;
export const B = () => {};
B.z = 3;
`;
const csf = loadCsf(input, { makeTitle }).parse();
expect(Object.keys(csf._storyAnnotations.A)).toEqual(['x', 'y']);
expect(Object.keys(csf._storyAnnotations.B)).toEqual(['z']);
});
it('v1-style story annotations', () => {
const input = dedent`
export default { title: 'foo/bar' };
export const A = () => {};
A.story = {
x: 1,
y: 2,
}
export const B = () => {};
B.story = {
z: 3,
}
`;
const csf = loadCsf(input, { makeTitle }).parse();
expect(Object.keys(csf._storyAnnotations.A)).toEqual(['x', 'y']);
expect(Object.keys(csf._storyAnnotations.B)).toEqual(['z']);
});
});
describe('CSF3', () => {
it('Object export with no-args render', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar' };
export const A = {
render: () => {}
}
`,
true
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--a
name: A
parameters:
__isArgsStory: false
__id: foo-bar--a
`);
});
it('Object export with args render', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar' };
export const A = {
render: (args) => {}
}
`,
true
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--a
name: A
parameters:
__isArgsStory: true
__id: foo-bar--a
`);
});
it('Object export with default render', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar' };
export const A = {}
`,
true
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--a
name: A
parameters:
__isArgsStory: true
__id: foo-bar--a
`);
});
it('Object export with name', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar' };
export const A = {
name: 'Apple'
}
`,
true
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
stories:
- id: foo-bar--a
name: Apple
parameters:
__isArgsStory: true
__id: foo-bar--a
`);
});
it('Object export with storyName', () => {
const consoleWarnMock = jest.spyOn(console, 'warn').mockImplementation();
parse(
dedent`
export default { title: 'foo/bar' };
export const A = {
storyName: 'Apple'
}
`,
true
);
expect(consoleWarnMock).toHaveBeenCalledWith(
'Unexpected usage of "storyName" in "A". Please use "name" instead.'
);
consoleWarnMock.mockRestore();
});
});
describe('import handling', () => {
it('imports', () => {
const input = dedent`
import Button from './Button';
import { Check } from './Check';
export default { title: 'foo/bar', x: 1, y: 2 };
`;
const csf = loadCsf(input, { makeTitle }).parse();
expect(csf.imports).toMatchInlineSnapshot(`
- ./Button
- ./Check
`);
});
// eslint-disable-next-line jest/no-disabled-tests
it.skip('dynamic imports', () => {
const input = dedent`
const Button = await import('./Button');
export default { title: 'foo/bar', x: 1, y: 2 };
`;
const csf = loadCsf(input, { makeTitle }).parse();
expect(csf.imports).toMatchInlineSnapshot();
});
// eslint-disable-next-line jest/no-disabled-tests
it.skip('requires', () => {
const input = dedent`
const Button = require('./Button');
export default { title: 'foo/bar', x: 1, y: 2 };
`;
const csf = loadCsf(input, { makeTitle }).parse();
expect(csf.imports).toMatchInlineSnapshot();
});
});
describe('tags', () => {
it('csf2', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar', tags: ['X'] };
export const A = () => {};
A.tags = ['Y'];
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
tags:
- X
stories:
- id: foo-bar--a
name: A
tags:
- 'Y'
`);
});
it('csf3', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar', tags: ['X'] };
export const A = {
render: () => {},
tags: ['Y'],
};
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
tags:
- X
stories:
- id: foo-bar--a
name: A
tags:
- 'Y'
`);
});
it('variables', () => {
expect(
parse(
dedent`
const x = ['X'];
const y = ['Y'];
export default { title: 'foo/bar', tags: x };
export const A = {
render: () => {},
tags: y,
};
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
tags:
- X
stories:
- id: foo-bar--a
name: A
tags:
- 'Y'
`);
});
it('array error', () => {
expect(() =>
parse(
dedent`
export default { title: 'foo/bar', tags: 'X' };
export const A = {
render: () => {},
};
`
)
).toThrow('CSF: Expected tags array');
});
it('array element handling', () => {
expect(() =>
parse(
dedent`
export default { title: 'foo/bar', tags: [10] };
export const A = {
render: () => {},
};
`
)
).toThrow('CSF: Expected tag to be string literal');
});
});
describe('play functions', () => {
it('story csf2', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar', tags: ['X'] };
export const A = () => {};
A.play = () => {};
A.tags = ['Y'];
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
tags:
- X
stories:
- id: foo-bar--a
name: A
tags:
- 'Y'
- play-fn
`);
});
it('story csf3', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar', tags: ['X'] };
export const A = {
render: () => {},
play: () => {},
tags: ['Y'],
};
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
tags:
- X
stories:
- id: foo-bar--a
name: A
tags:
- 'Y'
- play-fn
`);
});
it('meta csf2', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar', play: () => {}, tags: ['X'] };
export const A = {
render: () => {},
tags: ['Y'],
};
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
tags:
- X
- play-fn
stories:
- id: foo-bar--a
name: A
tags:
- 'Y'
`);
});
it('meta csf3', () => {
expect(
parse(
dedent`
export default { title: 'foo/bar', play: () => {}, tags: ['X'] };
export const A = () => {};
A.tags = ['Y'];
`
)
).toMatchInlineSnapshot(`
meta:
title: foo/bar
tags:
- X
- play-fn
stories:
- id: foo-bar--a
name: A
tags:
- 'Y'
`);
});
});
describe('index inputs', () => {
it('generates index inputs', () => {
const { indexInputs } = loadCsf(
dedent`
export default {
id: 'component-id',
title: 'custom foo title',
tags: ['component-tag']
};
export const A = {
play: () => {},
tags: ['story-tag'],
};
export const B = {
play: () => {},
tags: ['story-tag'],
};
`,
{ makeTitle, fileName: 'foo/bar.stories.js' }
).parse();
expect(indexInputs).toMatchInlineSnapshot(`
- type: story
importPath: foo/bar.stories.js
exportName: A
name: A
title: custom foo title
metaId: component-id
tags:
- component-tag
- story-tag
- play-fn
__id: component-id--a
- type: story
importPath: foo/bar.stories.js
exportName: B
name: B
title: custom foo title
metaId: component-id
tags:
- component-tag
- story-tag
- play-fn
__id: component-id--b
`);
});
it('supports custom parameters.__id', () => {
const { indexInputs } = loadCsf(
dedent`
export default {
id: 'component-id',
title: 'custom foo title',
tags: ['component-tag']
};
export const A = {
parameters: { __id: 'custom-story-id' }
};
`,
{ makeTitle, fileName: 'foo/bar.stories.js' }
).parse();
expect(indexInputs).toMatchInlineSnapshot(`
- type: story
importPath: foo/bar.stories.js
exportName: A
name: A
title: custom foo title
metaId: component-id
tags:
- component-tag
__id: custom-story-id
`);
});
it('removes duplicate tags', () => {
const { indexInputs } = loadCsf(
dedent`
export default {
title: 'custom foo title',
tags: ['component-tag', 'component-tag-dup', 'component-tag-dup', 'inherit-tag-dup']
};
export const A = {
tags: ['story-tag', 'story-tag-dup', 'story-tag-dup', 'inherit-tag-dup']
};
`,
{ makeTitle, fileName: 'foo/bar.stories.js' }
).parse();
expect(indexInputs).toMatchInlineSnapshot(`
- type: story
importPath: foo/bar.stories.js
exportName: A
name: A
title: custom foo title
tags:
- component-tag
- component-tag-dup
- inherit-tag-dup
- story-tag
- story-tag-dup
__id: custom-foo-title--a
`);
});
it('throws if getting indexInputs without filename option', () => {
const csf = loadCsf(
dedent`
export default {
title: 'custom foo title',
tags: ['component-tag', 'component-tag-dup', 'component-tag-dup', 'inherit-tag-dup']
};
export const A = {
tags: ['story-tag', 'story-tag-dup', 'story-tag-dup', 'inherit-tag-dup']
};
`,
{ makeTitle }
).parse();
expect(() => csf.indexInputs).toThrowErrorMatchingInlineSnapshot(`
"Cannot automatically create index inputs with CsfFile.indexInputs because the CsfFile instance was created without a the fileName option.
Either add the fileName option when creating the CsfFile instance, or create the index inputs manually."
`);
});
});
});
|
946 | 0 | petrpan-code/storybookjs/storybook/code/lib/csf-tools | petrpan-code/storybookjs/storybook/code/lib/csf-tools/src/enrichCsf.test.ts | /// <reference types="@types/jest" />;
/* eslint-disable no-underscore-dangle */
import { dedent } from 'ts-dedent';
import { formatCsf, loadCsf } from './CsfFile';
import type { EnrichCsfOptions } from './enrichCsf';
import { enrichCsf, extractSource } from './enrichCsf';
expect.addSnapshotSerializer({
print: (val: any) => val,
test: (val) => true,
});
const enrich = (code: string, options?: EnrichCsfOptions) => {
// we don't actually care about the title
const csf = loadCsf(code, { makeTitle: (userTitle) => userTitle || 'default' }).parse();
enrichCsf(csf, options);
return formatCsf(csf);
};
describe('enrichCsf', () => {
describe('source', () => {
it('csf1', () => {
expect(
enrich(dedent`
export default {
title: 'Button',
}
export const Basic = () => <Button />
`)
).toMatchInlineSnapshot(`
export default {
title: 'Button'
};
export const Basic = () => <Button />;
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "() => <Button />",
...Basic.parameters?.docs?.source
}
}
};
`);
});
it('csf2', () => {
expect(
enrich(dedent`
export default {
title: 'Button',
}
const Template = (args) => <Button {...args} />
export const Basic = Template.bind({});
Basic.parameters = { foo: 'bar' }
`)
).toMatchInlineSnapshot(`
export default {
title: 'Button'
};
const Template = args => <Button {...args} />;
export const Basic = Template.bind({});
Basic.parameters = {
foo: 'bar'
};
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "args => <Button {...args} />",
...Basic.parameters?.docs?.source
}
}
};
`);
});
it('csf3', () => {
expect(
enrich(dedent`
export default {
title: 'Button',
}
export const Basic = {
parameters: { foo: 'bar' }
}
`)
).toMatchInlineSnapshot(`
export default {
title: 'Button'
};
export const Basic = {
parameters: {
foo: 'bar'
}
};
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "{\\n parameters: {\\n foo: 'bar'\\n }\\n}",
...Basic.parameters?.docs?.source
}
}
};
`);
});
it('multiple stories', () => {
expect(
enrich(dedent`
export default {
title: 'Button',
}
export const A = {}
export const B = {}
`)
).toMatchInlineSnapshot(`
export default {
title: 'Button'
};
export const A = {};
export const B = {};
A.parameters = {
...A.parameters,
docs: {
...A.parameters?.docs,
source: {
originalSource: "{}",
...A.parameters?.docs?.source
}
}
};
B.parameters = {
...B.parameters,
docs: {
...B.parameters?.docs,
source: {
originalSource: "{}",
...B.parameters?.docs?.source
}
}
};
`);
});
});
describe('story descriptions', () => {
it('skips inline comments', () => {
expect(
enrich(dedent`
export default {
title: 'Button',
}
// The most basic button
export const Basic = () => <Button />
`)
).toMatchInlineSnapshot(`
export default {
title: 'Button'
};
// The most basic button
export const Basic = () => <Button />;
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "() => <Button />",
...Basic.parameters?.docs?.source
}
}
};
`);
});
it('skips blocks without jsdoc', () => {
expect(
enrich(dedent`
export default {
title: 'Button',
}
/* The most basic button */
export const Basic = () => <Button />
`)
).toMatchInlineSnapshot(`
export default {
title: 'Button'
};
/* The most basic button */
export const Basic = () => <Button />;
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "() => <Button />",
...Basic.parameters?.docs?.source
}
}
};
`);
});
it('JSDoc single-line', () => {
expect(
enrich(dedent`
export default {
title: 'Button',
}
/** The most basic button */
export const Basic = () => <Button />
`)
).toMatchInlineSnapshot(`
export default {
title: 'Button'
};
/** The most basic button */
export const Basic = () => <Button />;
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "() => <Button />",
...Basic.parameters?.docs?.source
},
description: {
story: "The most basic button",
...Basic.parameters?.docs?.description
}
}
};
`);
});
it('JSDoc multi-line', () => {
expect(
enrich(dedent`
export default {
title: 'Button',
}
/**
* The most basic button
*
* In a block!
*/
export const Basic = () => <Button />
`)
).toMatchInlineSnapshot(`
export default {
title: 'Button'
};
/**
* The most basic button
*
* In a block!
*/
export const Basic = () => <Button />;
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "() => <Button />",
...Basic.parameters?.docs?.source
},
description: {
story: "The most basic button\\n\\nIn a block!",
...Basic.parameters?.docs?.description
}
}
};
`);
});
it('preserves indentation', () => {
expect(
enrich(dedent`
export default {
title: 'Button',
}
/**
* - A bullet list
* - A sub-bullet
* - A second bullet
*/
export const Basic = () => <Button />
`)
).toMatchInlineSnapshot(`
export default {
title: 'Button'
};
/**
* - A bullet list
* - A sub-bullet
* - A second bullet
*/
export const Basic = () => <Button />;
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "() => <Button />",
...Basic.parameters?.docs?.source
},
description: {
story: "- A bullet list\\n - A sub-bullet\\n- A second bullet",
...Basic.parameters?.docs?.description
}
}
};
`);
});
});
describe('meta descriptions', () => {
it('skips inline comments', () => {
expect(
enrich(dedent`
// The most basic button
export default {
title: 'Button',
}
export const Basic = () => <Button />
`)
).toMatchInlineSnapshot(`
// The most basic button
export default {
title: 'Button'
};
export const Basic = () => <Button />;
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "() => <Button />",
...Basic.parameters?.docs?.source
}
}
};
`);
});
it('skips blocks without jsdoc', () => {
expect(
enrich(dedent`
/* The most basic button */
export default {
title: 'Button',
}
export const Basic = () => <Button />
`)
).toMatchInlineSnapshot(`
/* The most basic button */
export default {
title: 'Button'
};
export const Basic = () => <Button />;
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "() => <Button />",
...Basic.parameters?.docs?.source
}
}
};
`);
});
it('JSDoc single-line', () => {
expect(
enrich(dedent`
/** The most basic button */
export default {
title: 'Button'
}
export const Basic = () => <Button />
`)
).toMatchInlineSnapshot(`
/** The most basic button */
export default {
title: 'Button',
parameters: {
docs: {
description: {
component: "The most basic button"
}
}
}
};
export const Basic = () => <Button />;
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "() => <Button />",
...Basic.parameters?.docs?.source
}
}
};
`);
});
it('JSDoc multi-line', () => {
expect(
enrich(dedent`
/**
* The most basic button
*
* In a block!
*/
export default {
title: 'Button',
}
export const Basic = () => <Button />
`)
).toMatchInlineSnapshot(`
/**
* The most basic button
*
* In a block!
*/
export default {
title: 'Button',
parameters: {
docs: {
description: {
component: "The most basic button\\n\\nIn a block!"
}
}
}
};
export const Basic = () => <Button />;
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "() => <Button />",
...Basic.parameters?.docs?.source
}
}
};
`);
});
it('preserves indentation', () => {
expect(
enrich(dedent`
/**
* - A bullet list
* - A sub-bullet
* - A second bullet
*/
export default {
title: 'Button',
}
export const Basic = () => <Button />
`)
).toMatchInlineSnapshot(`
/**
* - A bullet list
* - A sub-bullet
* - A second bullet
*/
export default {
title: 'Button',
parameters: {
docs: {
description: {
component: "- A bullet list\\n - A sub-bullet\\n- A second bullet"
}
}
}
};
export const Basic = () => <Button />;
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "() => <Button />",
...Basic.parameters?.docs?.source
}
}
};
`);
});
it('correctly interleaves parameters', () => {
expect(
enrich(dedent`
/** The most basic button */
export default {
title: 'Button',
parameters: {
foo: 'bar',
docs: { inlineStories: true }
}
}
export const Basic = () => <Button />
`)
).toMatchInlineSnapshot(`
/** The most basic button */
export default {
title: 'Button',
parameters: {
foo: 'bar',
docs: {
inlineStories: true,
description: {
component: "The most basic button"
}
}
}
};
export const Basic = () => <Button />;
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "() => <Button />",
...Basic.parameters?.docs?.source
}
}
};
`);
});
it('respects user component description', () => {
expect(
enrich(dedent`
/** The most basic button */
export default {
title: 'Button',
parameters: {
docs: {
description: {
component: 'hahaha'
}
}
}
}
export const Basic = () => <Button />
`)
).toMatchInlineSnapshot(`
/** The most basic button */
export default {
title: 'Button',
parameters: {
docs: {
description: {
component: 'hahaha'
}
}
}
};
export const Basic = () => <Button />;
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "() => <Button />",
...Basic.parameters?.docs?.source
}
}
};
`);
});
it('respects meta variables', () => {
expect(
enrich(dedent`
/** The most basic button */
const meta = {
title: 'Button'
}
/** This should be ignored */
export default meta;
export const Basic = () => <Button />
`)
).toMatchInlineSnapshot(`
/** The most basic button */
const meta = {
title: 'Button',
parameters: {
docs: {
description: {
component: "The most basic button"
}
}
}
};
/** This should be ignored */
export default meta;
export const Basic = () => <Button />;
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "() => <Button />",
...Basic.parameters?.docs?.source
}
}
};
`);
});
});
describe('options', () => {
it('disableSource', () => {
expect(
enrich(
dedent`
export default {
title: 'Button',
}
/** The most basic button */
export const Basic = () => <Button />
`,
{ disableSource: true }
)
).toMatchInlineSnapshot(`
export default {
title: 'Button'
};
/** The most basic button */
export const Basic = () => <Button />;
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
description: {
story: "The most basic button",
...Basic.parameters?.docs?.description
}
}
};
`);
});
it('disableDescription', () => {
expect(
enrich(
dedent`
export default {
title: 'Button',
}
/** The most basic button */
export const Basic = () => <Button />
`,
{ disableDescription: true }
)
).toMatchInlineSnapshot(`
export default {
title: 'Button'
};
/** The most basic button */
export const Basic = () => <Button />;
Basic.parameters = {
...Basic.parameters,
docs: {
...Basic.parameters?.docs,
source: {
originalSource: "() => <Button />",
...Basic.parameters?.docs?.source
}
}
};
`);
});
it('disable all', () => {
expect(
enrich(
dedent`
export default {
title: 'Button',
}
/** The most basic button */
export const Basic = () => <Button />
`,
{ disableSource: true, disableDescription: true }
)
).toMatchInlineSnapshot(`
export default {
title: 'Button'
};
/** The most basic button */
export const Basic = () => <Button />;
`);
});
});
});
const source = (csfExport: string) => {
const code = dedent`
export default { title: 'Button' }
${csfExport}
`;
const csf = loadCsf(code, { makeTitle: (userTitle) => userTitle }).parse();
const exportNode = Object.values(csf._storyExports)[0];
return extractSource(exportNode);
};
describe('extractSource', () => {
it('csf1', () => {
expect(
source(dedent`
export const Basic = () => <Button />
`)
).toMatchInlineSnapshot(`() => <Button />`);
});
it('csf2', () => {
expect(
source(dedent`
export const Basic = (args) => <Button {...args} />;
`)
).toMatchInlineSnapshot(`args => <Button {...args} />`);
});
it('csf3', () => {
expect(
source(dedent`
export const Basic = {
parameters: { foo: 'bar' }
}
`)
).toMatchInlineSnapshot(`
{
parameters: {
foo: 'bar'
}
}
`);
});
});
|
949 | 0 | petrpan-code/storybookjs/storybook/code/lib/csf-tools | petrpan-code/storybookjs/storybook/code/lib/csf-tools/src/getStorySortParameter.test.ts | import { dedent } from 'ts-dedent';
import { getStorySortParameter } from './getStorySortParameter';
describe('getStorySortParameter', () => {
describe('named exports', () => {
describe('supported', () => {
it('no parameters', () => {
expect(
getStorySortParameter(dedent`
export const decorators = [];
`)
).toBeUndefined();
});
it('no storySort parameter', () => {
expect(
getStorySortParameter(dedent`
export const parameters = {
layout: 'fullscreen',
};
`)
).toBeUndefined();
});
it('with wildcards', () => {
expect(
getStorySortParameter(dedent`
export const parameters = {
options: {
storySort: [
"Intro",
"Pages",
["Home", "Login", "Admin"],
"Components",
"*",
"WIP",
]
}
};
`)
).toMatchInlineSnapshot(`
Array [
"Intro",
"Pages",
Array [
"Home",
"Login",
"Admin",
],
"Components",
"*",
"WIP",
]
`);
});
it('arrow function', () => {
expect(
getStorySortParameter(dedent`
export const parameters = {
options: {
storySort: (a, b) =>
a[1].kind === b[1].kind
? 0
: a[1].id.localeCompare(b[1].id, undefined, { numeric: true }),
},
};
`)
).toMatchInlineSnapshot(`[Function]`);
});
it('function', () => {
expect(
getStorySortParameter(dedent`
export const parameters = {
options: {
storySort: function sortStories(a, b) {
return a[1].kind === b[1].kind
? 0
: a[1].id.localeCompare(b[1].id, undefined, { numeric: true });
},
},
};
`)
).toMatchInlineSnapshot(`[Function]`);
});
it('empty sort', () => {
expect(
getStorySortParameter(dedent`
export const parameters = {
options: {
storySort: {
method: "",
order: [],
locales: "",
},
},
};
`)
).toMatchInlineSnapshot(`
Object {
"locales": "",
"method": "",
"order": Array [],
}
`);
});
it('parameters typescript', () => {
expect(
getStorySortParameter(dedent`
export const parameters = {
options: {
storySort: {
method: "",
order: [],
locales: "",
},
},
} as Parameters;
`)
).toMatchInlineSnapshot(`
Object {
"locales": "",
"method": "",
"order": Array [],
}
`);
});
it('parameters typescript satisfies', () => {
expect(
getStorySortParameter(dedent`
export const parameters = {
options: {
storySort: {
method: "",
order: [],
locales: "",
},
},
} satisfies Parameters;
`)
).toMatchInlineSnapshot(`
Object {
"locales": "",
"method": "",
"order": Array [],
}
`);
});
});
describe('unsupported', () => {
it('invalid parameters', () => {
expect(
getStorySortParameter(dedent`
export const parameters = [];
`)
).toBeUndefined();
});
it('parameters var', () => {
expect(
getStorySortParameter(dedent`
const parameters = {
options: {
storySort: {
method: "",
order: [],
locales: "",
},
},
};
export { parameters };
`)
).toBeUndefined();
});
it('options var', () => {
expect(() =>
getStorySortParameter(dedent`
const options = {
storySort: {
method: "",
order: [],
locales: "",
},
};
export const parameters = {
options,
};
`)
).toThrowErrorMatchingInlineSnapshot(`
"Unexpected 'options'. Parameter 'options.storySort' should be defined inline e.g.:
export default {
parameters: {
options: {
storySort: <array | object | function>
},
},
};"
`);
});
it('storySort var', () => {
expect(() =>
getStorySortParameter(dedent`
const storySort = {
method: "",
order: [],
locales: "",
};
export const parameters = {
options: {
storySort,
},
};
`)
).toThrowErrorMatchingInlineSnapshot(`
"Unexpected 'storySort'. Parameter 'options.storySort' should be defined inline e.g.:
export default {
parameters: {
options: {
storySort: <array | object | function>
},
},
};"
`);
});
it('order var', () => {
expect(() =>
getStorySortParameter(dedent`
const order = [];
export const parameters = {
options: {
storySort: {
method: "",
order,
locales: "",
}
},
};
`)
).toThrowErrorMatchingInlineSnapshot(`
"Unexpected 'order'. Parameter 'options.storySort' should be defined inline e.g.:
export default {
parameters: {
options: {
storySort: <array | object | function>
},
},
};"
`);
});
});
});
describe('default export', () => {
describe('supported', () => {
it('inline', () => {
expect(
getStorySortParameter(dedent`
export default {
parameters: {
options: {
storySort: [
"Intro",
"*",
"WIP",
]
}
}
};
`)
).toMatchInlineSnapshot(`
Array [
"Intro",
"*",
"WIP",
]
`);
});
it('no storysort', () => {
expect(
getStorySortParameter(dedent`
const config = {
actions: { argTypesRegex: '^on[A-Z].*' },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
}
export default config
`)
).toBeUndefined();
});
it('variable parameters without storysort', () => {
expect(
getStorySortParameter(dedent`
const parameters = {
actions: { argTypesRegex: '^on[A-Z].*' },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
const preview = {
parameters,
};
export default preview;
`)
).toBeUndefined();
});
it('variable parameters with storysort', () => {
expect(
getStorySortParameter(dedent`
const parameters = {
options: {
storySort: [
"Intro",
"*",
"WIP",
]
}
};
const preview = {
parameters,
};
export default preview;
`)
).toMatchInlineSnapshot(`
Array [
"Intro",
"*",
"WIP",
]
`);
});
it('inline typescript', () => {
expect(
getStorySortParameter(dedent`
export default {
parameters: {
options: {
storySort: [
"Intro",
"*",
"WIP",
]
}
}
} satisfies Preview;
`)
).toMatchInlineSnapshot(`
Array [
"Intro",
"*",
"WIP",
]
`);
});
it('variable', () => {
expect(
getStorySortParameter(dedent`
const preview = {
parameters: {
options: {
storySort: [
"Intro",
"*",
"WIP",
]
}
}
};
export default preview;
`)
).toMatchInlineSnapshot(`
Array [
"Intro",
"*",
"WIP",
]
`);
});
it('typescript var', () => {
expect(
getStorySortParameter(dedent`
const preview: Preview = {
parameters: {
options: {
storySort: [
"Intro",
"*",
"WIP",
]
}
}
};
export default preview;
`)
).toMatchInlineSnapshot(`
Array [
"Intro",
"*",
"WIP",
]
`);
});
it('typescript satisfies var', () => {
expect(
getStorySortParameter(dedent`
const preview = {
parameters: {
options: {
storySort: [
"Intro",
"*",
"WIP",
]
}
}
} satisfies Preview;
export default preview;
`)
).toMatchInlineSnapshot(`
Array [
"Intro",
"*",
"WIP",
]
`);
});
});
describe('unsupported', () => {
it('bad default export', () => {
expect(
getStorySortParameter(dedent`
export default 'foo';
`)
).toBeUndefined();
});
});
});
});
|
960 | 0 | petrpan-code/storybookjs/storybook/code/lib/docs-tools/src | petrpan-code/storybookjs/storybook/code/lib/docs-tools/src/argTypes/enhanceArgTypes.test.ts | import type { ArgTypes, StrictInputType } from '@storybook/types';
import { enhanceArgTypes } from './enhanceArgTypes';
expect.addSnapshotSerializer({
print: (val: any) => JSON.stringify(val, null, 2),
test: (val) => typeof val !== 'string',
});
const enhance = ({
argType,
arg,
extractedArgTypes,
isArgsStory = true,
}: {
argType?: StrictInputType;
arg?: any;
extractedArgTypes?: ArgTypes;
isArgsStory?: boolean;
}) => {
const context = {
componentId: 'foo',
title: 'foo',
kind: 'foo',
id: 'foo--bar',
name: 'bar',
story: 'bar',
component: 'dummy',
parameters: {
__isArgsStory: isArgsStory,
docs: {
extractArgTypes: extractedArgTypes && (() => extractedArgTypes),
},
},
argTypes: argType && { input: argType },
initialArgs: { input: arg },
args: { input: arg },
globals: {},
};
// @ts-expect-error (not strict)
return enhanceArgTypes(context);
};
describe('enhanceArgTypes', () => {
describe('no-args story function', () => {
it('should no-op', () => {
expect(
enhance({
argType: { name: 'input', foo: 'unmodified', type: { name: 'number' } },
isArgsStory: false,
}).input
).toMatchInlineSnapshot(`
{
"name": "input",
"foo": "unmodified",
"type": {
"name": "number"
}
}
`);
});
});
describe('args story function', () => {
describe('single-source input', () => {
describe('argTypes input', () => {
it('number', () => {
expect(
enhance({
argType: { name: 'input', type: { name: 'number' } },
}).input
).toMatchInlineSnapshot(`
{
"name": "input",
"type": {
"name": "number"
}
}
`);
});
});
describe('extraction from component', () => {
it('number', () => {
expect(
enhance({ extractedArgTypes: { input: { name: 'input', type: { name: 'number' } } } })
.input
).toMatchInlineSnapshot(`
{
"name": "input",
"type": {
"name": "number"
}
}
`);
});
});
describe('controls input', () => {
it('range', () => {
expect(
enhance({
argType: { name: 'input', control: { type: 'range', min: 0, max: 100 } },
}).input
).toMatchInlineSnapshot(`
{
"name": "input",
"control": {
"type": "range",
"min": 0,
"max": 100
}
}
`);
});
it('options', () => {
expect(
enhance({
argType: { name: 'input', control: { type: 'radio', options: [1, 2] } },
}).input
).toMatchInlineSnapshot(`
{
"name": "input",
"control": {
"type": "radio",
"options": [
1,
2
]
}
}
`);
});
});
});
describe('mixed-source input', () => {
it('user-specified argTypes take precedence over extracted argTypes', () => {
expect(
enhance({
argType: { name: 'input', type: { name: 'number' } },
extractedArgTypes: { input: { type: { name: 'string' } } },
}).input
).toMatchInlineSnapshot(`
{
"type": {
"name": "number"
},
"name": "input"
}
`);
});
it('user-specified argTypes take precedence over inferred argTypes', () => {
expect(
enhance({
argType: { name: 'input', type: { name: 'number' } },
arg: 'hello',
}).input
).toMatchInlineSnapshot(`
{
"name": "input",
"type": {
"name": "number"
}
}
`);
});
it('extracted argTypes take precedence over inferred argTypes', () => {
expect(
enhance({
extractedArgTypes: { input: { type: { name: 'string' } } },
arg: 6,
}).input
).toMatchInlineSnapshot(`
{
"type": {
"name": "string"
}
}
`);
});
it('user-specified controls take precedence over inferred controls', () => {
expect(
enhance({
argType: { name: 'input', defaultValue: 5, control: { type: 'range', step: 50 } },
arg: 3,
extractedArgTypes: { input: { name: 'input' } },
}).input
).toMatchInlineSnapshot(`
{
"name": "input",
"defaultValue": 5,
"control": {
"type": "range",
"step": 50
}
}
`);
});
it('includes extracted argTypes when there are no user-specified argTypes', () => {
expect(
enhance({
arg: 3,
extractedArgTypes: { input: { name: 'input' }, foo: { type: { name: 'number' } } },
})
).toMatchInlineSnapshot(`
{
"input": {
"name": "input"
},
"foo": {
"type": {
"name": "number"
}
}
}
`);
});
it('includes extracted argTypes when user-specified argTypes match', () => {
expect(
enhance({
argType: { name: 'input', type: { name: 'number' } },
extractedArgTypes: { input: { name: 'input' }, foo: { type: { name: 'number' } } },
})
).toMatchInlineSnapshot(`
{
"input": {
"name": "input",
"type": {
"name": "number"
}
},
"foo": {
"type": {
"name": "number"
}
}
}
`);
});
it('excludes extracted argTypes when user-specified argTypes do not match', () => {
expect(
enhance({
argType: { name: 'input', type: { name: 'number' } },
extractedArgTypes: { foo: { type: { name: 'number' } } },
})
).toMatchInlineSnapshot(`
{
"foo": {
"type": {
"name": "number"
}
},
"input": {
"name": "input",
"type": {
"name": "number"
}
}
}
`);
});
});
});
});
|
963 | 0 | petrpan-code/storybookjs/storybook/code/lib/docs-tools/src | petrpan-code/storybookjs/storybook/code/lib/docs-tools/src/argTypes/jsdocParser.test.ts | import { parseJsDoc } from './jsdocParser';
describe('parseJsDoc', () => {
it('should set includesJsDoc to false when the value is null', () => {
const { includesJsDoc, description, extractedTags } = parseJsDoc(null);
expect(includesJsDoc).toBeFalsy();
expect(description).toBeUndefined();
expect(extractedTags).toBeUndefined();
});
it('should set includesJsDocto to false when the value dont contains JSDoc', () => {
const { includesJsDoc, description, extractedTags } = parseJsDoc('Hey!');
expect(includesJsDoc).toBeFalsy();
expect(description).toBeUndefined();
expect(extractedTags).toBeUndefined();
});
it('should set includesJsDoc to true when the value contains JSDoc', () => {
const { includesJsDoc } = parseJsDoc('Hey!\n@version 1.2');
expect(includesJsDoc).toBeTruthy();
});
it('should remove all JSDoc tags from the description', () => {
const { description } = parseJsDoc('Hey!\n@version 1.2\n@deprecated');
expect(description).toBe('Hey!');
});
describe('@ignore', () => {
it('should set ignore to true when @ignore is present', () => {
const { ignore, description, extractedTags } = parseJsDoc('Hey!\n@ignore');
expect(ignore).toBeTruthy();
expect(description).toBeUndefined();
expect(extractedTags).toBeUndefined();
});
it('should set ignore to false when @ignore is not present', () => {
const { ignore } = parseJsDoc('Hey!\n@version 1.2');
expect(ignore).toBeFalsy();
});
});
describe('@param', () => {
it('should ignore invalid @param tags', () => {
const { extractedTags } = parseJsDoc('@param');
expect(extractedTags.params).toBeNull();
});
it('should return a @param with a name', () => {
const { extractedTags } = parseJsDoc('@param event');
expect(extractedTags.params).not.toBeNull();
expect(extractedTags.params[0].name).toBe('event');
expect(extractedTags.params[0].type).toBeNull();
expect(extractedTags.params[0].description).toBeNull();
});
it('should return a @param with a name and a type', () => {
const { extractedTags } = parseJsDoc('@param {SyntheticEvent} event');
expect(extractedTags.params).not.toBeNull();
expect(extractedTags.params[0].name).toBe('event');
expect(extractedTags.params[0].type).not.toBeNull();
expect(extractedTags.params[0].type.name).toBe('SyntheticEvent');
expect(extractedTags.params[0].description).toBeNull();
});
it('should return a @param with a name, a type and a description', () => {
const { extractedTags } = parseJsDoc('@param {SyntheticEvent} event - React event');
expect(extractedTags.params).not.toBeNull();
expect(extractedTags.params[0].name).toBe('event');
expect(extractedTags.params[0].type).not.toBeNull();
expect(extractedTags.params[0].type.name).toBe('SyntheticEvent');
expect(extractedTags.params[0].description).toBe('React event');
});
it('should support multiple @param tags', () => {
const { extractedTags } = parseJsDoc(
'@param {SyntheticEvent} event1 - React event\n@param {SyntheticEvent} event2 - React event\n@param {SyntheticEvent} event3 - React event'
);
['event1', 'event2', 'event3'].forEach((x, i) => {
expect(extractedTags.params[i].name).toBe(x);
expect(extractedTags.params[i].type).not.toBeNull();
expect(extractedTags.params[i].type.name).toBe('SyntheticEvent');
expect(extractedTags.params[i].description).toBe('React event');
});
});
it('should not return extra @param', () => {
const { extractedTags } = parseJsDoc('@param event');
expect(Object.keys(extractedTags.params).length).toBe(1);
});
it('should support multiline description when there is a @param', () => {
const { description, extractedTags } = parseJsDoc(
'This is a\nmultiline description\n@param event'
);
expect(description).toBe('This is a\nmultiline description');
expect(extractedTags.params).not.toBeNull();
expect(extractedTags.params[0].name).toBe('event');
});
it('should support multiline @param description', () => {
const { extractedTags } = parseJsDoc(
'@param event - This is a\nmultiline description\n@param anotherEvent'
);
expect(extractedTags.params).not.toBeNull();
expect(extractedTags.params[0].name).toBe('event');
expect(extractedTags.params[0].description).toBe('This is a\nmultiline description');
expect(extractedTags.params[1].name).toBe('anotherEvent');
});
['@arg', '@argument'].forEach((x) => {
it(`should support ${x} alias`, () => {
const { extractedTags } = parseJsDoc(`${x} {SyntheticEvent} event - React event`);
expect(extractedTags.params).not.toBeNull();
expect(extractedTags.params[0].name).toBe('event');
expect(extractedTags.params[0].type).not.toBeNull();
expect(extractedTags.params[0].type.name).toBe('SyntheticEvent');
expect(extractedTags.params[0].description).toBe('React event');
});
});
describe('getTypeName', () => {
it('should support record type with a single field', () => {
const { extractedTags } = parseJsDoc('@param {{a: number}} event');
expect(extractedTags.params[0].getTypeName()).toBe('({a: number})');
});
it('should support record type with multiple fields', () => {
const { extractedTags } = parseJsDoc('@param {{a: number, b: string}} event');
expect(extractedTags.params[0].getTypeName()).toBe('({a: number, b: string})');
});
it('should support record type with a field having only a name', () => {
const { extractedTags } = parseJsDoc('@param {{a}} event');
expect(extractedTags.params[0].getTypeName()).toBe('({a})');
});
it('should support union type', () => {
const { extractedTags } = parseJsDoc('@param {(number|boolean)} event');
expect(extractedTags.params[0].getTypeName()).toBe('(number|boolean)');
});
it('should support array type', () => {
const { extractedTags } = parseJsDoc('@param {number[]} event');
expect(extractedTags.params[0].getTypeName()).toBe('number[]');
});
it('should support untyped array type', () => {
const { extractedTags } = parseJsDoc('@param {[]} event');
expect(extractedTags.params[0].getTypeName()).toBe('[]');
});
it('should support nullable type', () => {
const { extractedTags } = parseJsDoc('@param {?number} event');
expect(extractedTags.params[0].getTypeName()).toBe('number');
});
it('should support non nullable type', () => {
const { extractedTags } = parseJsDoc('@param {!number} event');
expect(extractedTags.params[0].getTypeName()).toBe('number');
});
it('should support optional param with []', () => {
const { extractedTags } = parseJsDoc('@param {number} [event]');
expect(extractedTags.params[0].getTypeName()).toBe('number');
});
it('should support optional param with =', () => {
const { extractedTags } = parseJsDoc('@param {number=} event');
expect(extractedTags.params[0].getTypeName()).toBe('number');
});
it('should support any type', () => {
const { extractedTags } = parseJsDoc('@param {*} event');
expect(extractedTags.params[0].getTypeName()).toBe('any');
});
});
describe('getPrettyName', () => {
it('should return @param name', () => {
const { extractedTags } = parseJsDoc('@param {SyntheticEvent} event - React event');
expect(extractedTags.params[0].getPrettyName()).toBe('event');
});
it('should fix missing space between the @param name and the description separator', () => {
const { extractedTags } = parseJsDoc('@param {SyntheticEvent} event- React event');
expect(extractedTags.params[0].getPrettyName()).toBe('event');
});
it('should fix @param name ending with . followed by a @returns tag', () => {
const { extractedTags } = parseJsDoc('@param {SyntheticEvent} event.\n');
expect(extractedTags.params[0].getPrettyName()).toBe('event');
});
});
});
describe('@deprecated', () => {
it('should ignore invalid @deprecated', () => {
const { extractedTags } = parseJsDoc('@deprecated');
expect(extractedTags.returns).toBeNull();
});
it('should return a @deprecated with a name', () => {
const { extractedTags } = parseJsDoc('@deprecated string');
expect(extractedTags.deprecated).not.toBeNull();
expect(extractedTags.deprecated).not.toBeNull();
expect(extractedTags.deprecated).toBe('string');
});
});
describe('@returns', () => {
it('should ignore invalid @returns', () => {
const { extractedTags } = parseJsDoc('@returns');
expect(extractedTags.returns).toBeNull();
});
it('should return a @returns with a type', () => {
const { extractedTags } = parseJsDoc('@returns {string}');
expect(extractedTags.returns).not.toBeNull();
expect(extractedTags.returns.type).not.toBeNull();
expect(extractedTags.returns.type.name).toBe('string');
});
it('should return a @returns with a type and a description', () => {
const { extractedTags } = parseJsDoc('@returns {string} - A bar description');
expect(extractedTags.returns).not.toBeNull();
expect(extractedTags.returns.type).not.toBeNull();
expect(extractedTags.returns.type.name).toBe('string');
expect(extractedTags.returns.description).toBe('A bar description');
});
it('should support multiline @returns description', () => {
const { extractedTags } = parseJsDoc(
'@returns {string} - This is\na multiline\ndescription\n'
);
expect(extractedTags.returns).not.toBeNull();
expect(extractedTags.returns.type).not.toBeNull();
expect(extractedTags.returns.type.name).toBe('string');
expect(extractedTags.returns.description).toBe('This is\na multiline\ndescription');
});
it('should only consider the last @returns tag when there is multiple', () => {
const { extractedTags } = parseJsDoc('@returns {string}\n@returns {number}');
expect(extractedTags.returns).not.toBeNull();
expect(extractedTags.returns.type).not.toBeNull();
expect(extractedTags.returns.type.name).toBe('number');
});
describe('getTypeName', () => {
it('should support named type', () => {
const { extractedTags } = parseJsDoc('@returns {string}');
expect(extractedTags.returns.getTypeName()).toBe('string');
});
it('should support record type with a single field', () => {
const { extractedTags } = parseJsDoc('@returns {{a: number}}');
expect(extractedTags.returns.getTypeName()).toBe('({a: number})');
});
it('should support record type with multiple fields', () => {
const { extractedTags } = parseJsDoc('@returns {{a: number, b: string}}');
expect(extractedTags.returns.getTypeName()).toBe('({a: number, b: string})');
});
it('should support record type with a field having only a name', () => {
const { extractedTags } = parseJsDoc('@returns {{a}}');
expect(extractedTags.returns.getTypeName()).toBe('({a})');
});
it('should support array type', () => {
const { extractedTags } = parseJsDoc('@returns {integer[]}');
expect(extractedTags.returns.getTypeName()).toBe('integer[]');
});
it('should support untyped array type', () => {
const { extractedTags } = parseJsDoc('@returns {[]}');
expect(extractedTags.returns.getTypeName()).toBe('[]');
});
it('should support union type', () => {
const { extractedTags } = parseJsDoc('@returns {(number|boolean)}');
expect(extractedTags.returns.getTypeName()).toBe('(number|boolean)');
});
it('should support any type', () => {
const { extractedTags } = parseJsDoc('@returns {*}');
expect(extractedTags.returns.getTypeName()).toBe('any');
});
it('should support void', () => {
const { extractedTags } = parseJsDoc('@returns {void}');
expect(extractedTags.returns.getTypeName()).toBe('void');
});
});
});
it('should ignore unsupported JSDoc tags', () => {
const { extractedTags } = parseJsDoc('Hey!\n@param event', { tags: [] });
expect(extractedTags.params).toBeNull();
});
it('should remove extra newline characters between tags', () => {
const { extractedTags } = parseJsDoc(
'Hey!\n@param {SyntheticEvent} event - Original event.\n \n \n \n@returns {string}'
);
expect(extractedTags.params).not.toBeNull();
expect(Object.keys(extractedTags.params).length).toBe(1);
expect(extractedTags.params[0].name).toBe('event');
expect(extractedTags.params[0].type.name).toBe('SyntheticEvent');
expect(extractedTags.params[0].description).toBe('Original event.');
expect(extractedTags.returns).not.toBeNull();
expect(extractedTags.returns.type.name).toBe('string');
});
});
|
967 | 0 | petrpan-code/storybookjs/storybook/code/lib/docs-tools/src | petrpan-code/storybookjs/storybook/code/lib/docs-tools/src/argTypes/utils.test.ts | import { createSummaryValue } from './utils';
describe('createSummaryValue', () => {
it('creates an object with just summary if detail is not passed', () => {
const summary = 'boolean';
expect(createSummaryValue(summary)).toEqual({ summary });
});
it('creates an object with summary & detail if passed', () => {
const summary = 'MyType';
const detail = 'boolean | string';
expect(createSummaryValue(summary, detail)).toEqual({ summary, detail });
});
it('creates an object with just summary if details are equal', () => {
const summary = 'boolean';
const detail = 'boolean';
expect(createSummaryValue(summary, detail)).toEqual({ summary });
});
});
|
969 | 0 | petrpan-code/storybookjs/storybook/code/lib/docs-tools/src/argTypes | petrpan-code/storybookjs/storybook/code/lib/docs-tools/src/argTypes/convert/convert.test.ts | import 'jest-specific-snapshot';
import mapValues from 'lodash/mapValues.js';
import { transformSync } from '@babel/core';
import requireFromString from 'require-from-string';
import fs from 'fs';
import { convert } from './index';
import { normalizeNewlines } from '../utils';
expect.addSnapshotSerializer({
print: (val: any) => JSON.stringify(val, null, 2),
test: (val) => typeof val !== 'string',
});
describe('storybook type system', () => {
describe('TypeScript', () => {
it('scalars', () => {
const input = readFixture('typescript/functions.tsx');
expect(input).toMatchInlineSnapshot(`
"import type { FC } from 'react';
import React from 'react';
interface ItemInterface {
text: string;
value: string;
}
interface Props {
onClick?: () => void;
voidFunc: () => void;
funcWithArgsAndReturns: (a: string, b: string) => string;
funcWithUnionArg: (a: string | number) => string;
funcWithMultipleUnionReturns: () => string | ItemInterface;
}
export const Component: FC<Props> = (props: Props) => <>JSON.stringify(props)</>;
"
`);
expect(convertTs(input)).toMatchInlineSnapshot(`
{
"onClick": {
"raw": "() => void",
"name": "function"
},
"voidFunc": {
"raw": "() => void",
"name": "function"
},
"funcWithArgsAndReturns": {
"raw": "(a: string, b: string) => string",
"name": "function"
},
"funcWithUnionArg": {
"raw": "(a: string | number) => string",
"name": "function"
},
"funcWithMultipleUnionReturns": {
"raw": "() => string | ItemInterface",
"name": "function"
}
}
`);
});
it('functions', () => {
const input = readFixture('typescript/functions.tsx');
expect(input).toMatchInlineSnapshot(`
"import type { FC } from 'react';
import React from 'react';
interface ItemInterface {
text: string;
value: string;
}
interface Props {
onClick?: () => void;
voidFunc: () => void;
funcWithArgsAndReturns: (a: string, b: string) => string;
funcWithUnionArg: (a: string | number) => string;
funcWithMultipleUnionReturns: () => string | ItemInterface;
}
export const Component: FC<Props> = (props: Props) => <>JSON.stringify(props)</>;
"
`);
expect(convertTs(input)).toMatchInlineSnapshot(`
{
"onClick": {
"raw": "() => void",
"name": "function"
},
"voidFunc": {
"raw": "() => void",
"name": "function"
},
"funcWithArgsAndReturns": {
"raw": "(a: string, b: string) => string",
"name": "function"
},
"funcWithUnionArg": {
"raw": "(a: string | number) => string",
"name": "function"
},
"funcWithMultipleUnionReturns": {
"raw": "() => string | ItemInterface",
"name": "function"
}
}
`);
});
it('enums', () => {
const input = readFixture('typescript/enums.tsx');
expect(input).toMatchInlineSnapshot(`
"import type { FC } from 'react';
import React from 'react';
enum DefaultEnum {
TopLeft,
TopRight,
TopCenter,
}
enum NumericEnum {
TopLeft = 0,
TopRight,
TopCenter,
}
enum StringEnum {
TopLeft = 'top-left',
TopRight = 'top-right',
TopCenter = 'top-center',
}
interface Props {
defaultEnum: DefaultEnum;
numericEnum: NumericEnum;
stringEnum: StringEnum;
}
export const Component: FC<Props> = (props: Props) => <>JSON.stringify(props)</>;
"
`);
expect(convertTs(input)).toMatchInlineSnapshot(`
{
"defaultEnum": {
"name": "other",
"value": "DefaultEnum"
},
"numericEnum": {
"name": "other",
"value": "NumericEnum"
},
"stringEnum": {
"name": "other",
"value": "StringEnum"
}
}
`);
});
it('unions', () => {
const input = readFixture('typescript/unions.tsx');
expect(input).toMatchInlineSnapshot(`
"import type { FC } from 'react';
import React from 'react';
type Kind = 'default' | 'action';
enum DefaultEnum {
TopLeft,
TopRight,
TopCenter,
}
enum NumericEnum {
TopLeft = 0,
TopRight,
TopCenter,
}
type EnumUnion = DefaultEnum | NumericEnum;
interface Props {
kind?: Kind;
inlinedNumericLiteralUnion: 0 | 1;
enumUnion: EnumUnion;
}
export const Component: FC<Props> = (props: Props) => <>JSON.stringify(props)</>;
"
`);
expect(convertTs(input)).toMatchInlineSnapshot(`
{
"kind": {
"raw": "'default' | 'action'",
"name": "enum",
"value": [
"default",
"action"
]
},
"inlinedNumericLiteralUnion": {
"raw": "0 | 1",
"name": "enum",
"value": [
0,
1
]
},
"enumUnion": {
"raw": "DefaultEnum | NumericEnum",
"name": "union",
"value": [
{
"name": "other",
"value": "DefaultEnum"
},
{
"name": "other",
"value": "NumericEnum"
}
]
}
}
`);
});
it('intersections', () => {
const input = readFixture('typescript/intersections.tsx');
expect(input).toMatchInlineSnapshot(`
"import type { FC } from 'react';
import React from 'react';
interface ItemInterface {
text: string;
value: string;
}
interface PersonInterface {
name: string;
}
type InterfaceIntersection = ItemInterface & PersonInterface;
interface Props {
intersectionType: InterfaceIntersection;
intersectionWithInlineType: ItemInterface & { inlineValue: string };
}
export const Component: FC<Props> = (props: Props) => <>JSON.stringify(props)</>;
"
`);
expect(convertTs(input)).toMatchInlineSnapshot(`
{
"intersectionType": {
"raw": "ItemInterface & PersonInterface",
"name": "intersection",
"value": [
{
"name": "other",
"value": "ItemInterface"
},
{
"name": "other",
"value": "PersonInterface"
}
]
},
"intersectionWithInlineType": {
"raw": "ItemInterface & { inlineValue: string }",
"name": "intersection",
"value": [
{
"name": "other",
"value": "ItemInterface"
},
{
"raw": "{ inlineValue: string }",
"name": "object",
"value": {
"inlineValue": {
"name": "string"
}
}
}
]
}
}
`);
});
it('arrays', () => {
const input = readFixture('typescript/arrays.tsx');
expect(input).toMatchInlineSnapshot(`
"import type { FC } from 'react';
import React from 'react';
interface ItemInterface {
text: string;
value: string;
}
interface Point {
x: number;
y: number;
}
interface Props {
arrayOfPoints: Point[];
arrayOfInlineObjects: { w: number; h: number }[];
arrayOfPrimitive: string[];
arrayOfComplexObject: ItemInterface[];
}
export const Component: FC<Props> = (props: Props) => <>JSON.stringify(props)</>;
"
`);
expect(convertTs(input)).toMatchInlineSnapshot(`
{
"arrayOfPoints": {
"raw": "Point[]",
"name": "array",
"value": [
{
"name": "other",
"value": "Point"
}
]
},
"arrayOfInlineObjects": {
"raw": "{ w: number; h: number }[]",
"name": "array",
"value": [
{
"raw": "{ w: number; h: number }",
"name": "object",
"value": {
"w": {
"name": "number"
},
"h": {
"name": "number"
}
}
}
]
},
"arrayOfPrimitive": {
"raw": "string[]",
"name": "array",
"value": [
{
"name": "string"
}
]
},
"arrayOfComplexObject": {
"raw": "ItemInterface[]",
"name": "array",
"value": [
{
"name": "other",
"value": "ItemInterface"
}
]
}
}
`);
});
it('interfaces', () => {
const input = readFixture('typescript/interfaces.tsx');
expect(input).toMatchInlineSnapshot(`
"import type { FC } from 'react';
import React from 'react';
interface ItemInterface {
text: string;
value: string;
}
interface GenericInterface<T> {
value: T;
}
interface Props {
interface: ItemInterface;
genericInterface: GenericInterface<string>;
}
export const Component: FC<Props> = (props: Props) => <>JSON.stringify(props)</>;
"
`);
expect(convertTs(input)).toMatchInlineSnapshot(`
{
"interface": {
"name": "other",
"value": "ItemInterface"
},
"genericInterface": {
"raw": "GenericInterface<string>",
"name": "other",
"value": "GenericInterface"
}
}
`);
});
it('records', () => {
const input = readFixture('typescript/records.tsx');
expect(input).toMatchInlineSnapshot(`
"import type { FC } from 'react';
import React from 'react';
interface ItemInterface {
text: string;
value: string;
}
interface Props {
recordOfPrimitive: Record<string, number>;
recordOfComplexObject: Record<string, ItemInterface>;
}
export const Component: FC<Props> = (props: Props) => <>JSON.stringify(props)</>;
"
`);
expect(convertTs(input)).toMatchInlineSnapshot(`
{
"recordOfPrimitive": {
"raw": "Record<string, number>",
"name": "other",
"value": "Record"
},
"recordOfComplexObject": {
"raw": "Record<string, ItemInterface>",
"name": "other",
"value": "Record"
}
}
`);
});
it('aliases', () => {
const input = readFixture('typescript/aliases.tsx');
expect(input).toMatchInlineSnapshot(`
"import type { FC } from 'react';
import React from 'react';
type StringAlias = string;
type NumberAlias = number;
type AliasesIntersection = StringAlias & NumberAlias;
type AliasesUnion = StringAlias | NumberAlias;
interface GenericAlias<T> {
value: T;
}
interface Props {
typeAlias: StringAlias;
aliasesIntersection: AliasesIntersection;
aliasesUnion: AliasesUnion;
genericAlias: GenericAlias<string>;
}
export const Component: FC<Props> = (props: Props) => <>JSON.stringify(props)</>;
"
`);
expect(convertTs(input)).toMatchInlineSnapshot(`
{
"typeAlias": {
"name": "string"
},
"aliasesIntersection": {
"raw": "StringAlias & NumberAlias",
"name": "intersection",
"value": [
{
"name": "string"
},
{
"name": "number"
}
]
},
"aliasesUnion": {
"raw": "StringAlias | NumberAlias",
"name": "union",
"value": [
{
"name": "string"
},
{
"name": "number"
}
]
},
"genericAlias": {
"raw": "GenericAlias<string>",
"name": "other",
"value": "GenericAlias"
}
}
`);
});
it('tuples', () => {
const input = readFixture('typescript/tuples.tsx');
expect(input).toMatchInlineSnapshot(`
"import type { FC } from 'react';
import React from 'react';
interface ItemInterface {
text: string;
value: string;
}
interface Props {
tupleOfPrimitive: [string, number];
tupleWithComplexType: [string, ItemInterface];
}
export const Component: FC<Props> = (props: Props) => <>JSON.stringify(props)</>;
"
`);
expect(convertTs(input)).toMatchInlineSnapshot(`
{
"tupleOfPrimitive": {
"raw": "[string, number]",
"name": "other",
"value": "tuple"
},
"tupleWithComplexType": {
"raw": "[string, ItemInterface]",
"name": "other",
"value": "tuple"
}
}
`);
});
});
describe('PropTypes', () => {
it('scalars', () => {
const input = readFixture('proptypes/scalars.js');
expect(input).toMatchInlineSnapshot(`
"import React from 'react';
import PropTypes from 'prop-types';
export const Component = (props) => <>JSON.stringify(props)</>;
Component.propTypes = {
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,
};
"
`);
expect(convertJs(input)).toMatchInlineSnapshot(`
{
"optionalBool": {
"name": "boolean"
},
"optionalFunc": {
"name": "function"
},
"optionalNumber": {
"name": "number"
},
"optionalString": {
"name": "string"
},
"optionalSymbol": {
"name": "symbol"
}
}
`);
});
it('arrays', () => {
const input = readFixture('proptypes/arrays.js');
expect(input).toMatchInlineSnapshot(`
"import React from 'react';
import PropTypes from 'prop-types';
export const Component = (props) => <>JSON.stringify(props)</>;
Component.propTypes = {
optionalArray: PropTypes.array,
arrayOfStrings: PropTypes.arrayOf(PropTypes.string),
arrayOfShape: PropTypes.arrayOf(
PropTypes.shape({
active: PropTypes.bool,
})
),
};
"
`);
expect(convertJs(input)).toMatchInlineSnapshot(`
{
"optionalArray": {
"name": "array"
},
"arrayOfStrings": {
"name": "array",
"value": {
"name": "string"
}
},
"arrayOfShape": {
"name": "array",
"value": {
"name": "object",
"value": {
"active": {
"name": "boolean"
}
}
}
}
}
`);
});
it('enums', () => {
const input = readFixture('proptypes/enums.js');
expect(input).toMatchInlineSnapshot(`
"import React from 'react';
import PropTypes from 'prop-types';
export const Component = (props) => <>JSON.stringify(props)</>;
Component.propTypes = {
oneOfNumber: PropTypes.oneOf([1, 2, 3]),
oneOfMiscellaneous: PropTypes.oneOf([false, true, undefined]),
oneOfStringNumber: PropTypes.oneOf(['1', '2', '3']),
oneOfString: PropTypes.oneOf(['static', 'timed']),
};
"
`);
expect(convertJs(input)).toMatchInlineSnapshot(`
{
"oneOfNumber": {
"name": "enum",
"value": [
1,
2,
3
]
},
"oneOfMiscellaneous": {
"name": "enum",
"value": [
"false",
"true",
"undefined"
]
},
"oneOfStringNumber": {
"name": "enum",
"value": [
"1",
"2",
"3"
]
},
"oneOfString": {
"name": "enum",
"value": [
"static",
"timed"
]
}
}
`);
});
it('misc', () => {
const input = readFixture('proptypes/misc.js');
expect(input).toMatchInlineSnapshot(`
"import React from 'react';
import PropTypes from 'prop-types';
export const Component = (props) => <>JSON.stringify(props)</>;
Component.propTypes = {
// An object that could be one of many types
optionalUnion: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Object),
]),
optionalMessage: PropTypes.instanceOf(Object),
// A value of any data type
requiredAny: PropTypes.any.isRequired,
};
"
`);
expect(convertJs(input)).toMatchInlineSnapshot(`
{
"optionalUnion": {
"name": "union",
"value": [
{
"name": "string"
},
{
"name": "number"
},
{
"name": "other",
"value": "instanceOf(Object)"
}
]
},
"optionalMessage": {
"name": "other",
"value": "instanceOf(Object)"
},
"requiredAny": {
"name": "other",
"value": "any"
}
}
`);
});
it('objects', () => {
const input = readFixture('proptypes/objects.js');
expect(input).toMatchInlineSnapshot(`
"import React from 'react';
import PropTypes from 'prop-types';
export const Component = (props) => <>JSON.stringify(props)</>;
Component.propTypes = {
optionalObject: PropTypes.object,
optionalObjectOf: PropTypes.objectOf(PropTypes.number),
optionalObjectWithShape: PropTypes.shape({
color: PropTypes.string,
fontSize: PropTypes.number,
}),
optionalObjectWithStrictShape: PropTypes.exact({
name: PropTypes.string,
quantity: PropTypes.number,
}),
};
"
`);
expect(convertJs(input)).toMatchInlineSnapshot(`
{
"optionalObject": {
"name": "object"
},
"optionalObjectOf": {
"name": "objectOf",
"value": {
"name": "number"
}
},
"optionalObjectWithShape": {
"name": "object",
"value": {
"color": {
"name": "string"
},
"fontSize": {
"name": "number"
}
}
},
"optionalObjectWithStrictShape": {
"name": "object",
"value": {
"name": {
"name": "string"
},
"quantity": {
"name": "number"
}
}
}
}
`);
});
it('react', () => {
const input = readFixture('proptypes/react.js');
expect(input).toMatchInlineSnapshot(`
"import React from 'react';
import PropTypes from 'prop-types';
export const Component = (props) => <>JSON.stringify(props)</>;
Component.propTypes = {
// Anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
optionalNode: PropTypes.node,
// A React element.
optionalElement: PropTypes.element,
// A React element type (ie. MyComponent).
optionalElementType: PropTypes.elementType,
};
"
`);
expect(convertJs(input)).toMatchInlineSnapshot(`
{
"optionalNode": {
"name": "other",
"value": "node"
},
"optionalElement": {
"name": "other",
"value": "element"
},
"optionalElementType": {
"name": "other",
"value": "elementType"
}
}
`);
});
});
});
const readFixture = (fixture: string) =>
fs.readFileSync(`${__dirname}/__testfixtures__/${fixture}`).toString();
const transformToModule = (inputCode: string) => {
const options = {
presets: [
[
'@babel/preset-env',
{
targets: {
esmodules: true,
},
},
],
],
};
const { code } = transformSync(inputCode, options);
return normalizeNewlines(code);
};
const annotateWithDocgen = (inputCode: string, filename: string) => {
const options = {
presets: ['@babel/typescript', '@babel/react'],
plugins: ['babel-plugin-react-docgen', '@babel/plugin-transform-class-properties'],
babelrc: false,
filename,
};
const { code } = transformSync(inputCode, options);
return normalizeNewlines(code);
};
const convertCommon = (code: string, fileExt: string) => {
const docgenPretty = annotateWithDocgen(code, `temp.${fileExt}`);
const { Component } = requireFromString(transformToModule(docgenPretty));
// eslint-disable-next-line no-underscore-dangle
const { props = {} } = Component.__docgenInfo || {};
const types = mapValues(props, (prop) => convert(prop));
return types;
};
const convertTs = (code: string) => convertCommon(code, 'tsx');
const convertJs = (code: string) => convertCommon(code, 'js');
|
1,000 | 0 | petrpan-code/storybookjs/storybook/code/lib/docs-tools/src/argTypes | petrpan-code/storybookjs/storybook/code/lib/docs-tools/src/argTypes/docgen/extractDocgenProps.test.ts | /* eslint-disable no-underscore-dangle */
import type { Component } from '../types';
import { extractComponentProps } from './extractDocgenProps';
const DOCGEN_SECTION = 'props';
const PROP_NAME = 'propName';
interface TypeSystemDef {
name: string;
typeProperty?: string;
}
const TypeSystems: TypeSystemDef[] = [
{ name: 'javascript', typeProperty: 'type' },
{ name: 'typescript', typeProperty: 'tsType' },
{ name: 'flow', typeProperty: 'flowType' },
];
function createType(typeName: string, others: Record<string, any> = {}): Record<string, string> {
return {
name: typeName,
...others,
};
}
function createStringType(typeSystemDef: TypeSystemDef, others: Record<string, any> = {}): any {
return {
[typeSystemDef.typeProperty]: createType('string', others),
};
}
function createFuncType(typeSystemDef: TypeSystemDef, others: Record<string, any> = {}): any {
const typeName = typeSystemDef.name === 'javascript' ? 'func' : '() => {}';
return {
[typeSystemDef.typeProperty]: createType(typeName, others),
};
}
function createComponent(docgenInfo: Record<string, any>): Component {
const component = () => {};
component.__docgenInfo = {
[DOCGEN_SECTION]: {
[PROP_NAME]: {
required: false,
...docgenInfo,
},
},
};
return component;
}
TypeSystems.forEach((x) => {
describe(`${x.name}`, () => {
it('should map defaults docgen info properly', () => {
const component = createComponent({
...createStringType(x),
description: 'Hey! Hey!',
defaultValue: {
value: "'Default'",
computed: false,
},
});
const { propDef } = extractComponentProps(component, DOCGEN_SECTION)[0];
expect(propDef.name).toBe(PROP_NAME);
expect(propDef.type.summary).toBe('string');
expect(propDef.description).toBe('Hey! Hey!');
expect(propDef.required).toBe(false);
expect(propDef.defaultValue.summary).toBe("'Default'");
});
if (x === TypeSystems[0]) {
// NOTE: `react-docgen-typescript currently doesn't serialize string as expected
it('should map defaults docgen info properly, RDT broken strings', () => {
const component = createComponent({
...createStringType(x),
description: 'Hey! Hey!',
defaultValue: {
value: 'Default',
},
});
const { propDef } = extractComponentProps(component, DOCGEN_SECTION)[0];
expect(propDef.name).toBe(PROP_NAME);
expect(propDef.type.summary).toBe('string');
expect(propDef.description).toBe('Hey! Hey!');
expect(propDef.required).toBe(false);
expect(propDef.defaultValue.summary).toBe('"Default"');
});
it('should map defaults docgen info properly, RDT broken enums', () => {
const component = createComponent({
[x.typeProperty]: createType('enum', {
value: [{ value: '"Default"' }, { value: '"Other"' }],
}),
description: 'Hey! Hey!',
defaultValue: {
value: 'Default',
},
});
const { propDef } = extractComponentProps(component, DOCGEN_SECTION)[0];
expect(propDef.name).toBe(PROP_NAME);
expect(propDef.type.summary).toBe('enum');
expect(propDef.description).toBe('Hey! Hey!');
expect(propDef.required).toBe(false);
expect(propDef.defaultValue.summary).toBe('"Default"');
});
it('should map defaults docgen info properly, vue', () => {
const component = createComponent({
...createStringType(x),
description: 'Hey! Hey!',
defaultValue: {
value: "'Default'",
func: false,
},
});
const { propDef } = extractComponentProps(component, DOCGEN_SECTION)[0];
expect(propDef.name).toBe(PROP_NAME);
expect(propDef.type.summary).toBe('string');
expect(propDef.description).toBe('Hey! Hey!');
expect(propDef.required).toBe(false);
expect(propDef.defaultValue.summary).toBe("'Default'");
});
}
it('should remove JSDoc tags from the description', () => {
const component = createComponent({
...createStringType(x),
description: 'Hey!\n@param event\nreturns {string}',
});
const { propDef } = extractComponentProps(component, DOCGEN_SECTION)[0];
expect(propDef.description).toBe('Hey!');
});
it('should not remove newline characters of multilines description without JSDoc tags', () => {
const component = createComponent({
...createStringType(x),
description: 'onClick description\nis a\nmulti-lines\ndescription',
});
const { propDef } = extractComponentProps(component, DOCGEN_SECTION)[0];
expect(propDef.description).toBe('onClick description\nis a\nmulti-lines\ndescription');
});
it('should not remove newline characters of multilines description with JSDoc tags', () => {
const component = createComponent({
...createFuncType(x),
description: 'onClick description\nis a\nmulti-lines\ndescription\n@param event',
});
const { propDef } = extractComponentProps(component, DOCGEN_SECTION)[0];
expect(propDef.description).toBe('onClick description\nis a\nmulti-lines\ndescription');
});
it('should not remove markdown from description without JSDoc tags', () => {
const component = createComponent({
...createStringType(x),
description: 'onClick *emphasis*, **strong**, `formatted` description.',
});
const { propDef } = extractComponentProps(component, DOCGEN_SECTION)[0];
expect(propDef.description).toBe('onClick *emphasis*, **strong**, `formatted` description.');
});
it('should not remove markdown from description with JSDoc tags', () => {
const component = createComponent({
...createFuncType(x),
description: 'onClick *emphasis*, **strong**, `formatted` description.\n@param event',
});
const { propDef } = extractComponentProps(component, DOCGEN_SECTION)[0];
expect(propDef.description).toBe('onClick *emphasis*, **strong**, `formatted` description.');
});
it('should return null when the property is marked with @ignore', () => {
const component = createComponent({
...createStringType(x),
description: 'onClick description\n@ignore',
});
expect(extractComponentProps(component, DOCGEN_SECTION).length).toBe(0);
});
it('should provide raw @param tags', () => {
const component = createComponent({
...createFuncType(x),
description:
'onClick description\n@param {SyntheticEvent} event - Original event.\n@param {string} value',
});
const { propDef } = extractComponentProps(component, DOCGEN_SECTION)[0];
expect(propDef.description).toBe('onClick description');
expect(propDef.jsDocTags).toBeDefined();
expect(propDef.jsDocTags.params).toBeDefined();
expect(propDef.jsDocTags.params[0].name).toBe('event');
expect(propDef.jsDocTags.params[0].description).toBe('Original event.');
expect(propDef.jsDocTags.params[1].name).toBe('value');
expect(propDef.jsDocTags.params[1].description).toBeNull();
});
it("should not return 'null' default value", () => {
const component = createComponent({
...createStringType(x),
defaultValue: { value: 'null' },
});
const { propDef } = extractComponentProps(component, DOCGEN_SECTION)[0];
expect(propDef.defaultValue).toBeNull();
});
it("should not return 'undefined' default value", () => {
const component = createComponent({
...createStringType(x),
defaultValue: { value: 'undefined' },
});
const { propDef } = extractComponentProps(component, DOCGEN_SECTION)[0];
expect(propDef.defaultValue).toBeNull();
});
});
});
|
1,005 | 0 | petrpan-code/storybookjs/storybook/code/lib/docs-tools/src/argTypes/docgen | petrpan-code/storybookjs/storybook/code/lib/docs-tools/src/argTypes/docgen/flow/createPropDef.test.ts | import { createFlowPropDef } from './createPropDef';
import type { DocgenInfo } from '../types';
const PROP_NAME = 'propName';
function createDocgenInfo({ flowType, ...others }: Partial<DocgenInfo>): DocgenInfo {
return {
flowType,
required: false,
...others,
};
}
describe('type', () => {
['string', 'number', 'boolean', 'any', 'void', 'Object', 'String', 'MyClass', 'literal'].forEach(
(x) => {
it(`should support ${x}`, () => {
const docgenInfo = createDocgenInfo({
flowType: { name: x },
});
const { type } = createFlowPropDef(PROP_NAME, docgenInfo);
expect(type.summary).toBe(x);
expect(type.detail).toBeUndefined();
});
}
);
['Array', 'Class', 'MyClass'].forEach((x) => {
it(`should support untyped ${x}`, () => {
const docgenInfo = createDocgenInfo({
flowType: { name: x },
});
const { type } = createFlowPropDef(PROP_NAME, docgenInfo);
expect(type.summary).toBe(x);
expect(type.detail).toBeUndefined();
});
it(`should support typed ${x}`, () => {
const docgenInfo = createDocgenInfo({
flowType: {
name: x,
elements: [
{
name: 'any',
},
],
raw: `${x}<any>`,
},
});
const { type } = createFlowPropDef(PROP_NAME, docgenInfo);
expect(type.summary).toBe(`${x}<any>`);
expect(type.detail).toBeUndefined();
});
});
it('should support short object signature', () => {
const docgenInfo = createDocgenInfo({
flowType: {
name: 'signature',
type: 'object',
raw: '{ foo: string, bar?: mixed }',
signature: {
properties: [
{
key: 'foo',
value: {
name: 'string',
required: true,
},
},
{
key: 'bar',
value: {
name: 'mixed',
required: false,
},
},
],
},
},
});
const { type } = createFlowPropDef(PROP_NAME, docgenInfo);
expect(type.summary).toBe('{ foo: string, bar?: mixed }');
expect(type.detail).toBeUndefined();
});
it('should support long object signature', () => {
const docgenInfo = createDocgenInfo({
flowType: {
name: 'signature',
type: 'object',
raw: '{ (x: string): void, prop1: string, prop2: string, prop3: string, prop4: string, prop5: string, prop6: string, prop7: string, prop8: string }',
signature: {
properties: [
{
key: 'prop1',
value: {
name: 'string',
required: true,
},
},
{
key: 'prop2',
value: {
name: 'string',
required: true,
},
},
{
key: 'prop3',
value: {
name: 'string',
required: true,
},
},
{
key: 'prop4',
value: {
name: 'string',
required: true,
},
},
{
key: 'prop5',
value: {
name: 'string',
required: true,
},
},
{
key: 'prop5',
value: {
name: 'string',
required: true,
},
},
{
key: 'prop6',
value: {
name: 'string',
required: true,
},
},
{
key: 'prop7',
value: {
name: 'string',
required: true,
},
},
{
key: 'prop8',
value: {
name: 'string',
required: true,
},
},
],
constructor: {
name: 'signature',
type: 'function',
raw: '(x: string): void',
signature: {
arguments: [
{
name: 'x',
type: {
name: 'string',
},
},
],
return: {
name: 'void',
},
},
},
},
},
});
const { type } = createFlowPropDef(PROP_NAME, docgenInfo);
expect(type.summary).toBe('object');
expect(type.detail).toBe(
'{ (x: string): void, prop1: string, prop2: string, prop3: string, prop4: string, prop5: string, prop6: string, prop7: string, prop8: string }'
);
});
it('should support func signature', () => {
const docgenInfo = createDocgenInfo({
flowType: {
name: 'signature',
type: 'function',
raw: '(x: string) => void',
signature: {
arguments: [
{
name: 'x',
type: {
name: 'string',
},
},
],
return: {
name: 'void',
},
},
},
});
const { type } = createFlowPropDef(PROP_NAME, docgenInfo);
expect(type.summary).toBe('(x: string) => void');
expect(type.detail).toBeUndefined();
});
it('should support tuple', () => {
const docgenInfo = createDocgenInfo({
flowType: {
name: 'tuple',
raw: '[foo, "value", number]',
elements: [
{
name: 'foo',
},
{
name: 'literal',
value: '"value"',
},
{
name: 'number',
},
],
},
});
const { type } = createFlowPropDef(PROP_NAME, docgenInfo);
expect(type.summary).toBe('[foo, "value", number]');
});
it('should support union', () => {
const docgenInfo = createDocgenInfo({
flowType: {
name: 'union',
raw: 'number | string',
elements: [
{
name: 'number',
},
{
name: 'string',
},
],
},
});
const { type } = createFlowPropDef(PROP_NAME, docgenInfo);
expect(type.summary).toBe('number | string');
});
it('should support nested union elements', () => {
const docgenInfo = createDocgenInfo({
flowType: {
name: 'union',
raw: '"minimum" | "maximum" | UserSize',
elements: [
{
name: 'literal',
value: '"minimum"',
},
{
name: 'literal',
value: '"maximum"',
},
{
name: 'union',
raw: 'string | number',
elements: [
{
name: 'number',
},
{
name: 'string',
},
],
},
],
},
});
const { type } = createFlowPropDef(PROP_NAME, docgenInfo);
expect(type.summary).toBe('"minimum" | "maximum" | number | string');
});
it('uses raw union value if elements are missing', () => {
const docgenInfo = createDocgenInfo({
flowType: {
name: 'union',
raw: '"minimum" | "maximum" | UserSize',
},
});
const { type } = createFlowPropDef(PROP_NAME, docgenInfo);
expect(type.summary).toBe('"minimum" | "maximum" | UserSize');
});
it('removes a leading | if raw union value is used', () => {
const docgenInfo = createDocgenInfo({
flowType: {
name: 'union',
raw: '| "minimum" | "maximum" | UserSize',
},
});
const { type } = createFlowPropDef(PROP_NAME, docgenInfo);
expect(type.summary).toBe('"minimum" | "maximum" | UserSize');
});
it('even removes extra spaces after a leading | if raw union value is used', () => {
const docgenInfo = createDocgenInfo({
flowType: {
name: 'union',
raw: '| "minimum" | "maximum" | UserSize',
},
});
const { type } = createFlowPropDef(PROP_NAME, docgenInfo);
expect(type.summary).toBe('"minimum" | "maximum" | UserSize');
});
it('should support intersection', () => {
const docgenInfo = createDocgenInfo({
flowType: {
name: 'intersection',
raw: 'number & string',
elements: [
{
name: 'number',
},
{
name: 'string',
},
],
},
});
const { type } = createFlowPropDef(PROP_NAME, docgenInfo);
expect(type.summary).toBe('number & string');
});
});
|
1,009 | 0 | petrpan-code/storybookjs/storybook/code/lib/docs-tools/src/argTypes/docgen | petrpan-code/storybookjs/storybook/code/lib/docs-tools/src/argTypes/docgen/typeScript/createPropDef.test.ts | import { createTsPropDef } from './createPropDef';
import type { DocgenInfo } from '../types';
const PROP_NAME = 'propName';
function createDocgenInfo({ tsType, ...others }: Partial<DocgenInfo>): DocgenInfo {
return {
tsType,
required: true,
...others,
};
}
describe('type', () => {
it("should remove ' | undefined' from optional props type", () => {
const docgenInfo = createDocgenInfo({
tsType: { name: 'string | undefined' },
required: false,
});
const { type } = createTsPropDef(PROP_NAME, docgenInfo);
expect(type.summary).toBe('string');
expect(type.detail).toBeUndefined();
});
});
|
1,022 | 0 | petrpan-code/storybookjs/storybook/code/lib/instrumenter | petrpan-code/storybookjs/storybook/code/lib/instrumenter/src/instrumenter.test.ts | /// <reference types="@types/jest" />;
/* eslint-disable no-underscore-dangle */
import { addons, mockChannel } from '@storybook/preview-api';
import { logger } from '@storybook/client-logger';
import {
FORCE_REMOUNT,
SET_CURRENT_STORY,
STORY_RENDER_PHASE_CHANGED,
} from '@storybook/core-events';
import { global } from '@storybook/global';
import { EVENTS, Instrumenter } from './instrumenter';
import type { Options } from './types';
jest.mock('@storybook/client-logger');
const callSpy = jest.fn();
const syncSpy = jest.fn();
const forceRemountSpy = jest.fn();
addons.setChannel(mockChannel());
addons.getChannel().on(EVENTS.CALL, callSpy);
addons.getChannel().on(EVENTS.SYNC, syncSpy);
addons.getChannel().on(FORCE_REMOUNT, forceRemountSpy);
class HTMLElement {
constructor(props: any) {
Object.assign(this, props);
}
}
// @ts-expect-error (global scope type conflicts)
delete global.location;
// @ts-expect-error (global scope type conflicts)
global.location = { reload: jest.fn() };
// @ts-expect-error (global scope type conflicts)
global.HTMLElement = HTMLElement;
const storyId = 'kind--story';
global.window.__STORYBOOK_PREVIEW__ = {
selectionStore: { selection: { storyId, viewMode: 'story' } },
} as any;
const setRenderPhase = (newPhase: string) =>
addons.getChannel().emit(STORY_RENDER_PHASE_CHANGED, { newPhase, storyId });
let instrumenter: Instrumenter;
const instrument = <TObj extends Record<string, any>>(obj: TObj, options: Options = {}) =>
instrumenter.instrument(obj, options);
const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
beforeEach(() => {
jest.useRealTimers();
callSpy.mockClear();
syncSpy.mockClear();
forceRemountSpy.mockClear();
instrumenter = new Instrumenter();
setRenderPhase('loading');
});
afterEach(() => {
addons.getChannel().emit(SET_CURRENT_STORY); // trigger a cleanup
});
describe('Instrumenter', () => {
it('patches object methods', () => {
const fn = () => {};
const result = instrument({ fn });
expect(result).toStrictEqual({ fn: expect.any(Function) });
expect(result.fn.name).toBe('fn');
expect(result.fn.__originalFn__).toBe(fn);
});
it('patches nested methods', () => {
const fn1: any = () => {};
const fn2: any = () => {};
const result = instrument({ foo: { fn1, bar: { fn2 } } });
expect(result).toStrictEqual({
foo: {
fn1: expect.any(Function),
bar: { fn2: expect.any(Function) },
},
});
expect(result.foo.fn1.__originalFn__).toBe(fn1);
expect(result.foo.bar.fn2.__originalFn__).toBe(fn2);
});
it('does not patch already patched functions', () => {
const fn: any = () => {};
const result = instrument(instrument({ fn }));
expect(result.fn.__originalFn__).toBe(fn);
expect(result.fn.__originalFn__.__originalFn__).not.toBeDefined();
});
it('does not traverse into arrays', () => {
const fn1: any = () => {};
const fn2: any = () => {};
const result = instrument({ arr: [fn1, { fn2 }] });
expect(result).toStrictEqual({ arr: [fn1, { fn2 }] });
expect(result.arr[0].__originalFn__).not.toBeDefined();
expect(result.arr[1].fn2.__originalFn__).not.toBeDefined();
});
it('patches function properties on functions', () => {
const fn1: any = () => {};
fn1.fn2 = () => {};
const result = instrument({ fn1 });
expect(result.fn1).toEqual(expect.any(Function));
expect(result.fn1.fn2).toEqual(expect.any(Function));
expect(result.fn1.__originalFn__).toBe(fn1);
expect(result.fn1.fn2.__originalFn__).toBe(fn1.fn2);
});
it('patches functions correctly that reference this', () => {
const object = {
name: 'name',
method() {
return this.name;
},
};
const instrumented = instrument(object);
expect(object.method()).toEqual(instrumented.method());
expect(instrumented.method).toEqual(expect.any(Function));
expect(instrumented.method.__originalFn__).toBe(object.method);
});
it('patches functions correctly that use proxies', () => {
const object = new Proxy(
{
name: 'name',
method() {
return this.name;
},
},
{
get(target, prop, receiver) {
if (prop === 'name') return `${target[prop]}!`;
return Reflect.get(target, prop, receiver);
},
}
);
const instrumented = instrument(object);
expect(object.method()).toEqual(instrumented.method());
expect(instrumented.method).toEqual(expect.any(Function));
expect(instrumented.method.__originalFn__).toBe(object.method);
});
it('patched functions call the original function when invoked', () => {
const { fn } = instrument({ fn: jest.fn() });
const obj = {};
fn('foo', obj);
expect(fn.__originalFn__).toHaveBeenCalledWith('foo', obj);
});
it('emits a "call" event every time a patched function is invoked', () => {
const { fn } = instrument({ fn: (...args: any) => {} });
fn('foo', 'bar');
fn('baz');
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({
id: 'kind--story [0] fn',
args: ['foo', 'bar'],
})
);
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({
id: 'kind--story [1] fn',
args: ['baz'],
})
);
});
it('provides metadata about the call in the event', () => {
const { obj } = instrument({ obj: { fn: () => {} } });
obj.fn();
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({
path: ['obj'],
method: 'fn',
interceptable: false,
status: 'done',
ancestors: [],
})
);
});
it('maps event args which originate from an earlier call to a call ref', () => {
const { fn1, fn2 } = instrument({
fn1: (arg: any) => arg,
fn2: (arg: any) => {},
});
fn2(fn1({}));
expect(callSpy).toHaveBeenLastCalledWith(
expect.objectContaining({
method: 'fn2',
args: [{ __callId__: callSpy.mock.calls[0][0].id, retain: false }],
})
);
});
it('does not map primitive event args which originate from an earlier call', () => {
const { fn1, fn2 } = instrument({
fn1: (...args: any) => args[0],
fn2: (...args: any) => {},
});
fn2(
fn1(undefined),
fn1(null),
fn1(true),
fn1('foo'),
fn1(1),
fn1(BigInt(1)),
fn1({}),
fn1([]),
fn1(() => {}),
fn1(Symbol('hi')),
fn1(new Error('Oops'))
);
expect(callSpy).toHaveBeenLastCalledWith(
expect.objectContaining({
method: 'fn2',
args: [
/* call 0 */ undefined,
/* call 1 */ null,
/* call 2 */ true,
/* call 3 */ 'foo',
/* call 4 */ 1,
/* call 5 */ BigInt(1),
{ __callId__: callSpy.mock.calls[6][0].id, retain: false },
{ __callId__: callSpy.mock.calls[7][0].id, retain: false },
{ __callId__: callSpy.mock.calls[8][0].id, retain: false },
{ __callId__: callSpy.mock.calls[9][0].id, retain: false },
{ __callId__: callSpy.mock.calls[10][0].id, retain: false },
],
})
);
});
it('maps HTML Elements in event args to an element ref', () => {
const { fn } = instrument({ fn: (...args: any) => {} });
fn(new HTMLElement({ prefix: '', localName: 'div', id: 'root', classList: [] }));
expect(callSpy).toHaveBeenLastCalledWith(
expect.objectContaining({
args: [{ __element__: { prefix: '', localName: 'div', id: 'root', classNames: [] } }],
})
);
});
it('tracks the parent call id for calls inside callbacks', () => {
const fn = (callback?: Function) => callback && callback();
const { fn1, fn2, fn3, fn4, fn5 } = instrument({ fn1: fn, fn2: fn, fn3: fn, fn4: fn, fn5: fn });
fn1(() => {
fn2(() => fn3());
fn4();
});
fn5();
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({ id: 'kind--story [0] fn1', ancestors: [] })
);
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({
id: 'kind--story [0] fn1 [0] fn2',
ancestors: ['kind--story [0] fn1'],
})
);
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({
id: 'kind--story [0] fn1 [0] fn2 [0] fn3',
ancestors: ['kind--story [0] fn1', 'kind--story [0] fn1 [0] fn2'],
})
);
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({
id: 'kind--story [0] fn1 [1] fn4',
ancestors: ['kind--story [0] fn1'],
})
);
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({ id: 'kind--story [1] fn5', ancestors: [] })
);
});
it('handles exceptions when making calls inside callbacks', () => {
const fn = (callback?: Function) => callback && callback();
const { fn1, fn2, fn3 } = instrument({
fn1: fn,
fn2: fn,
fn3: fn,
});
const error = new Error('foo');
let thrownError;
fn1(() => {
try {
fn2(() => {
throw error;
});
} catch (err) {
thrownError = err;
}
fn3();
});
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({ id: 'kind--story [0] fn1', ancestors: [] })
);
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({
id: 'kind--story [0] fn1 [0] fn2',
ancestors: ['kind--story [0] fn1'],
})
);
expect(thrownError).toBe(error);
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({
id: 'kind--story [0] fn1 [1] fn3',
ancestors: ['kind--story [0] fn1'],
})
);
});
it('tracks the parent call id for async callbacks', async () => {
const fn = (callback?: Function) => Promise.resolve(callback && callback());
const { fn1, fn2, fn3 } = instrument({ fn1: fn, fn2: fn, fn3: fn });
await fn1(() => fn2());
await fn3();
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({ id: 'kind--story [0] fn1', ancestors: [] })
);
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({
id: 'kind--story [0] fn1 [0] fn2',
ancestors: ['kind--story [0] fn1'],
})
);
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({ id: 'kind--story [1] fn3', ancestors: [] })
);
});
it('instruments the call result to support chaining', () => {
const { fn1 } = instrument({
fn1: () => ({
fn2: () => {},
}),
});
fn1().fn2();
expect(callSpy).toHaveBeenLastCalledWith(
expect.objectContaining({
method: 'fn2',
path: [{ __callId__: callSpy.mock.calls[0][0].id }],
})
);
});
it('handles exceptions when making calls inside async callbacks', async () => {
const fn = (callback?: Function) => Promise.resolve(callback && callback());
const { fn1, fn2, fn3 } = instrument({
fn1: fn,
fn2: fn,
fn3: fn,
});
const error = new Error('foo');
let thrownError;
await fn1(async () => {
try {
await fn2(async () => {
throw error;
});
} catch (err) {
thrownError = err;
}
await fn3();
});
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({ id: 'kind--story [0] fn1', ancestors: [] })
);
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({
id: 'kind--story [0] fn1 [0] fn2',
ancestors: ['kind--story [0] fn1'],
})
);
expect(thrownError).toBe(error);
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({
id: 'kind--story [0] fn1 [1] fn3',
ancestors: ['kind--story [0] fn1'],
})
);
});
it('emits a "sync" event with debounce after a patched function is invoked', () => {
const { fn } = instrument({ fn: (...args: any) => {} }, { intercept: true });
jest.useFakeTimers();
syncSpy.mockClear();
fn('foo');
fn('bar');
jest.runAllTimers();
expect(syncSpy).toHaveBeenCalledTimes(1);
});
it('sends a folded log with the "sync" event', () => {
const { fn } = instrument({ fn: (...args: any) => ({ fn2: () => {} }) }, { intercept: true });
jest.useFakeTimers();
fn('foo', fn('bar')).fn2();
fn('baz');
jest.runAllTimers();
expect(syncSpy).toHaveBeenCalledWith(
expect.objectContaining({
logItems: [
{ callId: 'kind--story [2] fn2', status: 'done', ancestors: [] },
{ callId: 'kind--story [3] fn', status: 'done', ancestors: [] },
],
})
);
});
it('catches thrown errors and throws an ignoredException instead', () => {
const { fn } = instrument({
fn: () => {
throw new Error('Boom!');
},
});
expect(fn).toThrow('ignoredException');
});
it('catches nested exceptions and throws an ignoredException instead', () => {
const { fn1, fn2 } = instrument({
fn1: (_: any) => {},
fn2: () => {
throw new Error('Boom!');
},
});
expect(() => fn1(fn2())).toThrow('ignoredException');
});
it('bubbles child exceptions up to parent (in callback)', () => {
const { fn1, fn2 } = instrument({
fn1: jest.fn((callback: Function) => callback()),
fn2: () => {
throw new Error('Boom!');
},
});
expect(() =>
fn1(() => {
fn2();
})
).toThrow('ignoredException');
expect(fn1).toHaveBeenCalled();
expect(logger.warn).toHaveBeenCalledWith(new Error('Boom!'));
expect((logger.warn as any).mock.calls[0][0].callId).toBe('kind--story [0] fn1 [0] fn2');
});
it("re-throws anything that isn't an error", () => {
const { fn } = instrument({
fn: () => {
// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw 'Boom!';
},
});
expect(fn).toThrow('Boom!');
expect(callSpy).not.toHaveBeenCalled();
});
it('does not affect intercepted methods', () => {
const { fn } = instrument({ fn: jest.fn() }, { intercept: true });
fn('foo');
expect(fn.__originalFn__).toHaveBeenCalledWith('foo');
});
it('clears state when switching stories', () => {
addons.getChannel().emit(SET_CURRENT_STORY); // initialization
instrumenter.state = {
'kind--story': {
isDebugging: false,
cursor: 123,
calls: [{ id: 'kind--story [0] fn' }],
shadowCalls: [{ id: 'kind--story [0] fn' }, { id: 'kind--story [1] fn' }],
callRefsByResult: new Map([[{}, 'ref']]),
chainedCallIds: new Set(['kind--story [0] fn']),
parentCall: { id: 'kind--story [0] fn' },
playUntil: 'kind--story [1] fn',
resolvers: { ref: () => {} },
syncTimeout: 123,
forwardedException: new Error('Oops'),
},
} as any;
addons.getChannel().emit(SET_CURRENT_STORY);
expect(instrumenter.state).toStrictEqual({});
});
describe('with intercept: true', () => {
const options = { intercept: true };
it('only includes intercepted calls in the log', async () => {
const fn = (callback?: Function) => callback && callback();
const { fn1, fn2 } = instrument({ fn1: fn, fn2: fn }, options);
const { fn3 } = instrument({ fn3: fn }, { intercept: false });
fn1();
fn2();
fn3();
await tick();
expect(syncSpy).toHaveBeenCalledWith(
expect.objectContaining({
logItems: [
{ callId: 'kind--story [0] fn1', status: 'done', ancestors: [] },
{ callId: 'kind--story [1] fn2', status: 'done', ancestors: [] },
],
})
);
});
it('also includes child calls in the log', async () => {
const fn = (callback?: Function) => callback && callback();
const { fn1, fn2 } = instrument({ fn1: fn, fn2: fn }, options);
fn1(() => {
fn2();
});
await tick();
expect(syncSpy).toHaveBeenCalledWith(
expect.objectContaining({
logItems: [
{ callId: 'kind--story [0] fn1', status: 'done', ancestors: [] },
{
callId: 'kind--story [0] fn1 [0] fn2',
status: 'done',
ancestors: ['kind--story [0] fn1'],
},
],
})
);
});
it('emits a call event with error data when the function throws', () => {
const { fn } = instrument(
{
fn: () => {
throw new Error('Boom!');
},
},
options
);
expect(fn).toThrow();
expect(callSpy).toHaveBeenCalledWith(
expect.objectContaining({
id: 'kind--story [0] fn',
exception: expect.objectContaining({
name: 'Error',
message: 'Boom!',
stack: expect.stringContaining('Error: Boom!'),
callId: 'kind--story [0] fn',
}),
})
);
});
});
describe('while debugging', () => {
afterEach(() => {
addons.getChannel().emit(EVENTS.END, { storyId });
});
it('remounts on the "start" event', async () => {
addons.getChannel().emit(EVENTS.START, { storyId });
expect(forceRemountSpy).toHaveBeenCalled();
});
it('defers calls to intercepted functions', () => {
const { fn } = instrument({ fn: jest.fn() }, { intercept: true });
addons.getChannel().emit(EVENTS.START, { storyId });
expect(fn()).toEqual(expect.any(Promise));
expect(fn.__originalFn__).not.toHaveBeenCalled();
});
it('does not defer calls to non-intercepted functions', () => {
const { fn } = instrument({ fn: jest.fn(() => 'ok') });
addons.getChannel().emit(EVENTS.START, { storyId });
expect(fn()).toBe('ok');
expect(fn.__originalFn__).toHaveBeenCalled();
});
it('does not defer calls to intercepted functions that are chained upon', () => {
const { fn1 } = instrument(
{ fn1: jest.fn(() => ({ fn2: jest.fn() as any })) },
{ intercept: true }
);
fn1().fn2();
addons.getChannel().emit(EVENTS.START, { storyId });
const res1 = fn1();
expect(res1.fn2()).toEqual(expect.any(Promise));
expect(fn1.__originalFn__).toHaveBeenCalledTimes(2);
expect(res1.fn2.__originalFn__).not.toHaveBeenCalled();
});
it.skip('starts debugging at the first non-nested interceptable call', () => {
const fn = (...args: any[]) => args;
const { fn1, fn2, fn3 } = instrument({ fn1: fn, fn2: fn, fn3: fn }, { intercept: true });
fn3(fn1(), fn2()); // setup the dependencies
addons.getChannel().emit(EVENTS.START, { storyId });
const a = fn1('a');
const b = fn2('b');
const c = fn3(a, b);
expect(a).toEqual(['a']);
expect(b).toEqual(['b']);
expect(c).toEqual(expect.any(Promise));
});
it('steps through each interceptable function on "next"', async () => {
const fn = jest.fn();
const { fn: instrumentedFn } = instrument({ fn }, { intercept: true });
const mockedInstrumentedFn = jest.fn(instrumentedFn);
const play = async () => {
await mockedInstrumentedFn();
await mockedInstrumentedFn();
await mockedInstrumentedFn();
};
await play();
fn.mockClear();
mockedInstrumentedFn.mockClear();
addons.getChannel().emit(EVENTS.START, { storyId });
const p = play();
expect(mockedInstrumentedFn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenCalledTimes(0);
addons.getChannel().emit(EVENTS.NEXT, { storyId });
await tick();
expect(mockedInstrumentedFn).toHaveBeenCalledTimes(2);
expect(fn).toHaveBeenCalledTimes(1);
addons.getChannel().emit(EVENTS.END, { storyId });
await tick();
expect(mockedInstrumentedFn).toHaveBeenCalledTimes(3);
expect(fn).toHaveBeenCalledTimes(3);
await p;
});
});
});
|
1,042 | 0 | petrpan-code/storybookjs/storybook/code/lib/manager-api/src | petrpan-code/storybookjs/storybook/code/lib/manager-api/src/lib/stories.test.ts | import type { StoryIndexV2, StoryIndexV3 } from '@storybook/types';
import { transformStoryIndexV2toV3, transformStoryIndexV3toV4 } from './stories';
const baseV2: StoryIndexV2['stories'][0] = {
id: '1',
story: '',
kind: '',
parameters: {},
};
const baseV3: StoryIndexV3['stories'][0] = {
id: '1',
title: '',
name: '',
story: '',
kind: '',
parameters: {},
importPath: '',
};
describe('transformStoryIndexV2toV3', () => {
it('transforms a StoryIndexV2 to a StoryIndexV3 correctly', () => {
const indexV2: StoryIndexV2 = {
v: 2,
stories: {
'1': {
...baseV2,
id: '1',
kind: 'story',
story: 'Story 1',
},
'2': {
...baseV2,
id: '2',
kind: 'blog',
story: 'Blog 1',
},
},
};
expect(transformStoryIndexV2toV3(indexV2)).toMatchInlineSnapshot(`
Object {
"stories": Object {
"1": Object {
"id": "1",
"importPath": "",
"kind": "story",
"name": "Story 1",
"parameters": Object {},
"story": "Story 1",
"title": "story",
},
"2": Object {
"id": "2",
"importPath": "",
"kind": "blog",
"name": "Blog 1",
"parameters": Object {},
"story": "Blog 1",
"title": "blog",
},
},
"v": 3,
}
`);
});
});
describe('transformStoryIndexV3toV4', () => {
it('transforms a StoryIndexV3 to an API_PreparedStoryIndex correctly', () => {
const indexV3: StoryIndexV3 = {
v: 3,
stories: {
'1': {
...baseV3,
id: '1',
kind: 'story',
title: 'Story 1',
parameters: {
docsOnly: true,
},
},
'2': {
...baseV3,
id: '2',
kind: 'page',
name: 'Page 1',
title: 'Page 1',
},
'3': {
...baseV3,
id: '3',
kind: 'story',
title: 'Story 2',
},
'4': {
...baseV3,
id: '4',
kind: 'page',
name: 'Page 2',
title: 'Page 1',
},
},
};
expect(transformStoryIndexV3toV4(indexV3)).toMatchInlineSnapshot(`
Object {
"entries": Object {
"1": Object {
"id": "1",
"importPath": "",
"name": "",
"parameters": Object {
"docsOnly": true,
},
"storiesImports": Array [],
"tags": Array [
"stories-mdx",
],
"title": "Story 1",
"type": "docs",
},
"2": Object {
"id": "2",
"importPath": "",
"name": "Page 1",
"parameters": Object {},
"title": "Page 1",
"type": "story",
},
"3": Object {
"id": "3",
"importPath": "",
"name": "",
"parameters": Object {},
"title": "Story 2",
"type": "story",
},
"4": Object {
"id": "4",
"importPath": "",
"name": "Page 2",
"parameters": Object {},
"title": "Page 1",
"type": "story",
},
},
"v": 4,
}
`);
});
});
|
1,060 | 0 | petrpan-code/storybookjs/storybook/code/lib/manager-api/src | petrpan-code/storybookjs/storybook/code/lib/manager-api/src/tests/events.test.ts | import { getEventMetadata } from '../lib/events';
import type { API } from '../index';
jest.mock('@storybook/global', () => ({
global: {
location: { origin: 'http://localhost:6006', pathname: '/' },
},
}));
describe('getEventMetadata', () => {
const fullAPIMock = { findRef: jest.fn(), getRefs: jest.fn() };
const fullAPI = fullAPIMock as unknown as API;
it('returns local if the event source is the same current location', () => {
expect(
getEventMetadata({ type: 'event', source: 'http://localhost:6006' }, fullAPI)
).toMatchObject({
sourceType: 'local',
});
});
it('returns external if the refId is set', () => {
fullAPIMock.getRefs.mockReset().mockReturnValue({
ref: { id: 'ref' },
});
expect(
getEventMetadata(
{ type: 'event', source: 'http://localhost:6006/foo/bar', refId: 'ref' },
fullAPI
)
).toMatchObject({
sourceType: 'external',
ref: { id: 'ref' },
});
});
it('returns external if the source is set to something other and ref is unset (SB5)', () => {
fullAPIMock.findRef.mockReset().mockReturnValue({ id: 'ref' });
expect(
getEventMetadata({ type: 'event', source: 'http://storybook.host' }, fullAPI)
).toMatchObject({
sourceType: 'external',
ref: { id: 'ref' },
});
});
});
|
1,061 | 0 | petrpan-code/storybookjs/storybook/code/lib/manager-api/src | petrpan-code/storybookjs/storybook/code/lib/manager-api/src/tests/globals.test.ts | import { EventEmitter } from 'events';
import { SET_STORIES, SET_GLOBALS, UPDATE_GLOBALS, GLOBALS_UPDATED } from '@storybook/core-events';
import type { API } from '../index';
import type { SubAPI } from '../modules/globals';
import { init as initModule } from '../modules/globals';
import type { ModuleArgs } from '../lib/types';
const { logger } = require('@storybook/client-logger');
const { getEventMetadata } = require('../lib/events');
jest.mock('@storybook/client-logger');
jest.mock('../lib/events');
beforeEach(() => {
getEventMetadata.mockReset().mockReturnValue({ sourceType: 'local' });
});
function createMockStore() {
let state = {};
return {
getState: jest.fn().mockImplementation(() => state),
setState: jest.fn().mockImplementation((s) => {
state = { ...state, ...s };
}),
};
}
describe('globals API', () => {
it('sets a sensible initialState', () => {
const store = createMockStore();
const channel = new EventEmitter();
const { state } = initModule({ store, provider: { channel } } as unknown as ModuleArgs);
expect(state).toEqual({
globals: {},
globalTypes: {},
});
});
it('set global args on SET_GLOBALS', () => {
const channel = new EventEmitter();
const store = createMockStore();
const { state } = initModule({
store,
provider: { channel },
} as unknown as ModuleArgs);
store.setState(state);
channel.emit(SET_GLOBALS, {
globals: { a: 'b' },
globalTypes: { a: { type: { name: 'string' } } },
});
expect(store.getState()).toEqual({
globals: { a: 'b' },
globalTypes: { a: { type: { name: 'string' } } },
});
});
it('ignores SET_STORIES from other refs', () => {
const channel = new EventEmitter();
const api = { findRef: jest.fn() };
const store = createMockStore();
const { state } = initModule({
store,
fullAPI: api,
provider: { channel },
} as unknown as ModuleArgs);
store.setState(state);
getEventMetadata.mockReturnValueOnce({ sourceType: 'external', ref: { id: 'ref' } });
channel.emit(SET_STORIES, { globals: { a: 'b' } });
expect(store.getState()).toEqual({ globals: {}, globalTypes: {} });
});
it('ignores SET_GLOBALS from other refs', () => {
const api = { findRef: jest.fn() };
const channel = new EventEmitter();
const store = createMockStore();
const { state } = initModule({
store,
fullAPI: api,
provider: { channel },
} as unknown as ModuleArgs);
store.setState(state);
getEventMetadata.mockReturnValueOnce({ sourceType: 'external', ref: { id: 'ref' } });
channel.emit(SET_GLOBALS, {
globals: { a: 'b' },
globalTypes: { a: { type: { name: 'string' } } },
});
expect(store.getState()).toEqual({ globals: {}, globalTypes: {} });
});
it('updates the state when the preview emits GLOBALS_UPDATED', () => {
const channel = new EventEmitter();
const api = { findRef: jest.fn() };
const store = createMockStore();
const { state } = initModule({
store,
fullAPI: api,
provider: { channel },
} as unknown as ModuleArgs);
store.setState(state);
channel.emit(GLOBALS_UPDATED, { globals: { a: 'b' } });
expect(store.getState()).toEqual({ globals: { a: 'b' }, globalTypes: {} });
channel.emit(GLOBALS_UPDATED, { globals: { a: 'c' } });
expect(store.getState()).toEqual({ globals: { a: 'c' }, globalTypes: {} });
// SHOULD NOT merge global args
channel.emit(GLOBALS_UPDATED, { globals: { d: 'e' } });
expect(store.getState()).toEqual({ globals: { d: 'e' }, globalTypes: {} });
});
it('ignores GLOBALS_UPDATED from other refs', () => {
const channel = new EventEmitter();
const api = { findRef: jest.fn() };
const store = createMockStore();
const { state } = initModule({
store,
fullAPI: api,
provider: { channel },
} as unknown as ModuleArgs);
store.setState(state);
getEventMetadata.mockReturnValueOnce({ sourceType: 'external', ref: { id: 'ref' } });
logger.warn.mockClear();
channel.emit(GLOBALS_UPDATED, { globals: { a: 'b' } });
expect(store.getState()).toEqual({ globals: {}, globalTypes: {} });
expect(logger.warn).toHaveBeenCalled();
});
it('emits UPDATE_GLOBALS when updateGlobals is called', () => {
const channel = new EventEmitter();
const fullAPI = {} as unknown as API;
const store = createMockStore();
const listener = jest.fn();
channel.on(UPDATE_GLOBALS, listener);
const { api } = initModule({ store, fullAPI, provider: { channel } } as unknown as ModuleArgs);
(api as SubAPI).updateGlobals({ a: 'b' });
expect(listener).toHaveBeenCalledWith({
globals: { a: 'b' },
options: { target: 'storybook-preview-iframe' },
});
});
});
|
1,067 | 0 | petrpan-code/storybookjs/storybook/code/lib/manager-api/src | petrpan-code/storybookjs/storybook/code/lib/manager-api/src/tests/refs.test.ts | import { global } from '@storybook/global';
import { getSourceType, init as initRefs } from '../modules/refs';
const { fetch } = global;
const fetchMock = jest.mocked(fetch);
jest.mock('@storybook/global', () => {
const globalMock = {
fetch: jest.fn(() => Promise.resolve({})),
REFS: {
fake: {
id: 'fake',
url: 'https://example.com',
title: 'Fake',
},
},
};
// Change global.location value to handle edge cases
// Add additional variations of global.location mock return values in this array.
// NOTE: The order must match the order that global.location is called in the unit tests.
const edgecaseLocations = [
{ origin: 'https://storybook.js.org', pathname: '/storybook/index.html' },
];
// global.location value after all edgecaseLocations are returned
const lastLocation = { origin: 'https://storybook.js.org', pathname: '/storybook/' };
Object.defineProperties(globalMock, {
location: {
get: edgecaseLocations
.reduce((mockFn, location) => mockFn.mockReturnValueOnce(location), jest.fn())
.mockReturnValue(lastLocation),
},
});
return { global: globalMock };
});
const provider = {
getConfig: jest.fn().mockReturnValue({}),
};
const store = {
getState: jest.fn().mockReturnValue({
refs: {
fake: {
id: 'fake',
url: 'https://example.com',
title: 'Fake',
},
},
}),
setState: jest.fn((a: any) => {}),
};
interface ResponseResult {
ok?: boolean;
err?: Error;
response?: () => never | object | Promise<object>;
}
type ResponseKeys =
| 'indexPrivate'
| 'indexPublic'
| 'storiesPrivate'
| 'storiesPublic'
| 'iframe'
| 'metadata';
function respond(result: ResponseResult): Promise<Response> {
const { err, ok, response } = result;
if (err) {
return Promise.reject(err);
}
return Promise.resolve({
ok: ok ?? !!response,
json: response,
} as Response);
}
const setupResponses = ({
indexPrivate,
indexPublic,
storiesPrivate,
storiesPublic,
iframe,
metadata,
}: Partial<Record<ResponseKeys, ResponseResult>>) => {
fetchMock.mockClear();
store.setState.mockClear();
fetchMock.mockImplementation((l, o) => {
if (typeof l !== 'string') {
throw new Error('Wrong request type');
}
if (l.includes('index') && o.credentials === 'include' && indexPrivate) {
return respond(indexPrivate);
}
if (l.includes('index') && o.credentials === 'omit' && indexPublic) {
return respond(indexPublic);
}
if (l.includes('stories') && o.credentials === 'include' && storiesPrivate) {
return respond(storiesPrivate);
}
if (l.includes('stories') && o.credentials === 'omit' && storiesPublic) {
return respond(storiesPublic);
}
if (l.includes('iframe') && iframe) {
return respond(iframe);
}
if (l.includes('metadata') && metadata) {
return respond(metadata);
}
throw new Error(`Called URL ${l} without setting up mock`);
});
};
describe('Refs API', () => {
describe('getSourceType(source)', () => {
// These tests must be run first and in correct order.
// The order matches the "edgecaseLocations" order in the 'global' mock function above.
describe('edge cases', () => {
it('returns "local" when source matches location with /index.html in path', () => {
// mockReturnValue(edgecaseLocations[0])
expect(getSourceType('https://storybook.js.org/storybook/iframe.html')).toEqual([
'local',
'https://storybook.js.org/storybook',
]);
});
it('returns "correct url" when source does not match location', () => {
expect(getSourceType('https://external.com/storybook/')).toEqual([
'external',
'https://external.com/storybook',
]);
});
});
// Other tests use "lastLocation" for the 'global' mock
it('returns "local" when source matches location', () => {
expect(getSourceType('https://storybook.js.org/storybook/iframe.html')).toEqual([
'local',
'https://storybook.js.org/storybook',
]);
});
it('returns "external" when source does not match location', () => {
expect(getSourceType('https://external.com/storybook/iframe.html')).toEqual([
'external',
'https://external.com/storybook',
]);
});
});
describe('checkRef', () => {
it('on initialization it checks refs', async () => {
// given
initRefs({ provider, store } as any);
expect(fetchMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
"https://example.com/index.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/stories.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
]
`);
});
it('passes version when set on the ref', async () => {
// given
global.REFS = {
fake: {
id: 'fake',
url: 'https://example.com',
title: 'Fake',
version: '2.1.3-rc.2',
},
};
initRefs({ provider, store } as any);
expect(fetchMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
"https://example.com/index.json?version=2.1.3-rc.2",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/stories.json?version=2.1.3-rc.2",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
]
`);
});
it('checks refs (all fail)', async () => {
// given
const { api } = initRefs({ provider, store } as any, { runCheck: false });
setupResponses({
indexPrivate: {
ok: false,
response: async () => {
throw new Error('Failed to fetch');
},
},
storiesPrivate: {
ok: false,
response: async () => {
throw new Error('Failed to fetch');
},
},
});
await api.checkRef({
id: 'fake',
url: 'https://example.com',
title: 'Fake',
});
expect(fetchMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
"https://example.com/index.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/stories.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
]
`);
expect(store.setState.mock.calls[0][0]).toMatchInlineSnapshot(`
Object {
"refs": Object {
"fake": Object {
"id": "fake",
"index": undefined,
"indexError": Object {
"message": "Error: Loading of ref failed
at fetch (lib/api/src/modules/refs.ts)
URL: https://example.com
We weren't able to load the above URL,
it's possible a CORS error happened.
Please check your dev-tools network tab.",
},
"title": "Fake",
"type": "auto-inject",
"url": "https://example.com",
},
},
}
`);
});
it('checks refs (all throw)', async () => {
// given
const { api } = initRefs({ provider, store } as any, { runCheck: false });
setupResponses({
indexPrivate: {
err: new Error('TypeError: Failed to fetch'),
},
storiesPrivate: {
err: new Error('TypeError: Failed to fetch'),
},
});
await api.checkRef({
id: 'fake',
url: 'https://example.com',
title: 'Fake',
});
expect(fetchMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
"https://example.com/index.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/stories.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
]
`);
expect(store.setState.mock.calls[0][0]).toMatchInlineSnapshot(`
Object {
"refs": Object {
"fake": Object {
"id": "fake",
"index": undefined,
"indexError": Object {
"message": "Error: Loading of ref failed
at fetch (lib/api/src/modules/refs.ts)
URL: https://example.com
We weren't able to load the above URL,
it's possible a CORS error happened.
Please check your dev-tools network tab.",
},
"title": "Fake",
"type": "auto-inject",
"url": "https://example.com",
},
},
}
`);
});
it('checks refs (index throws)', async () => {
// given
const { api } = initRefs({ provider, store } as any, { runCheck: false });
setupResponses({
indexPrivate: {
err: new Error('TypeError: Failed to fetch'),
},
storiesPrivate: {
ok: true,
response: async () => ({ v: 3, stories: {} }),
},
metadata: {
ok: true,
response: async () => ({
versions: {},
}),
},
});
await api.checkRef({
id: 'fake',
url: 'https://example.com',
title: 'Fake',
});
expect(fetchMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
"https://example.com/index.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/stories.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/metadata.json",
Object {
"cache": "no-cache",
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
]
`);
});
it('checks refs (metadata throws)', async () => {
// given
const { api } = initRefs({ provider, store } as any, { runCheck: false });
setupResponses({
indexPrivate: {
ok: true,
response: async () => ({ v: 4, entries: {} }),
},
storiesPrivate: {
ok: true,
response: async () => ({ v: 3, stories: {} }),
},
metadata: {
err: new Error('TypeError: Failed to fetch'),
},
});
await api.checkRef({
id: 'fake',
url: 'https://example.com',
title: 'Fake',
});
expect(fetchMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
"https://example.com/index.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/stories.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/metadata.json",
Object {
"cache": "no-cache",
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
]
`);
expect(store.setState.mock.calls[0][0]).toMatchInlineSnapshot(`
Object {
"refs": Object {
"fake": Object {
"id": "fake",
"index": Object {},
"title": "Fake",
"type": "lazy",
"url": "https://example.com",
},
},
}
`);
expect(store.setState.mock.calls[0][0]).toMatchInlineSnapshot(`
Object {
"refs": Object {
"fake": Object {
"id": "fake",
"index": Object {},
"title": "Fake",
"type": "lazy",
"url": "https://example.com",
},
},
}
`);
});
it('checks refs (success)', async () => {
// given
const { api } = initRefs({ provider, store } as any, { runCheck: false });
setupResponses({
indexPrivate: {
ok: true,
response: async () => ({ v: 4, entries: {} }),
},
storiesPrivate: {
ok: true,
response: async () => ({ v: 3, stories: {} }),
},
metadata: {
ok: true,
response: async () => ({
versions: {},
}),
},
});
await api.checkRef({
id: 'fake',
url: 'https://example.com',
title: 'Fake',
});
expect(fetchMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
"https://example.com/index.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/stories.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/metadata.json",
Object {
"cache": "no-cache",
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
]
`);
expect(store.setState.mock.calls[0][0]).toMatchInlineSnapshot(`
Object {
"refs": Object {
"fake": Object {
"id": "fake",
"index": Object {},
"title": "Fake",
"type": "lazy",
"url": "https://example.com",
"versions": Object {},
},
},
}
`);
});
it('checks refs (not replace versions)', async () => {
// given
const { api } = initRefs({ provider, store } as any, { runCheck: false });
setupResponses({
indexPrivate: {
ok: true,
response: async () => ({ v: 4, entries: {} }),
},
storiesPrivate: {
ok: true,
response: async () => ({ v: 3, stories: {} }),
},
metadata: {
ok: true,
response: async () => ({
versions: {},
}),
},
});
await api.checkRef({
id: 'fake',
url: 'https://example.com',
title: 'Fake',
versions: { a: 'http://example.com/a', b: 'http://example.com/b' },
});
expect(fetchMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
"https://example.com/index.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/stories.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/metadata.json",
Object {
"cache": "no-cache",
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
]
`);
expect(store.setState.mock.calls[0][0]).toMatchInlineSnapshot(`
Object {
"refs": Object {
"fake": Object {
"id": "fake",
"index": Object {},
"title": "Fake",
"type": "lazy",
"url": "https://example.com",
"versions": Object {
"a": "http://example.com/a",
"b": "http://example.com/b",
},
},
},
}
`);
});
it('checks refs (auth)', async () => {
// given
const { api } = initRefs({ provider, store } as any, { runCheck: false });
setupResponses({
indexPrivate: {
ok: true,
response: async () => ({ loginUrl: 'https://example.com/login' }),
},
storiesPrivate: {
ok: true,
response: async () => ({ loginUrl: 'https://example.com/login' }),
},
metadata: {
ok: true,
response: async () => ({ loginUrl: 'https://example.com/login' }),
},
});
await api.checkRef({
id: 'fake',
url: 'https://example.com',
title: 'Fake',
});
expect(fetchMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
"https://example.com/index.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/stories.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/metadata.json",
Object {
"cache": "no-cache",
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
]
`);
expect(store.setState.mock.calls[0][0]).toMatchInlineSnapshot(`
Object {
"refs": Object {
"fake": Object {
"id": "fake",
"index": undefined,
"loginUrl": "https://example.com/login",
"title": "Fake",
"type": "auto-inject",
"url": "https://example.com",
},
},
}
`);
});
it('checks refs (basic-auth)', async () => {
// given
const { api } = initRefs({ provider, store } as any, { runCheck: false });
setupResponses({
indexPrivate: {
ok: true,
response: async () => ({ v: 4, entries: {} }),
},
storiesPrivate: {
ok: true,
response: async () => ({ v: 3, stories: {} }),
},
metadata: {
ok: true,
response: async () => ({ versions: {} }),
},
});
await api.checkRef({
id: 'fake',
url: 'https://user:pass@example.com',
title: 'Fake',
});
expect(fetchMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
"https://example.com/index.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
"Authorization": "Basic dXNlcjpwYXNz",
},
},
],
Array [
"https://example.com/stories.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
"Authorization": "Basic dXNlcjpwYXNz",
},
},
],
Array [
"https://example.com/metadata.json",
Object {
"cache": "no-cache",
"credentials": "include",
"headers": Object {
"Accept": "application/json",
"Authorization": "Basic dXNlcjpwYXNz",
},
},
],
]
`);
});
it('checks refs (mixed)', async () => {
// given
const { api } = initRefs({ provider, store } as any, { runCheck: false });
fetchMock.mockClear();
store.setState.mockClear();
setupResponses({
indexPrivate: {
ok: true,
response: async () => ({ loginUrl: 'https://example.com/login' }),
},
storiesPrivate: {
ok: true,
response: async () => ({ loginUrl: 'https://example.com/login' }),
},
metadata: {
ok: true,
response: async () => ({
versions: { '1.0.0': 'https://example.com/v1', '2.0.0': 'https://example.com' },
}),
},
});
await api.checkRef({
id: 'fake',
url: 'https://example.com',
title: 'Fake',
});
expect(fetchMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
"https://example.com/index.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/stories.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/metadata.json",
Object {
"cache": "no-cache",
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
]
`);
expect(store.setState.mock.calls[0][0]).toMatchInlineSnapshot(`
Object {
"refs": Object {
"fake": Object {
"id": "fake",
"index": undefined,
"loginUrl": "https://example.com/login",
"title": "Fake",
"type": "auto-inject",
"url": "https://example.com",
"versions": Object {
"1.0.0": "https://example.com/v1",
"2.0.0": "https://example.com",
},
},
},
}
`);
});
it('checks refs (serverside-success)', async () => {
// given
const { api } = initRefs({ provider, store } as any, { runCheck: false });
setupResponses({
indexPublic: {
ok: true,
response: async () => ({ v: 4, entries: {} }),
},
storiesPublic: {
ok: true,
response: async () => ({ v: 3, stories: {} }),
},
metadata: {
ok: true,
response: async () => ({
versions: {},
}),
},
});
await api.checkRef({
id: 'fake',
url: 'https://example.com',
title: 'Fake',
type: 'server-checked',
});
expect(fetchMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
"https://example.com/index.json",
Object {
"credentials": "omit",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/stories.json",
Object {
"credentials": "omit",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/metadata.json",
Object {
"cache": "no-cache",
"credentials": "omit",
"headers": Object {
"Accept": "application/json",
},
},
],
]
`);
expect(store.setState.mock.calls[0][0]).toMatchInlineSnapshot(`
Object {
"refs": Object {
"fake": Object {
"id": "fake",
"index": Object {},
"title": "Fake",
"type": "lazy",
"url": "https://example.com",
"versions": Object {},
},
},
}
`);
});
it('checks refs (serverside-fail)', async () => {
// given
const { api } = initRefs({ provider, store } as any, { runCheck: false });
setupResponses({
indexPrivate: {
ok: true,
response: async () => ({ v: 4, entries: {} }),
},
storiesPrivate: {
ok: true,
response: async () => ({ v: 3, stories: {} }),
},
metadata: {
ok: true,
response: async () => ({
versions: {},
}),
},
});
await api.checkRef({
id: 'fake',
url: 'https://example.com',
title: 'Fake',
type: 'unknown',
});
expect(fetchMock.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
"https://example.com/index.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/stories.json",
Object {
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
Array [
"https://example.com/metadata.json",
Object {
"cache": "no-cache",
"credentials": "include",
"headers": Object {
"Accept": "application/json",
},
},
],
]
`);
expect(store.setState.mock.calls[0][0]).toMatchInlineSnapshot(`
Object {
"refs": Object {
"fake": Object {
"id": "fake",
"index": Object {},
"title": "Fake",
"type": "lazy",
"url": "https://example.com",
"versions": Object {},
},
},
}
`);
});
describe('v3 compatibility', () => {
it('infers docs only if there is only one story and it has the name "Page"', async () => {
// given
const { api } = initRefs({ provider, store } as any, { runCheck: false });
const index = {
v: 3,
stories: {
'component-a--page': {
id: 'component-a--page',
title: 'Component A',
name: 'Page', // Called "Page" but not only story
importPath: './path/to/component-a.ts',
},
'component-a--story-2': {
id: 'component-a--story-2',
title: 'Component A',
name: 'Story 2',
importPath: './path/to/component-a.ts',
},
'component-b--page': {
id: 'component-b--page',
title: 'Component B',
name: 'Page', // Page and only story
importPath: './path/to/component-b.ts',
},
'component-c--story-4': {
id: 'component-c--story-4',
title: 'Component c',
name: 'Story 4', // Only story but not page
importPath: './path/to/component-c.ts',
},
},
};
setupResponses({
indexPrivate: { ok: false },
storiesPrivate: {
ok: true,
response: async () => index,
},
metadata: {
ok: true,
response: async () => ({
versions: {},
}),
},
});
await api.checkRef({
id: 'fake',
url: 'https://example.com',
title: 'Fake',
});
const { refs } = store.setState.mock.calls[0][0];
const hash = refs.fake.index;
// We need exact key ordering, even if in theory JS doesn't guarantee it
expect(Object.keys(hash)).toEqual([
'component-a',
'component-a--page',
'component-a--story-2',
'component-b',
'component-b--page',
'component-c',
'component-c--story-4',
]);
expect(hash['component-a--page'].type).toBe('story');
expect(hash['component-a--story-2'].type).toBe('story');
expect(hash['component-b--page'].type).toBe('docs');
expect(hash['component-c--story-4'].type).toBe('story');
});
it('prefers parameters.docsOnly to inferred docsOnly status', async () => {
const { api } = initRefs({ provider, store } as any, { runCheck: false });
const index = {
v: 3,
stories: {
'component-a--docs': {
id: 'component-a--docs',
title: 'Component A',
name: 'Docs', // Called 'Docs' rather than 'Page'
importPath: './path/to/component-a.ts',
parameters: {
docsOnly: true,
},
},
},
};
setupResponses({
indexPrivate: { ok: false },
storiesPrivate: {
ok: true,
response: async () => index,
},
metadata: {
ok: true,
response: async () => ({
versions: {},
}),
},
});
await api.checkRef({
id: 'fake',
url: 'https://example.com',
title: 'Fake',
});
const { refs } = store.setState.mock.calls[0][0];
const hash = refs.fake.index;
// We need exact key ordering, even if in theory JS doesn't guarantee it
expect(Object.keys(hash)).toEqual(['component-a', 'component-a--docs']);
expect(hash['component-a--docs'].type).toBe('docs');
});
});
});
it('errors on unknown version', async () => {
// given
const { api } = initRefs({ provider, store } as any, { runCheck: false });
setupResponses({
indexPrivate: {
ok: false,
},
storiesPrivate: {
ok: true,
response: async () => ({ stories: {} }),
},
metadata: {
ok: true,
response: async () => ({
versions: {},
}),
},
});
await expect(
api.checkRef({
id: 'fake',
url: 'https://example.com',
title: 'Fake',
})
).rejects.toThrow('Composition: Missing stories.json version');
});
});
|
1,071 | 0 | petrpan-code/storybookjs/storybook/code/lib/manager-api/src | petrpan-code/storybookjs/storybook/code/lib/manager-api/src/tests/stories.test.ts | /// <reference types="@types/jest" />;
import {
STORY_ARGS_UPDATED,
UPDATE_STORY_ARGS,
RESET_STORY_ARGS,
SET_STORIES,
STORY_SPECIFIED,
STORY_PREPARED,
STORY_INDEX_INVALIDATED,
CONFIG_ERROR,
SET_INDEX,
CURRENT_STORY_WAS_SET,
STORY_MISSING,
DOCS_PREPARED,
} from '@storybook/core-events';
import { EventEmitter } from 'events';
import { global } from '@storybook/global';
import type { API_StoryEntry } from '@storybook/types';
import { getEventMetadata as getEventMetadataOriginal } from '../lib/events';
import { init as initStories } from '../modules/stories';
import type Store from '../store';
import type { API, State } from '..';
import { mockEntries, docsEntries, preparedEntries, navigationEntries } from './mockStoriesEntries';
import type { ModuleArgs } from '../lib/types';
const mockGetEntries = jest.fn();
const fetch = global.fetch as jest.Mock<ReturnType<typeof global.fetch>>;
const getEventMetadata = getEventMetadataOriginal as unknown as jest.Mock<
ReturnType<typeof getEventMetadataOriginal>
>;
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
jest.mock('../lib/events', () => ({
getEventMetadata: jest.fn(() => ({ sourceType: 'local' })),
}));
jest.mock('@storybook/global', () => ({
global: {
...globalThis,
fetch: jest.fn(() => ({ json: () => ({ v: 4, entries: mockGetEntries() }) })),
FEATURES: { storyStoreV7: true },
CONFIG_TYPE: 'DEVELOPMENT',
},
}));
function createMockStore(initialState: Partial<State> = {}) {
let state = initialState;
return {
getState: jest.fn(() => state),
setState: jest.fn((s: typeof state) => {
state = { ...state, ...s };
return Promise.resolve(state);
}),
} as any as Store;
}
function createMockProvider() {
return {
getConfig: jest.fn().mockReturnValue({}),
channel: new EventEmitter(),
};
}
function createMockModuleArgs({
fullAPI = {},
initialState = {},
}: {
fullAPI?: Partial<jest.Mocked<API>>;
initialState?: Partial<State>;
}) {
const navigate = jest.fn();
const store = createMockStore({ filters: {}, status: {}, ...initialState });
const provider = createMockProvider();
return { navigate, store, provider, fullAPI };
}
describe('stories API', () => {
it('sets a sensible initialState', () => {
const moduleArgs = createMockModuleArgs({});
const { state } = initStories({
...(moduleArgs as unknown as ModuleArgs),
storyId: 'id',
viewMode: 'story',
});
expect(state).toEqual(
expect.objectContaining({
previewInitialized: false,
storyId: 'id',
viewMode: 'story',
hasCalledSetOptions: false,
})
);
});
describe('setIndex', () => {
it('sets the initial set of stories in the stories hash', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
api.setIndex({ v: 4, entries: mockEntries });
const { index } = store.getState();
// We need exact key ordering, even if in theory JS doesn't guarantee it
expect(Object.keys(index)).toEqual([
'component-a',
'component-a--docs',
'component-a--story-1',
'component-a--story-2',
'component-b',
'component-b--story-3',
]);
expect(index['component-a']).toMatchObject({
type: 'component',
id: 'component-a',
children: ['component-a--docs', 'component-a--story-1', 'component-a--story-2'],
});
expect(index['component-a--docs']).toMatchObject({
type: 'docs',
id: 'component-a--docs',
parent: 'component-a',
title: 'Component A',
name: 'Docs',
storiesImports: [],
prepared: false,
});
expect(index['component-a--story-1']).toMatchObject({
type: 'story',
id: 'component-a--story-1',
parent: 'component-a',
title: 'Component A',
name: 'Story 1',
prepared: false,
});
expect(
(index['component-a--story-1'] as API_StoryEntry as API_StoryEntry).args
).toBeUndefined();
});
it('trims whitespace of group/component names (which originate from the kind)', () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
api.setIndex({
v: 4,
entries: {
'design-system-some-component--my-story': {
type: 'story',
id: 'design-system-some-component--my-story',
title: ' Design System / Some Component ', // note the leading/trailing whitespace around each part of the path
name: ' My Story ', // we only trim the path, so this will be kept as-is (it may intentionally have whitespace)
importPath: './path/to/some-component.ts',
},
},
});
const { index } = store.getState();
// We need exact key ordering, even if in theory JS doesn't guarantee it
expect(Object.keys(index)).toEqual([
'design-system',
'design-system-some-component',
'design-system-some-component--my-story',
]);
expect(index['design-system']).toMatchObject({
type: 'root',
name: 'Design System', // root name originates from `kind`, so it gets trimmed
});
expect(index['design-system-some-component']).toMatchObject({
type: 'component',
name: 'Some Component', // component name originates from `kind`, so it gets trimmed
});
expect(index['design-system-some-component--my-story']).toMatchObject({
type: 'story',
title: ' Design System / Some Component ', // title is kept as-is, because it may be used as identifier
name: ' My Story ', // story name is kept as-is, because it's set directly on the story
});
});
it('moves rootless stories to the front of the list', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
api.setIndex({
v: 4,
entries: {
'root-first--story-1': {
type: 'story',
id: 'root-first--story-1',
title: 'Root/First',
name: 'Story 1',
importPath: './path/to/root/first.ts',
},
...mockEntries,
},
});
const { index } = store.getState();
// We need exact key ordering, even if in theory JS doesn't guarantee it
expect(Object.keys(index)).toEqual([
'component-a',
'component-a--docs',
'component-a--story-1',
'component-a--story-2',
'component-b',
'component-b--story-3',
'root',
'root-first',
'root-first--story-1',
]);
expect(index.root).toMatchObject({
type: 'root',
id: 'root',
children: ['root-first'],
});
});
it('sets roots when showRoots = true', () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store, provider } = moduleArgs;
provider.getConfig.mockReturnValue({ sidebar: { showRoots: true } });
api.setIndex({
v: 4,
entries: {
'a-b--1': {
type: 'story',
id: 'a-b--1',
title: 'a/b',
name: '1',
importPath: './a/b.ts',
},
},
});
const { index } = store.getState();
// We need exact key ordering, even if in theory JS doens't guarantee it
expect(Object.keys(index)).toEqual(['a', 'a-b', 'a-b--1']);
expect(index.a).toMatchObject({
type: 'root',
id: 'a',
children: ['a-b'],
});
expect(index['a-b']).toMatchObject({
type: 'component',
id: 'a-b',
parent: 'a',
children: ['a-b--1'],
});
expect(index['a-b--1']).toMatchObject({
type: 'story',
id: 'a-b--1',
parent: 'a-b',
name: '1',
title: 'a/b',
});
});
it('does not put bare stories into a root when showRoots = true', () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store, provider } = moduleArgs;
provider.getConfig.mockReturnValue({ sidebar: { showRoots: true } });
api.setIndex({
v: 4,
entries: {
'a--1': {
type: 'story',
id: 'a--1',
title: 'a',
name: '1',
importPath: './a.ts',
},
},
});
const { index } = store.getState();
// We need exact key ordering, even if in theory JS doens't guarantee it
expect(Object.keys(index)).toEqual(['a', 'a--1']);
expect(index.a).toMatchObject({
type: 'component',
id: 'a',
children: ['a--1'],
});
expect(index['a--1']).toMatchObject({
type: 'story',
id: 'a--1',
parent: 'a',
title: 'a',
name: '1',
});
});
// Stories can get out of order for a few reasons -- see reproductions on
// https://github.com/storybookjs/storybook/issues/5518
it('does the right thing for out of order stories', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store, provider } = moduleArgs;
provider.getConfig.mockReturnValue({ sidebar: { showRoots: true } });
api.setIndex({
v: 4,
entries: {
'a--1': { type: 'story', title: 'a', name: '1', id: 'a--1', importPath: './a.ts' },
'b--1': { type: 'story', title: 'b', name: '1', id: 'b--1', importPath: './b.ts' },
'a--2': { type: 'story', title: 'a', name: '2', id: 'a--2', importPath: './a.ts' },
},
});
const { index } = store.getState();
// We need exact key ordering, even if in theory JS doens't guarantee it
expect(Object.keys(index)).toEqual(['a', 'a--1', 'a--2', 'b', 'b--1']);
expect(index.a).toMatchObject({
type: 'component',
id: 'a',
children: ['a--1', 'a--2'],
});
expect(index.b).toMatchObject({
type: 'component',
id: 'b',
children: ['b--1'],
});
});
// Entries on the SET_STORIES event will be prepared
it('handles properly prepared stories', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
api.setIndex({
v: 4,
entries: {
'prepared--story': {
type: 'story',
id: 'prepared--story',
title: 'Prepared',
name: 'Story',
importPath: './path/to/prepared.ts',
parameters: { parameter: 'exists' },
args: { arg: 'exists' },
},
},
});
const { index } = store.getState();
expect(index['prepared--story']).toMatchObject({
type: 'story',
id: 'prepared--story',
parent: 'prepared',
title: 'Prepared',
name: 'Story',
prepared: true,
parameters: { parameter: 'exists' },
args: { arg: 'exists' },
});
});
it('retains prepared-ness of stories', async () => {
const fullAPI = { setOptions: jest.fn() };
const moduleArgs = createMockModuleArgs({ fullAPI });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store, provider } = moduleArgs;
api.setIndex({ v: 4, entries: mockEntries });
provider.channel.emit(STORY_PREPARED, {
id: 'component-a--story-1',
parameters: { a: 'b' },
args: { c: 'd' },
});
// Let the promise/await chain resolve
await new Promise((r) => setTimeout(r, 0));
expect(store.getState().index['component-a--story-1'] as API_StoryEntry).toMatchObject({
prepared: true,
parameters: { a: 'b' },
args: { c: 'd' },
});
api.setIndex({ v: 4, entries: mockEntries });
// Let the promise/await chain resolve
await new Promise((r) => setTimeout(r, 0));
expect(store.getState().index['component-a--story-1'] as API_StoryEntry).toMatchObject({
prepared: true,
parameters: { a: 'b' },
args: { c: 'd' },
});
});
describe('docs entries', () => {
it('handles docs entries', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
api.setIndex({ v: 4, entries: docsEntries });
const { index } = store.getState();
// We need exact key ordering, even if in theory JS doesn't guarantee it
expect(Object.keys(index)).toEqual([
'component-a',
'component-a--page',
'component-a--story-2',
'component-b',
'component-b--docs',
'component-c',
'component-c--story-4',
]);
expect(index['component-a--page'].type).toBe('story');
expect(index['component-a--story-2'].type).toBe('story');
expect(index['component-b--docs'].type).toBe('docs');
expect(index['component-c--story-4'].type).toBe('story');
});
describe('when DOCS_MODE = true', () => {
it('strips out story entries', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories({
...(moduleArgs as unknown as ModuleArgs),
docsOptions: { docsMode: true },
});
const { store } = moduleArgs;
api.setIndex({ v: 4, entries: docsEntries });
const { index } = store.getState();
expect(Object.keys(index)).toEqual(['component-b', 'component-b--docs']);
});
});
});
});
describe('SET_INDEX event', () => {
it('calls setIndex w/ the data', () => {
const fullAPI = { setOptions: jest.fn() };
const moduleArgs = createMockModuleArgs({ fullAPI });
initStories(moduleArgs as unknown as ModuleArgs);
const { store, provider } = moduleArgs;
provider.channel.emit(SET_INDEX, { v: 4, entries: mockEntries });
expect(store.getState().index).toEqual(
expect.objectContaining({
'component-a': expect.any(Object),
'component-a--docs': expect.any(Object),
'component-a--story-1': expect.any(Object),
})
);
});
it('calls setOptions w/ first story parameter', () => {
const fullAPI = { setOptions: jest.fn() };
const moduleArgs = createMockModuleArgs({ fullAPI });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { provider } = moduleArgs;
// HACK api to effectively mock getCurrentParameter
Object.assign(api, {
getCurrentParameter: jest.fn().mockReturnValue('options'),
});
provider.channel.emit(SET_INDEX, { v: 4, entries: mockEntries });
expect(fullAPI.setOptions).toHaveBeenCalledWith('options');
});
});
describe('fetchIndex', () => {
it('deals with 500 errors', async () => {
fetch.mockReturnValue(
Promise.resolve({
status: 500,
text: async () => new Error('sorting error'),
} as any as Response)
);
const moduleArgs = createMockModuleArgs({});
const { init } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
await init();
const { indexError } = store.getState();
expect(indexError).toBeDefined();
});
it('watches for the INVALIDATE event and re-fetches -- and resets the hash', async () => {
fetch.mockReturnValue(
Promise.resolve({
status: 200,
ok: true,
json: () => ({
v: 4,
entries: {
'component-a--story-1': {
type: 'story',
id: 'component-a--story-1',
title: 'Component A',
name: 'Story 1',
importPath: './path/to/component-a.ts',
},
},
}),
} as any as Response)
);
const moduleArgs = createMockModuleArgs({});
const { init } = initStories(moduleArgs as unknown as ModuleArgs);
const { store, provider } = moduleArgs;
await init();
expect(fetch).toHaveBeenCalledTimes(1);
provider.channel.emit(STORY_INDEX_INVALIDATED);
expect(global.fetch).toHaveBeenCalledTimes(2);
// this side-effect is in an un-awaited promise.
await wait(16);
const { index } = store.getState();
expect(Object.keys(index)).toEqual(['component-a', 'component-a--story-1']);
});
it('clears 500 errors when invalidated', async () => {
fetch.mockReturnValueOnce(
Promise.resolve({
status: 500,
text: async () => new Error('sorting error'),
} as any as Response)
);
const moduleArgs = createMockModuleArgs({});
const { init } = initStories(moduleArgs as unknown as ModuleArgs);
const { store, provider } = moduleArgs;
await init();
const { indexError } = store.getState();
expect(indexError).toBeDefined();
fetch.mockReturnValueOnce(
Promise.resolve({
status: 200,
ok: true,
json: () => ({
v: 4,
entries: {
'component-a--story-1': {
type: 'story',
id: 'component-a--story-1',
title: 'Component A',
name: 'Story 1',
importPath: './path/to/component-a.ts',
},
},
}),
} as any as Response)
);
provider.channel.emit(STORY_INDEX_INVALIDATED);
expect(global.fetch).toHaveBeenCalledTimes(2);
// this side-effect is in an un-awaited promise.
await wait(16);
const { index, indexError: newIndexError } = store.getState();
expect(newIndexError).not.toBeDefined();
expect(Object.keys(index)).toEqual(['component-a', 'component-a--story-1']);
});
});
describe('STORY_SPECIFIED event', () => {
it('navigates to the story', async () => {
const moduleArgs = createMockModuleArgs({ initialState: { path: '/', index: {} } });
initStories(moduleArgs as unknown as ModuleArgs);
const { navigate, provider } = moduleArgs;
provider.channel.emit(STORY_SPECIFIED, { storyId: 'a--1', viewMode: 'story' });
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
it('DOES not navigate if the story was already selected', async () => {
const moduleArgs = createMockModuleArgs({ initialState: { path: '/story/a--1', index: {} } });
initStories(moduleArgs as unknown as ModuleArgs);
const { navigate, provider } = moduleArgs;
provider.channel.emit(STORY_SPECIFIED, { storyId: 'a--1', viewMode: 'story' });
expect(navigate).not.toHaveBeenCalled();
});
it('DOES not navigate if a settings page was selected', async () => {
const moduleArgs = createMockModuleArgs({
initialState: { path: '/settings/about', index: {} },
});
initStories(moduleArgs as unknown as ModuleArgs);
const { navigate, provider } = moduleArgs;
provider.channel.emit(STORY_SPECIFIED, { storyId: 'a--1', viewMode: 'story' });
expect(navigate).not.toHaveBeenCalled();
});
it('DOES not navigate if a custom page was selected', async () => {
const moduleArgs = createMockModuleArgs({
initialState: { path: '/custom/page', index: {} },
});
initStories(moduleArgs as unknown as ModuleArgs);
const { navigate, provider } = moduleArgs;
provider.channel.emit(STORY_SPECIFIED, { storyId: 'a--1', viewMode: 'story' });
expect(navigate).not.toHaveBeenCalled();
});
});
describe('CURRENT_STORY_WAS_SET event', () => {
it('sets previewInitialized', async () => {
const moduleArgs = createMockModuleArgs({});
initStories(moduleArgs as unknown as ModuleArgs);
const { store, provider } = moduleArgs;
provider.channel.emit(CURRENT_STORY_WAS_SET, { id: 'a--1' });
expect(store.getState().previewInitialized).toBe(true);
});
it('sets a ref to previewInitialized', async () => {
const fullAPI = { updateRef: jest.fn() };
const moduleArgs = createMockModuleArgs({ fullAPI });
initStories(moduleArgs as unknown as ModuleArgs);
const { provider } = moduleArgs;
provider.channel.emit(CURRENT_STORY_WAS_SET, { id: 'a--1' });
getEventMetadata.mockReturnValueOnce({
sourceType: 'external',
refId: 'refId',
source: '',
sourceLocation: '',
type: '',
ref: { id: 'refId', index: { 'a--1': { args: { a: 'b' } } } } as any,
});
provider.channel.emit(CURRENT_STORY_WAS_SET, { id: 'a--1' });
expect(fullAPI.updateRef.mock.calls.length).toBe(1);
expect(fullAPI.updateRef.mock.calls[0][1]).toEqual({
previewInitialized: true,
});
});
});
describe('args handling', () => {
it('changes args properly, per story when receiving STORY_ARGS_UPDATED', () => {
const fullAPI = { updateRef: jest.fn() };
const moduleArgs = createMockModuleArgs({ fullAPI });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { provider, store } = moduleArgs;
api.setIndex({ v: 4, entries: preparedEntries });
const { index } = store.getState();
expect((index['a--1'] as API_StoryEntry).args).toEqual({ a: 'b' });
expect((index['b--1'] as API_StoryEntry).args).toEqual({ x: 'y' });
provider.channel.emit(STORY_ARGS_UPDATED, { storyId: 'a--1', args: { foo: 'bar' } });
const { index: changedIndex } = store.getState();
expect((changedIndex['a--1'] as API_StoryEntry).args).toEqual({ foo: 'bar' });
expect((changedIndex['b--1'] as API_StoryEntry).args).toEqual({ x: 'y' });
});
it('changes reffed args properly, per story when receiving STORY_ARGS_UPDATED', () => {
const fullAPI = { updateRef: jest.fn() };
const moduleArgs = createMockModuleArgs({ fullAPI });
initStories(moduleArgs as unknown as ModuleArgs);
const { provider } = moduleArgs;
getEventMetadata.mockReturnValueOnce({
sourceType: 'external',
refId: 'refId',
source: '',
sourceLocation: '',
type: '',
ref: { id: 'refId', index: { 'a--1': { args: { a: 'b' } } } } as any,
});
provider.channel.emit(STORY_ARGS_UPDATED, { storyId: 'a--1', args: { foo: 'bar' } });
expect(fullAPI.updateRef).toHaveBeenCalledWith('refId', {
index: { 'a--1': { args: { foo: 'bar' } } },
});
});
it('updateStoryArgs emits UPDATE_STORY_ARGS to the local frame and does not change anything', () => {
const fullAPI = { updateRef: jest.fn() };
const moduleArgs = createMockModuleArgs({ fullAPI });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { provider, store } = moduleArgs;
const listener = jest.fn();
provider.channel.on(UPDATE_STORY_ARGS, listener);
api.setIndex({ v: 4, entries: preparedEntries });
api.updateStoryArgs({ id: 'a--1' } as API_StoryEntry, { foo: 'bar' });
expect(listener).toHaveBeenCalledWith({
storyId: 'a--1',
updatedArgs: { foo: 'bar' },
options: {
target: undefined,
},
});
const { index } = store.getState();
expect((index['a--1'] as API_StoryEntry).args).toEqual({ a: 'b' });
expect((index['b--1'] as API_StoryEntry).args).toEqual({ x: 'y' });
});
it('updateStoryArgs emits UPDATE_STORY_ARGS to the right frame', () => {
const fullAPI = { updateRef: jest.fn() };
const moduleArgs = createMockModuleArgs({ fullAPI });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { provider } = moduleArgs;
const listener = jest.fn();
provider.channel.on(UPDATE_STORY_ARGS, listener);
api.setIndex({ v: 4, entries: preparedEntries });
api.updateStoryArgs({ id: 'a--1', refId: 'refId' } as API_StoryEntry, { foo: 'bar' });
expect(listener).toHaveBeenCalledWith({
storyId: 'a--1',
updatedArgs: { foo: 'bar' },
options: {
target: 'refId',
},
});
});
it('refId to the local frame and does not change anything', () => {
const fullAPI = { updateRef: jest.fn() };
const moduleArgs = createMockModuleArgs({ fullAPI });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { provider, store } = moduleArgs;
const listener = jest.fn();
provider.channel.on(RESET_STORY_ARGS, listener);
api.setIndex({ v: 4, entries: preparedEntries });
api.resetStoryArgs({ id: 'a--1' } as API_StoryEntry, ['foo']);
expect(listener).toHaveBeenCalledWith({
storyId: 'a--1',
argNames: ['foo'],
options: {
target: undefined,
},
});
const { index } = store.getState();
expect((index['a--1'] as API_StoryEntry).args).toEqual({ a: 'b' });
expect((index['b--1'] as API_StoryEntry).args).toEqual({ x: 'y' });
});
it('resetStoryArgs emits RESET_STORY_ARGS to the right frame', () => {
const fullAPI = { updateRef: jest.fn() };
const moduleArgs = createMockModuleArgs({ fullAPI });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { provider } = moduleArgs;
const listener = jest.fn();
provider.channel.on(RESET_STORY_ARGS, listener);
api.setIndex({ v: 4, entries: preparedEntries });
api.resetStoryArgs({ id: 'a--1', refId: 'refId' } as API_StoryEntry, ['foo']);
expect(listener).toHaveBeenCalledWith({
storyId: 'a--1',
argNames: ['foo'],
options: {
target: 'refId',
},
});
});
});
describe('jumpToStory', () => {
it('works forward', () => {
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.jumpToStory(1);
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('works backwards', () => {
const initialState = { path: '/story/a--2', storyId: 'a--2', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.jumpToStory(-1);
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
it('does nothing if you are at the last story and go forward', () => {
const initialState = {
path: '/story/custom-id--1',
storyId: 'custom-id--1',
viewMode: 'story',
};
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.jumpToStory(1);
expect(navigate).not.toHaveBeenCalled();
});
it('does nothing if you are at the first story and go backward', () => {
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.jumpToStory(-1);
expect(navigate).not.toHaveBeenCalled();
});
it('does nothing if you have not selected a story', () => {
// @ts-expect-error (storyId type is maybe wrong?)
const initialState = { path: '/story', storyId: undefined, viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.jumpToStory(1);
expect(navigate).not.toHaveBeenCalled();
});
});
describe('findSiblingStoryId', () => {
it('works forward', () => {
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
const result = api.findSiblingStoryId('a--1', store.getState().index, 1, false);
expect(result).toBe('a--2');
});
it('works forward toSiblingGroup', () => {
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
const result = api.findSiblingStoryId('a--1', store.getState().index, 1, true);
expect(result).toBe('b-c--1');
});
});
describe('jumpToComponent', () => {
it('works forward', () => {
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.jumpToComponent(1);
expect(navigate).toHaveBeenCalledWith('/story/b-c--1');
});
it('works backwards', () => {
const initialState = {
path: '/story/b-c--1',
storyId: 'b-c--1',
viewMode: 'story',
};
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.jumpToComponent(-1);
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
it('does nothing if you are in the last component and go forward', () => {
const initialState = {
path: '/story/custom-id--1',
storyId: 'custom-id--1',
viewMode: 'story',
};
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.jumpToComponent(1);
expect(navigate).not.toHaveBeenCalled();
});
it('does nothing if you are at the first component and go backward', () => {
const initialState = { path: '/story/a--2', storyId: 'a--2', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.jumpToComponent(-1);
expect(navigate).not.toHaveBeenCalled();
});
});
describe('selectStory', () => {
it('navigates', () => {
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.selectStory('a--2');
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('sets view mode to docs if doc-level component is selected', () => {
const initialState = { path: '/docs/a--1', storyId: 'a--1', viewMode: 'docs' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({
v: 4,
entries: {
...navigationEntries,
'intro--docs': {
type: 'docs',
id: 'intro--docs',
title: 'Intro',
name: 'Page',
importPath: './intro.mdx',
storiesImports: [],
},
},
});
api.selectStory('intro');
expect(navigate).toHaveBeenCalledWith('/docs/intro--docs');
});
it('updates lastTrackedStoryId', () => {
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.selectStory('a--1');
expect(store.getState().settings.lastTrackedStoryId).toBe('a--1');
});
describe('deprecated api', () => {
it('allows navigating to a combination of title + name', () => {
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.selectStory('a', '2');
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('allows navigating to a given name (in the current component)', () => {
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.selectStory(undefined, '2');
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
});
it('allows navigating away from the settings pages', () => {
const initialState = { path: '/settings/a--1', storyId: 'a--1', viewMode: 'settings' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.selectStory('a--2');
expect(navigate).toHaveBeenCalledWith('/story/a--2');
});
it('allows navigating to first story in component on call by component id', () => {
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.selectStory('a');
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
it('allows navigating to first story in group on call by group id', () => {
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.selectStory('b');
expect(navigate).toHaveBeenCalledWith('/story/b-c--1');
});
it('allows navigating to first story in component on call by title', () => {
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.selectStory('A');
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
it('allows navigating to the first story of the current component if passed nothing', () => {
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.selectStory();
expect(navigate).toHaveBeenCalledWith('/story/a--1');
});
describe('component permalinks', () => {
it('allows navigating to kind/storyname (legacy api)', () => {
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.selectStory('b/e', '1');
expect(navigate).toHaveBeenCalledWith('/story/custom-id--1');
});
it('allows navigating to component permalink/storyname (legacy api)', () => {
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.selectStory('custom-id', '1');
expect(navigate).toHaveBeenCalledWith('/story/custom-id--1');
});
it('allows navigating to first story in kind on call by kind', () => {
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { navigate } = moduleArgs;
api.setIndex({ v: 4, entries: navigationEntries });
api.selectStory('b/e');
expect(navigate).toHaveBeenCalledWith('/story/custom-id--1');
});
});
});
describe('STORY_PREPARED', () => {
it('prepares the story', async () => {
const fullAPI = { setOptions: jest.fn() };
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState, fullAPI });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { provider, store } = moduleArgs;
api.setIndex({ v: 4, entries: mockEntries });
provider.channel.emit(STORY_PREPARED, {
id: 'component-a--story-1',
parameters: { a: 'b' },
args: { c: 'd' },
});
const { index } = store.getState();
expect(index['component-a--story-1']).toMatchObject({
type: 'story',
id: 'component-a--story-1',
parent: 'component-a',
title: 'Component A',
name: 'Story 1',
prepared: true,
parameters: { a: 'b' },
args: { c: 'd' },
});
});
it('sets options the first time it is called', async () => {
const fullAPI = { setOptions: jest.fn() };
const initialState = { path: '/story/a--1', storyId: 'a--1', viewMode: 'story' };
const moduleArgs = createMockModuleArgs({ initialState, fullAPI });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { provider } = moduleArgs;
api.setIndex({ v: 4, entries: mockEntries });
provider.channel.emit(STORY_PREPARED, {
id: 'component-a--story-1',
parameters: { options: 'options' },
});
expect(fullAPI.setOptions).toHaveBeenCalledWith('options');
fullAPI.setOptions.mockClear();
provider.channel.emit(STORY_PREPARED, {
id: 'component-a--story-1',
parameters: { options: 'options2' },
});
expect(fullAPI.setOptions).not.toHaveBeenCalled();
});
});
describe('DOCS_PREPARED', () => {
it('prepares the docs entry', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { provider, store } = moduleArgs;
api.setIndex({ v: 4, entries: mockEntries });
provider.channel.emit(DOCS_PREPARED, {
id: 'component-a--docs',
parameters: { a: 'b' },
});
const { index } = store.getState();
expect(index['component-a--docs']).toMatchObject({
type: 'docs',
id: 'component-a--docs',
parent: 'component-a',
title: 'Component A',
name: 'Docs',
prepared: true,
parameters: { a: 'b' },
});
});
});
describe('CONFIG_ERROR', () => {
it('sets previewInitialized to true, local', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { provider, store } = moduleArgs;
api.setIndex({ v: 4, entries: mockEntries });
provider.channel.emit(CONFIG_ERROR, { message: 'Failed to run configure' });
const { previewInitialized } = store.getState();
expect(previewInitialized).toBe(true);
});
it('sets previewInitialized to true, ref', async () => {
const fullAPI = { updateRef: jest.fn() };
const moduleArgs = createMockModuleArgs({ fullAPI });
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { provider } = moduleArgs;
api.setIndex({ v: 4, entries: mockEntries });
getEventMetadata.mockReturnValueOnce({
sourceType: 'external',
ref: { id: 'refId', stories: { 'a--1': { args: { a: 'b' } } } },
} as any);
provider.channel.emit(CONFIG_ERROR, { message: 'Failed to run configure' });
expect(fullAPI.updateRef.mock.calls.length).toBe(1);
expect(fullAPI.updateRef.mock.calls[0][1]).toEqual({
previewInitialized: true,
});
});
});
describe('STORY_MISSING', () => {
it('sets previewInitialized to true, local', async () => {
const moduleArgs = createMockModuleArgs({});
initStories(moduleArgs as unknown as ModuleArgs);
const { provider, store } = moduleArgs;
provider.channel.emit(STORY_MISSING, { message: 'Failed to run configure' });
const { previewInitialized } = store.getState();
expect(previewInitialized).toBe(true);
});
it('sets previewInitialized to true, ref', async () => {
const fullAPI = { updateRef: jest.fn() };
const moduleArgs = createMockModuleArgs({ fullAPI });
initStories(moduleArgs as unknown as ModuleArgs);
const { provider } = moduleArgs;
getEventMetadata.mockReturnValueOnce({
sourceType: 'external',
ref: { id: 'refId', stories: { 'a--1': { args: { a: 'b' } } } },
} as any);
provider.channel.emit(STORY_MISSING, { message: 'Failed to run configure' });
expect(fullAPI.updateRef.mock.calls.length).toBe(1);
expect(fullAPI.updateRef.mock.calls[0][1]).toEqual({
previewInitialized: true,
});
});
});
describe('v2 SET_STORIES event', () => {
it('normalizes parameters and calls setRef for external stories', () => {
const fullAPI = {
findRef: jest.fn(),
setRef: jest.fn(),
};
const moduleArgs = createMockModuleArgs({ fullAPI });
initStories(moduleArgs as unknown as ModuleArgs);
const { provider, store } = moduleArgs;
getEventMetadata.mockReturnValueOnce({
sourceType: 'external',
ref: { id: 'ref' },
} as any);
const setStoriesPayload = {
v: 2,
globalParameters: { global: 'global' },
kindParameters: { a: { kind: 'kind' } },
stories: { 'a--1': { kind: 'a', parameters: { story: 'story' } } },
};
provider.channel.emit(SET_STORIES, setStoriesPayload);
expect(store.getState().index).toBeUndefined();
expect(fullAPI.setRef).toHaveBeenCalledWith(
'ref',
{
id: 'ref',
setStoriesData: {
'a--1': { kind: 'a', parameters: { global: 'global', kind: 'kind', story: 'story' } },
},
},
true
);
});
});
describe('legacy (v1) SET_STORIES event', () => {
it('calls setRef with stories', () => {
const fullAPI = {
findRef: jest.fn(),
setRef: jest.fn(),
};
const moduleArgs = createMockModuleArgs({ fullAPI });
initStories(moduleArgs as unknown as ModuleArgs);
const { provider, store } = moduleArgs;
getEventMetadata.mockReturnValueOnce({
sourceType: 'external',
ref: { id: 'ref' },
} as any);
const setStoriesPayload = {
stories: { 'a--1': {} },
};
provider.channel.emit(SET_STORIES, setStoriesPayload);
expect(store.getState().index).toBeUndefined();
expect(fullAPI.setRef).toHaveBeenCalledWith(
'ref',
{
id: 'ref',
setStoriesData: {
'a--1': {},
},
},
true
);
});
});
describe('experimental_updateStatus', () => {
it('is included in the initial state', () => {
const moduleArgs = createMockModuleArgs({});
const { state } = initStories(moduleArgs as unknown as ModuleArgs);
expect(state).toEqual(
expect.objectContaining({
status: {},
})
);
});
it('updates a story', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
await api.setIndex({ v: 4, entries: mockEntries });
await expect(
api.experimental_updateStatus('a-addon-id', {
'a-story-id': {
status: 'pending',
title: 'an addon title',
description: 'an addon description',
},
})
).resolves.not.toThrow();
expect(store.getState().status).toMatchInlineSnapshot(`
Object {
"a-story-id": Object {
"a-addon-id": Object {
"description": "an addon description",
"status": "pending",
"title": "an addon title",
},
},
}
`);
});
it('skips updating index, if index is unset', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
await expect(
api.experimental_updateStatus('a-addon-id', {
'a-story-id': {
status: 'pending',
title: 'an addon title',
description: 'an addon description',
},
})
).resolves.not.toThrow();
expect(store.getState().status).toMatchInlineSnapshot(`
Object {
"a-story-id": Object {
"a-addon-id": Object {
"description": "an addon description",
"status": "pending",
"title": "an addon title",
},
},
}
`);
});
it('updates multiple stories', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
await api.setIndex({ v: 4, entries: mockEntries });
await expect(
api.experimental_updateStatus('a-addon-id', {
'a-story-id': {
status: 'pending',
title: 'an addon title',
description: 'an addon description',
},
'another-story-id': { status: 'success', title: 'a addon title', description: '' },
})
).resolves.not.toThrow();
expect(store.getState().status).toMatchInlineSnapshot(`
Object {
"a-story-id": Object {
"a-addon-id": Object {
"description": "an addon description",
"status": "pending",
"title": "an addon title",
},
},
"another-story-id": Object {
"a-addon-id": Object {
"description": "",
"status": "success",
"title": "a addon title",
},
},
}
`);
});
it('delete when value is null', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
await api.setIndex({ v: 4, entries: mockEntries });
await expect(
api.experimental_updateStatus('a-addon-id', {
'a-story-id': {
status: 'pending',
title: 'an addon title',
description: 'an addon description',
},
'another-story-id': { status: 'success', title: 'a addon title', description: '' },
})
).resolves.not.toThrow();
// do a second update, this time with null
await expect(
api.experimental_updateStatus('a-addon-id', {
'a-story-id': null,
'another-story-id': { status: 'success', title: 'a addon title', description: '' },
})
).resolves.not.toThrow();
expect(store.getState().status).toMatchInlineSnapshot(`
Object {
"another-story-id": Object {
"a-addon-id": Object {
"description": "",
"status": "success",
"title": "a addon title",
},
},
}
`);
});
it('updates with a function', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
await api.setIndex({ v: 4, entries: mockEntries });
// setup initial state
await expect(
api.experimental_updateStatus('a-addon-id', () => ({
'a-story-id': {
status: 'pending',
title: 'an addon title',
description: 'an addon description',
},
'another-story-id': { status: 'success', title: 'a addon title', description: '' },
}))
).resolves.not.toThrow();
// use existing state in function
await expect(
api.experimental_updateStatus('a-addon-id', (current) => {
return Object.fromEntries(
Object.entries(current).map(([k, v]) => [k, { ...v['a-addon-id'], status: 'success' }])
);
})
).resolves.not.toThrow();
expect(store.getState().status).toMatchInlineSnapshot(`
Object {
"a-story-id": Object {
"a-addon-id": Object {
"description": "an addon description",
"status": "success",
"title": "an addon title",
},
},
"another-story-id": Object {
"a-addon-id": Object {
"description": "",
"status": "success",
"title": "a addon title",
},
},
}
`);
});
});
describe('experimental_setFilter', () => {
it('is included in the initial state', async () => {
const moduleArgs = createMockModuleArgs({});
const { state, api } = initStories(moduleArgs as unknown as ModuleArgs);
await api.setIndex({ v: 4, entries: mockEntries });
expect(state).toEqual(
expect.objectContaining({
filters: {},
})
);
});
it('updates state', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
await api.setIndex({ v: 4, entries: mockEntries });
api.experimental_setFilter('myCustomFilter', () => true);
expect(store.getState()).toEqual(
expect.objectContaining({
filters: {
myCustomFilter: expect.any(Function),
},
})
);
});
it('can filter', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
await api.setIndex({ v: 4, entries: navigationEntries });
await api.experimental_setFilter('myCustomFilter', (item) => item.id.startsWith('a'));
const { index } = store.getState();
expect(index).toMatchInlineSnapshot(`
Object {
"a": Object {
"children": Array [
"a--1",
"a--2",
],
"depth": 0,
"id": "a",
"isComponent": true,
"isLeaf": false,
"isRoot": false,
"name": "a",
"parent": undefined,
"renderLabel": undefined,
"type": "component",
},
"a--1": Object {
"depth": 1,
"id": "a--1",
"importPath": "./a.ts",
"isComponent": false,
"isLeaf": true,
"isRoot": false,
"kind": "a",
"name": "1",
"parent": "a",
"prepared": false,
"renderLabel": undefined,
"title": "a",
"type": "story",
},
"a--2": Object {
"depth": 1,
"id": "a--2",
"importPath": "./a.ts",
"isComponent": false,
"isLeaf": true,
"isRoot": false,
"kind": "a",
"name": "2",
"parent": "a",
"prepared": false,
"renderLabel": undefined,
"title": "a",
"type": "story",
},
}
`);
});
it('can filter on status', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
await api.setIndex({ v: 4, entries: navigationEntries });
await api.experimental_setFilter(
'myCustomFilter',
(item) =>
item.status !== undefined &&
Object.values(item.status).some((v) => v.status === 'pending')
);
// empty, because there are no stories with status
expect(store.getState().index).toMatchInlineSnapshot(`Object {}`);
// setting status should update the index
await api.experimental_updateStatus('a-addon-id', {
'a--1': {
status: 'pending',
title: 'an addon title',
description: 'an addon description',
},
'a--2': { status: 'success', title: 'a addon title', description: '' },
});
expect(store.getState().index).toMatchInlineSnapshot(`
Object {
"a": Object {
"children": Array [
"a--1",
],
"depth": 0,
"id": "a",
"isComponent": true,
"isLeaf": false,
"isRoot": false,
"name": "a",
"parent": undefined,
"renderLabel": undefined,
"type": "component",
},
"a--1": Object {
"depth": 1,
"id": "a--1",
"importPath": "./a.ts",
"isComponent": false,
"isLeaf": true,
"isRoot": false,
"kind": "a",
"name": "1",
"parent": "a",
"prepared": false,
"renderLabel": undefined,
"title": "a",
"type": "story",
},
}
`);
});
it('persists filter when index is updated', async () => {
const moduleArgs = createMockModuleArgs({});
const { api } = initStories(moduleArgs as unknown as ModuleArgs);
const { store } = moduleArgs;
await api.setIndex({ v: 4, entries: navigationEntries });
await api.experimental_setFilter('myCustomFilter', (item) => item.id.startsWith('a'));
await api.setIndex({ v: 4, entries: navigationEntries });
const { index } = store.getState();
expect(index).toMatchInlineSnapshot(`
Object {
"a": Object {
"children": Array [
"a--1",
"a--2",
],
"depth": 0,
"id": "a",
"isComponent": true,
"isLeaf": false,
"isRoot": false,
"name": "a",
"parent": undefined,
"renderLabel": undefined,
"type": "component",
},
"a--1": Object {
"depth": 1,
"id": "a--1",
"importPath": "./a.ts",
"isComponent": false,
"isLeaf": true,
"isRoot": false,
"kind": "a",
"name": "1",
"parent": "a",
"prepared": false,
"renderLabel": undefined,
"title": "a",
"type": "story",
},
"a--2": Object {
"depth": 1,
"id": "a--2",
"importPath": "./a.ts",
"isComponent": false,
"isLeaf": true,
"isRoot": false,
"kind": "a",
"name": "2",
"parent": "a",
"prepared": false,
"renderLabel": undefined,
"title": "a",
"type": "story",
},
}
`);
});
});
});
|
1,079 | 0 | petrpan-code/storybookjs/storybook/code/lib/node-logger | petrpan-code/storybookjs/storybook/code/lib/node-logger/src/index.test.ts | import { info, warn } from 'npmlog';
import { logger } from '.';
globalThis.console = { log: jest.fn() } as any;
jest.mock('npmlog', () => ({
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
levels: {
silly: -Infinity,
verbose: 1000,
info: 2000,
timing: 2500,
http: 3000,
notice: 3500,
warn: 4000,
error: 5000,
silent: Infinity,
},
level: 'info',
}));
//
describe('node-logger', () => {
it('should have an info method', () => {
const message = 'information';
logger.info(message);
expect(info).toHaveBeenCalledWith('', message);
});
it('should have a warn method', () => {
const message = 'warning message';
logger.warn(message);
expect(warn).toHaveBeenCalledWith('', message);
});
it('should have an error method', () => {
const message = 'error message';
logger.error(message);
expect(globalThis.console.log).toHaveBeenCalledWith(expect.stringMatching('message'));
});
it('should format errors', () => {
const message = new Error('A complete disaster');
logger.error(message);
expect(globalThis.console.log).toHaveBeenCalledWith(
expect.stringMatching('A complete disaster')
);
});
});
|
1,086 | 0 | petrpan-code/storybookjs/storybook/code/lib/postinstall | petrpan-code/storybookjs/storybook/code/lib/postinstall/src/codemods.test.ts | import path from 'path';
import fs from 'fs';
import 'jest-specific-snapshot';
// @ts-expect-error (broken types)
import { applyTransform } from 'jscodeshift/dist/testUtils';
jest.mock('@storybook/node-logger');
const inputRegExp = /\.input\.js$/;
const fixturesDir = path.resolve(__dirname, './__testfixtures__');
fs.readdirSync(fixturesDir).forEach((transformName) => {
const transformFixturesDir = path.join(fixturesDir, transformName);
describe(`${transformName}`, () => {
fs.readdirSync(transformFixturesDir)
.filter((fileName) => inputRegExp.test(fileName))
.forEach((fileName) => {
const inputPath = path.join(transformFixturesDir, fileName);
it(`transforms correctly using "${fileName}" data`, () =>
expect(
applyTransform(
// eslint-disable-next-line global-require,import/no-dynamic-require
require(path.join(__dirname, '__testtransforms__', transformName)),
null,
{ path: inputPath, source: fs.readFileSync(inputPath, 'utf8') }
)
).toMatchSpecificSnapshot(inputPath.replace(inputRegExp, '.output.snapshot')));
});
});
});
|
1,087 | 0 | petrpan-code/storybookjs/storybook/code/lib/postinstall | petrpan-code/storybookjs/storybook/code/lib/postinstall/src/frameworks.test.ts | import { getFrameworks } from './frameworks';
const REACT = {
'@storybook/react': '5.2.5',
};
const VUE = {
'@storybook/vue': '5.2.5',
};
const NONE = {
'@storybook/preview-api': '5.2.5',
lodash: '^4.17.15',
};
describe('getFrameworks', () => {
it('single framework', () => {
const frameworks = getFrameworks({
dependencies: NONE,
devDependencies: REACT,
});
expect(frameworks).toEqual(['react']);
});
it('multi-framework', () => {
const frameworks = getFrameworks({
dependencies: VUE,
devDependencies: REACT,
});
expect(frameworks.sort()).toEqual(['react', 'vue']);
});
it('no deps', () => {
const frameworks = getFrameworks({});
expect(frameworks).toEqual([]);
});
it('no framework', () => {
const frameworks = getFrameworks({
dependencies: NONE,
});
expect(frameworks).toEqual([]);
});
});
|
1,121 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/addons/make-decorator.test.ts | import type { Addon_StoryContext } from '@storybook/types';
import { makeDecorator } from './make-decorator';
// Copy & paste from internal api: client-api/src/client_api
type DecoratorFn = (fn: any, context: Addon_StoryContext) => any;
const defaultDecorateStory = (getStory: any, decorators: DecoratorFn[]) =>
decorators.reduce(
(decorated, decorator) => (context: Addon_StoryContext) =>
decorator(() => decorated(context), context),
getStory
);
const baseContext = {
name: '',
kind: '',
parameters: {},
};
describe('makeDecorator', () => {
it('returns a decorator that passes parameters on the parameters argument', () => {
const wrapper = jest.fn();
const decorator = makeDecorator({ wrapper, name: 'test', parameterName: 'test' });
const story = jest.fn();
const decoratedStory = defaultDecorateStory(story, [decorator]);
const context = { kind: '', name: '', parameters: { test: 'test-val' } };
decoratedStory(context);
expect(wrapper).toHaveBeenCalledWith(expect.any(Function), context, { parameters: 'test-val' });
});
it('passes options added at decoration time', () => {
const wrapper = jest.fn();
const decorator = makeDecorator({ wrapper, name: 'test', parameterName: 'test' });
const story = jest.fn();
const options = 'test-val';
const decoratedStory = defaultDecorateStory(story, [decorator(options)]);
const context = { ...baseContext };
decoratedStory(context);
expect(wrapper).toHaveBeenCalledWith(expect.any(Function), context, { options: 'test-val' });
});
it('passes object options added at decoration time', () => {
const wrapper = jest.fn();
const decorator = makeDecorator({ wrapper, name: 'test', parameterName: 'test' });
const story = jest.fn();
const options = { test: 'val' };
const decoratedStory = defaultDecorateStory(story, [decorator(options)]);
const context = { ...baseContext };
decoratedStory(context);
expect(wrapper).toHaveBeenCalledWith(expect.any(Function), context, {
options: { test: 'val' },
});
});
it('passes multiple options added at decoration time', () => {
const wrapper = jest.fn();
const decorator = makeDecorator({ wrapper, name: 'test', parameterName: 'test' });
const story = jest.fn();
const options = ['test-val', 'test-val2'];
const decoratedStory = defaultDecorateStory(story, [decorator(...options)]);
const context = { ...baseContext };
decoratedStory(context);
expect(wrapper).toHaveBeenCalledWith(expect.any(Function), context, {
options: ['test-val', 'test-val2'],
});
});
it('passes multiple options including objects added at decoration time', () => {
const wrapper = jest.fn();
const decorator = makeDecorator({ wrapper, name: 'test', parameterName: 'test' });
const story = jest.fn();
const options = ['test-val', 'test-val2', { test: 'val' }];
const decoratedStory = defaultDecorateStory(story, [decorator(...options)]);
const context = { ...baseContext };
decoratedStory(context);
expect(wrapper).toHaveBeenCalledWith(expect.any(Function), context, {
options: ['test-val', 'test-val2', { test: 'val' }],
});
});
it('passes both options *and* parameters at the same time', () => {
const wrapper = jest.fn();
const decorator = makeDecorator({ wrapper, name: 'test', parameterName: 'test' });
const story = jest.fn();
const options = 'test-val';
const decoratedStory = defaultDecorateStory(story, [decorator(options)]);
const context = { ...baseContext, parameters: { test: 'test-val' } };
decoratedStory(context);
expect(wrapper).toHaveBeenCalledWith(expect.any(Function), context, {
options: 'test-val',
parameters: 'test-val',
});
});
it('passes nothing if neither are supplied', () => {
const wrapper = jest.fn();
const decorator = makeDecorator({ wrapper, name: 'test', parameterName: 'test' });
const story = jest.fn();
const decoratedStory = defaultDecorateStory(story, [decorator]);
const context = { ...baseContext };
decoratedStory(context);
expect(wrapper).toHaveBeenCalledWith(expect.any(Function), context, {});
});
it('calls the story directly if neither options or parameters are supplied and skipIfNoParametersOrOptions is true', () => {
const wrapper = jest.fn();
const decorator = makeDecorator({
wrapper,
name: 'test',
parameterName: 'test',
skipIfNoParametersOrOptions: true,
});
const story = jest.fn();
const decoratedStory = defaultDecorateStory(story, [decorator]);
const context = { ...baseContext };
decoratedStory(context);
expect(wrapper).not.toHaveBeenCalled();
expect(story).toHaveBeenCalled();
});
it('calls the story directly if the disable parameter is passed to the decorator', () => {
const wrapper = jest.fn();
const decorator = makeDecorator({
wrapper,
name: 'test',
parameterName: 'test',
skipIfNoParametersOrOptions: true,
});
const story = jest.fn();
const decoratedStory = defaultDecorateStory(story, [decorator]);
const context = { ...baseContext, parameters: { test: { disable: true } } };
decoratedStory(context);
expect(wrapper).not.toHaveBeenCalled();
expect(story).toHaveBeenCalled();
});
it('throws if options are added at storytime, if not allowed', () => {
const wrapper = jest.fn();
const decorator = makeDecorator({
wrapper,
name: 'test',
parameterName: 'test',
});
const options = 'test-val';
const story = jest.fn();
expect(() => decorator(options)(story)).toThrow(/not allowed/);
});
});
|
1,124 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/client-api/ClientApi.test.ts | import { addons, mockChannel } from '../addons';
import { ClientApi } from './ClientApi';
beforeEach(() => {
addons.setChannel(mockChannel());
});
describe('ClientApi', () => {
describe('getStoryIndex', () => {
it('should remember the order that files were added in', async () => {
const clientApi = new ClientApi();
const store = {
processCSFFileWithCache: jest.fn(() => ({ meta: { title: 'title' } })),
storyFromCSFFile: jest.fn(({ storyId }) => ({
id: storyId,
parameters: { fileName: storyId.split('-')[0].replace('kind', 'file') },
})),
};
clientApi.storyStore = store as any;
let disposeCallback: () => void = () => {};
const module1 = {
id: 'file1',
hot: {
data: {},
accept: jest.fn(),
dispose(cb: () => void) {
disposeCallback = cb;
},
},
};
const module2 = {
id: 'file2',
};
clientApi.storiesOf('kind1', module1 as unknown as NodeModule).add('story1', jest.fn());
clientApi.storiesOf('kind2', module2 as unknown as NodeModule).add('story2', jest.fn());
// This gets called by configure
// eslint-disable-next-line no-underscore-dangle
clientApi._loadAddedExports();
expect(Object.keys(clientApi.getStoryIndex().entries)).toEqual([
'kind1--story1',
'kind2--story2',
]);
disposeCallback();
clientApi.storiesOf('kind1', module1 as unknown as NodeModule).add('story1', jest.fn());
await new Promise((r) => setTimeout(r, 0));
expect(Object.keys(clientApi.getStoryIndex().entries)).toEqual([
'kind1--story1',
'kind2--story2',
]);
});
});
});
|
1,131 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/core-client/start.test.ts | /* eslint-disable no-underscore-dangle */
/**
* @jest-environment jsdom
*/
// import { describe, it, beforeAll, beforeEach, afterAll, afterEach, jest } from '@jest/globals';
import { STORY_RENDERED, STORY_UNCHANGED, SET_INDEX, CONFIG_ERROR } from '@storybook/core-events';
import type { ModuleExports, Path } from '@storybook/types';
import { global } from '@storybook/global';
import { setGlobalRender } from '../../client-api';
import {
waitForRender,
waitForEvents,
waitForQuiescence,
emitter,
mockChannel,
} from '../preview-web/PreviewWeb.mockdata';
import { start as realStart } from './start';
import type { Loadable } from './executeLoadable';
jest.mock('@storybook/global', () => ({
global: {
...globalThis,
window: globalThis,
history: { replaceState: jest.fn() },
document: {
location: {
pathname: 'pathname',
search: '?id=*',
},
},
DOCS_OPTIONS: {},
},
}));
// console.log(global);
jest.mock('@storybook/channels', () => ({
createBrowserChannel: () => mockChannel,
}));
jest.mock('@storybook/client-logger');
jest.mock('react-dom');
// for the auto-title test
jest.mock('../../store', () => {
const actualStore = jest.requireActual('../../store');
return {
...actualStore,
userOrAutoTitle: (importPath: Path, specifier: any, userTitle?: string) =>
userTitle || 'auto-title',
};
});
jest.mock('../../preview-web', () => {
const actualPreviewWeb = jest.requireActual('../../preview-web');
class OverloadPreviewWeb extends actualPreviewWeb.PreviewWeb {
constructor() {
super();
this.view = {
...Object.fromEntries(
Object.getOwnPropertyNames(this.view.constructor.prototype).map((key) => [key, jest.fn()])
),
prepareForDocs: jest.fn().mockReturnValue('docs-root'),
prepareForStory: jest.fn().mockReturnValue('story-root'),
};
}
}
return {
...actualPreviewWeb,
PreviewWeb: OverloadPreviewWeb,
};
});
beforeEach(() => {
mockChannel.emit.mockClear();
// Preview doesn't clean itself up as it isn't designed to ever be stopped :shrug:
emitter.removeAllListeners();
});
const start: typeof realStart = (...args) => {
const result = realStart(...args);
const configure: typeof result['configure'] = (
framework: string,
loadable: Loadable,
m?: NodeModule,
disableBackwardCompatibility = false
) => result.configure(framework, loadable, m, disableBackwardCompatibility);
return {
...result,
configure,
};
};
afterEach(() => {
// I'm not sure why this is required (it seems just afterEach is required really)
mockChannel.emit.mockClear();
});
function makeRequireContext(importMap: Record<Path, ModuleExports>) {
const req = (path: Path) => importMap[path];
req.keys = () => Object.keys(importMap);
return req;
}
describe('start', () => {
beforeEach(() => {
global.DOCS_OPTIONS = {};
// @ts-expect-error (setting this to undefined is indeed what we want to do)
global.__STORYBOOK_CLIENT_API__ = undefined;
// @ts-expect-error (setting this to undefined is indeed what we want to do)
global.__STORYBOOK_PREVIEW__ = undefined;
// @ts-expect-error (setting this to undefined is indeed what we want to do)
global.IS_STORYBOOK = undefined;
});
describe('when configure is called with storiesOf only', () => {
it('loads and renders the first story correctly', async () => {
const renderToCanvas = jest.fn();
const { configure, clientApi } = start(renderToCanvas);
configure('test', () => {
clientApi
.storiesOf('Component A', { id: 'file1' } as NodeModule)
.add('Story One', jest.fn())
.add('Story Two', jest.fn());
clientApi
.storiesOf('Component B', { id: 'file2' } as NodeModule)
.add('Story Three', jest.fn());
});
await waitForRender();
expect(mockChannel.emit.mock.calls.find((call) => call[0] === SET_INDEX)?.[1])
.toMatchInlineSnapshot(`
Object {
"entries": Object {
"component-a--story-one": Object {
"argTypes": Object {},
"args": Object {},
"componentId": "component-a",
"id": "component-a--story-one",
"importPath": "file1",
"initialArgs": Object {},
"name": "Story One",
"parameters": Object {
"__id": "component-a--story-one",
"__isArgsStory": false,
"fileName": "file1",
"renderer": "test",
},
"tags": Array [
"story",
],
"title": "Component A",
"type": "story",
},
"component-a--story-two": Object {
"argTypes": Object {},
"args": Object {},
"componentId": "component-a",
"id": "component-a--story-two",
"importPath": "file1",
"initialArgs": Object {},
"name": "Story Two",
"parameters": Object {
"__id": "component-a--story-two",
"__isArgsStory": false,
"fileName": "file1",
"renderer": "test",
},
"tags": Array [
"story",
],
"title": "Component A",
"type": "story",
},
"component-b--story-three": Object {
"argTypes": Object {},
"args": Object {},
"componentId": "component-b",
"id": "component-b--story-three",
"importPath": "file2",
"initialArgs": Object {},
"name": "Story Three",
"parameters": Object {
"__id": "component-b--story-three",
"__isArgsStory": false,
"fileName": "file2",
"renderer": "test",
},
"tags": Array [
"story",
],
"title": "Component B",
"type": "story",
},
},
"v": 4,
}
`);
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-a--story-one');
expect(renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
id: 'component-a--story-one',
}),
'story-root'
);
});
it('deals with stories with "default" name', async () => {
const renderToCanvas = jest.fn();
const { configure, clientApi } = start(renderToCanvas);
configure('test', () => {
clientApi.storiesOf('Component A', { id: 'file1' } as NodeModule).add('default', jest.fn());
});
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-a--default');
});
it('deals with stories with camel-cased names', async () => {
const renderToCanvas = jest.fn();
const { configure, clientApi } = start(renderToCanvas);
configure('test', () => {
clientApi
.storiesOf('Component A', { id: 'file1' } as NodeModule)
.add('storyOne', jest.fn());
});
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-a--storyone');
});
it('deals with stories with spaces in the name', async () => {
const renderToCanvas = jest.fn();
const { configure, clientApi } = start(renderToCanvas);
configure('test', () => {
clientApi
.storiesOf('Component A', { id: 'file1' } as NodeModule)
.add('Story One', jest.fn());
});
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-a--story-one');
});
// https://github.com/storybookjs/storybook/issues/16303
it('deals with stories with numeric names', async () => {
const renderToCanvas = jest.fn();
const { configure, clientApi } = start(renderToCanvas);
configure('test', () => {
clientApi.storiesOf('Component A', { id: 'file1' } as NodeModule).add('story0', jest.fn());
});
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-a--story0');
});
it('deals with storiesOf from the same file twice', async () => {
const renderToCanvas = jest.fn();
const { configure, clientApi } = start(renderToCanvas);
configure('test', () => {
clientApi.storiesOf('Component A', { id: 'file1' } as NodeModule).add('default', jest.fn());
clientApi.storiesOf('Component B', { id: 'file1' } as NodeModule).add('default', jest.fn());
clientApi.storiesOf('Component C', { id: 'file1' } as NodeModule).add('default', jest.fn());
});
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-a--default');
const storiesOfData = mockChannel.emit.mock.calls.find((call) => call[0] === SET_INDEX)?.[1];
expect(Object.values(storiesOfData.entries).map((s: any) => s.parameters.fileName)).toEqual([
'file1',
'file1-2',
'file1-3',
]);
});
it('allows setting compomnent/args/argTypes via a parameter', async () => {
const renderToCanvas = jest.fn(({ storyFn }) => storyFn());
const { configure, clientApi } = start(renderToCanvas);
const component = {};
configure('test', () => {
clientApi
.storiesOf('Component A', { id: 'file1' } as NodeModule)
.addParameters({
component,
args: { a: 'a' },
argTypes: { a: { type: 'string' } },
})
.add('default', jest.fn(), {
args: { b: 'b' },
argTypes: { b: { type: 'string' } },
});
});
await waitForRender();
expect(renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
storyContext: expect.objectContaining({
component,
args: { a: 'a', b: 'b' },
argTypes: {
a: { name: 'a', type: { name: 'string' } },
b: { name: 'b', type: { name: 'string' } },
},
}),
}),
'story-root'
);
expect(global.IS_STORYBOOK).toBe(true);
});
it('supports forceRerender()', async () => {
const renderToCanvas = jest.fn(({ storyFn }) => storyFn());
const { configure, clientApi, forceReRender } = start(renderToCanvas);
configure('test', () => {
clientApi.storiesOf('Component A', { id: 'file1' } as NodeModule).add('default', jest.fn());
});
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-a--default');
mockChannel.emit.mockClear();
forceReRender();
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-a--default');
});
it('supports HMR when a story file changes', async () => {
const renderToCanvas = jest.fn(({ storyFn }) => storyFn());
const { configure, clientApi } = start(renderToCanvas);
let disposeCallback: () => void = () => {};
const module = {
id: 'file1',
hot: {
accept: jest.fn(),
dispose(cb: () => void) {
disposeCallback = cb;
},
},
};
const firstImplementation = jest.fn();
configure('test', () => {
clientApi.storiesOf('Component A', module as any).add('default', firstImplementation);
});
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-a--default');
expect(firstImplementation).toHaveBeenCalled();
expect(module.hot.accept).toHaveBeenCalled();
expect(disposeCallback).toBeDefined();
mockChannel.emit.mockClear();
disposeCallback();
const secondImplementation = jest.fn();
clientApi.storiesOf('Component A', module as any).add('default', secondImplementation);
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-a--default');
expect(secondImplementation).toHaveBeenCalled();
});
it('re-emits SET_INDEX when a story is added', async () => {
const renderToCanvas = jest.fn(({ storyFn }) => storyFn());
const { configure, clientApi } = start(renderToCanvas);
let disposeCallback: () => void = () => {};
const module = {
id: 'file1',
hot: {
accept: jest.fn(),
dispose(cb: () => void) {
disposeCallback = cb;
},
},
};
configure('test', () => {
clientApi.storiesOf('Component A', module as any).add('default', jest.fn());
});
await waitForRender();
mockChannel.emit.mockClear();
disposeCallback();
clientApi
.storiesOf('Component A', module as any)
.add('default', jest.fn())
.add('new', jest.fn());
await waitForEvents([SET_INDEX]);
expect(mockChannel.emit.mock.calls.find((call) => call[0] === SET_INDEX)?.[1])
.toMatchInlineSnapshot(`
Object {
"entries": Object {
"component-a--default": Object {
"argTypes": Object {},
"args": Object {},
"componentId": "component-a",
"id": "component-a--default",
"importPath": "file1",
"initialArgs": Object {},
"name": "default",
"parameters": Object {
"__id": "component-a--default",
"__isArgsStory": false,
"fileName": "file1",
"renderer": "test",
},
"tags": Array [
"story",
],
"title": "Component A",
"type": "story",
},
"component-a--new": Object {
"argTypes": Object {},
"args": Object {},
"componentId": "component-a",
"id": "component-a--new",
"importPath": "file1",
"initialArgs": Object {},
"name": "new",
"parameters": Object {
"__id": "component-a--new",
"__isArgsStory": false,
"fileName": "file1",
"renderer": "test",
},
"tags": Array [
"story",
],
"title": "Component A",
"type": "story",
},
},
"v": 4,
}
`);
});
it('re-emits SET_INDEX when a story file is removed', async () => {
const renderToCanvas = jest.fn(({ storyFn }) => storyFn());
const { configure, clientApi } = start(renderToCanvas);
let disposeCallback: () => void = () => {};
const moduleB = {
id: 'file2',
hot: {
accept: jest.fn(),
dispose(cb: () => void) {
disposeCallback = cb;
},
},
};
configure('test', () => {
clientApi.storiesOf('Component A', { id: 'file1' } as any).add('default', jest.fn());
clientApi.storiesOf('Component B', moduleB as any).add('default', jest.fn());
});
await waitForEvents([SET_INDEX]);
expect(mockChannel.emit.mock.calls.find((call) => call[0] === SET_INDEX)?.[1])
.toMatchInlineSnapshot(`
Object {
"entries": Object {
"component-a--default": Object {
"argTypes": Object {},
"args": Object {},
"componentId": "component-a",
"id": "component-a--default",
"importPath": "file1",
"initialArgs": Object {},
"name": "default",
"parameters": Object {
"__id": "component-a--default",
"__isArgsStory": false,
"fileName": "file1",
"renderer": "test",
},
"tags": Array [
"story",
],
"title": "Component A",
"type": "story",
},
"component-b--default": Object {
"argTypes": Object {},
"args": Object {},
"componentId": "component-b",
"id": "component-b--default",
"importPath": "file2",
"initialArgs": Object {},
"name": "default",
"parameters": Object {
"__id": "component-b--default",
"__isArgsStory": false,
"fileName": "file2",
"renderer": "test",
},
"tags": Array [
"story",
],
"title": "Component B",
"type": "story",
},
},
"v": 4,
}
`);
mockChannel.emit.mockClear();
disposeCallback();
await waitForEvents([SET_INDEX]);
expect(mockChannel.emit.mock.calls.find((call) => call[0] === SET_INDEX)?.[1])
.toMatchInlineSnapshot(`
Object {
"entries": Object {
"component-a--default": Object {
"argTypes": Object {},
"args": Object {},
"componentId": "component-a",
"id": "component-a--default",
"importPath": "file1",
"initialArgs": Object {},
"name": "default",
"parameters": Object {
"__id": "component-a--default",
"__isArgsStory": false,
"fileName": "file1",
"renderer": "test",
},
"tags": Array [
"story",
],
"title": "Component A",
"type": "story",
},
},
"v": 4,
}
`);
});
});
const componentCExports = {
default: {
title: 'Component C',
tags: ['component-tag', 'autodocs'],
},
StoryOne: {
render: jest.fn(),
tags: ['story-tag'],
},
StoryTwo: jest.fn(),
};
describe('when configure is called with CSF only', () => {
it('loads and renders the first story correctly', async () => {
const renderToCanvas = jest.fn();
const { configure } = start(renderToCanvas);
configure('test', () => [componentCExports]);
await waitForRender();
expect(mockChannel.emit.mock.calls.find((call) => call[0] === SET_INDEX)?.[1])
.toMatchInlineSnapshot(`
Object {
"entries": Object {
"component-c--story-one": Object {
"argTypes": Object {},
"args": Object {},
"id": "component-c--story-one",
"importPath": "exports-map-0",
"initialArgs": Object {},
"name": "Story One",
"parameters": Object {
"__isArgsStory": false,
"fileName": "exports-map-0",
"renderer": "test",
},
"tags": Array [
"story-tag",
"story",
],
"title": "Component C",
"type": "story",
},
"component-c--story-two": Object {
"argTypes": Object {},
"args": Object {},
"id": "component-c--story-two",
"importPath": "exports-map-0",
"initialArgs": Object {},
"name": "Story Two",
"parameters": Object {
"__isArgsStory": false,
"fileName": "exports-map-0",
"renderer": "test",
},
"tags": Array [
"component-tag",
"autodocs",
"story",
],
"title": "Component C",
"type": "story",
},
},
"v": 4,
}
`);
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-c--story-one');
expect(renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
id: 'component-c--story-one',
}),
'story-root'
);
});
it('supports HMR when a story file changes', async () => {
const renderToCanvas = jest.fn(({ storyFn }) => storyFn());
let disposeCallback: (data: object) => void = () => {};
const module = {
id: 'file1',
hot: {
data: {},
accept: jest.fn(),
dispose(cb: () => void) {
disposeCallback = cb;
},
},
};
const { configure } = start(renderToCanvas);
configure('test', () => [componentCExports], module as any);
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-c--story-one');
expect(componentCExports.StoryOne.render).toHaveBeenCalled();
expect(module.hot.accept).toHaveBeenCalled();
expect(disposeCallback).toBeDefined();
mockChannel.emit.mockClear();
disposeCallback(module.hot.data);
const secondImplementation = jest.fn();
configure(
'test',
() => [{ ...componentCExports, StoryOne: secondImplementation }],
module as any
);
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-c--story-one');
expect(secondImplementation).toHaveBeenCalled();
});
it('re-emits SET_INDEX when a story is added', async () => {
const renderToCanvas = jest.fn(({ storyFn }) => storyFn());
let disposeCallback: (data: object) => void = () => {};
const module = {
id: 'file1',
hot: {
data: {},
accept: jest.fn(),
dispose(cb: () => void) {
disposeCallback = cb;
},
},
};
const { configure } = start(renderToCanvas);
configure('test', () => [componentCExports], module as any);
await waitForRender();
mockChannel.emit.mockClear();
disposeCallback(module.hot.data);
configure('test', () => [{ ...componentCExports, StoryThree: jest.fn() }], module as any);
await waitForEvents([SET_INDEX]);
expect(mockChannel.emit.mock.calls.find((call) => call[0] === SET_INDEX)?.[1])
.toMatchInlineSnapshot(`
Object {
"entries": Object {
"component-c--story-one": Object {
"argTypes": Object {},
"args": Object {},
"id": "component-c--story-one",
"importPath": "exports-map-0",
"initialArgs": Object {},
"name": "Story One",
"parameters": Object {
"__isArgsStory": false,
"fileName": "exports-map-0",
"renderer": "test",
},
"tags": Array [
"story-tag",
"story",
],
"title": "Component C",
"type": "story",
},
"component-c--story-three": Object {
"argTypes": Object {},
"args": Object {},
"id": "component-c--story-three",
"importPath": "exports-map-0",
"initialArgs": Object {},
"name": "Story Three",
"parameters": Object {
"__isArgsStory": false,
"fileName": "exports-map-0",
"renderer": "test",
},
"tags": Array [
"component-tag",
"autodocs",
"story",
],
"title": "Component C",
"type": "story",
},
"component-c--story-two": Object {
"argTypes": Object {},
"args": Object {},
"id": "component-c--story-two",
"importPath": "exports-map-0",
"initialArgs": Object {},
"name": "Story Two",
"parameters": Object {
"__isArgsStory": false,
"fileName": "exports-map-0",
"renderer": "test",
},
"tags": Array [
"component-tag",
"autodocs",
"story",
],
"title": "Component C",
"type": "story",
},
},
"v": 4,
}
`);
});
it('re-emits SET_INDEX when a story file is removed', async () => {
const renderToCanvas = jest.fn(({ storyFn }) => storyFn());
let disposeCallback: (data: object) => void = () => {};
const module = {
id: 'file1',
hot: {
data: {},
accept: jest.fn(),
dispose(cb: () => void) {
disposeCallback = cb;
},
},
};
const { configure } = start(renderToCanvas);
configure(
'test',
() => [componentCExports, { default: { title: 'Component D' }, StoryFour: jest.fn() }],
module as any
);
await waitForEvents([SET_INDEX]);
expect(mockChannel.emit.mock.calls.find((call) => call[0] === SET_INDEX)?.[1])
.toMatchInlineSnapshot(`
Object {
"entries": Object {
"component-c--story-one": Object {
"argTypes": Object {},
"args": Object {},
"id": "component-c--story-one",
"importPath": "exports-map-0",
"initialArgs": Object {},
"name": "Story One",
"parameters": Object {
"__isArgsStory": false,
"fileName": "exports-map-0",
"renderer": "test",
},
"tags": Array [
"story-tag",
"story",
],
"title": "Component C",
"type": "story",
},
"component-c--story-two": Object {
"argTypes": Object {},
"args": Object {},
"id": "component-c--story-two",
"importPath": "exports-map-0",
"initialArgs": Object {},
"name": "Story Two",
"parameters": Object {
"__isArgsStory": false,
"fileName": "exports-map-0",
"renderer": "test",
},
"tags": Array [
"component-tag",
"autodocs",
"story",
],
"title": "Component C",
"type": "story",
},
"component-d--story-four": Object {
"argTypes": Object {},
"args": Object {},
"id": "component-d--story-four",
"importPath": "exports-map-1",
"initialArgs": Object {},
"name": "Story Four",
"parameters": Object {
"__isArgsStory": false,
"fileName": "exports-map-1",
"renderer": "test",
},
"tags": Array [
"story",
],
"title": "Component D",
"type": "story",
},
},
"v": 4,
}
`);
await waitForRender();
mockChannel.emit.mockClear();
disposeCallback(module.hot.data);
configure('test', () => [componentCExports], module as any);
await waitForEvents([SET_INDEX]);
expect(mockChannel.emit.mock.calls.find((call) => call[0] === SET_INDEX)?.[1])
.toMatchInlineSnapshot(`
Object {
"entries": Object {
"component-c--story-one": Object {
"argTypes": Object {},
"args": Object {},
"id": "component-c--story-one",
"importPath": "exports-map-0",
"initialArgs": Object {},
"name": "Story One",
"parameters": Object {
"__isArgsStory": false,
"fileName": "exports-map-0",
"renderer": "test",
},
"tags": Array [
"story-tag",
"story",
],
"title": "Component C",
"type": "story",
},
"component-c--story-two": Object {
"argTypes": Object {},
"args": Object {},
"id": "component-c--story-two",
"importPath": "exports-map-0",
"initialArgs": Object {},
"name": "Story Two",
"parameters": Object {
"__isArgsStory": false,
"fileName": "exports-map-0",
"renderer": "test",
},
"tags": Array [
"component-tag",
"autodocs",
"story",
],
"title": "Component C",
"type": "story",
},
},
"v": 4,
}
`);
await waitForEvents([STORY_UNCHANGED]);
});
it('allows you to override the render function in project annotations', async () => {
const renderToCanvas = jest.fn(({ storyFn }) => storyFn());
const frameworkRender = jest.fn();
const { configure } = start(renderToCanvas, { render: frameworkRender });
const projectRender = jest.fn();
setGlobalRender(projectRender);
configure('test', () => {
return [
{
default: {
title: 'Component A',
component: jest.fn(),
},
StoryOne: {},
},
];
});
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-a--story-one');
expect(frameworkRender).not.toHaveBeenCalled();
expect(projectRender).toHaveBeenCalled();
});
describe('docs', () => {
beforeEach(() => {
global.DOCS_OPTIONS = {};
});
// NOTE: MDX files are only ever passed as CSF
it('sends over docs only stories as entries', async () => {
const renderToCanvas = jest.fn();
const { configure } = start(renderToCanvas);
configure(
'test',
makeRequireContext({
'./Introduction.stories.mdx': {
default: { title: 'Introduction', tags: ['stories-mdx'] },
_Page: { name: 'Page', parameters: { docsOnly: true } },
},
})
);
await waitForEvents([SET_INDEX]);
expect(mockChannel.emit.mock.calls.find((call) => call[0] === SET_INDEX)?.[1])
.toMatchInlineSnapshot(`
Object {
"entries": Object {
"introduction": Object {
"id": "introduction",
"importPath": "./Introduction.stories.mdx",
"name": undefined,
"parameters": Object {
"fileName": "./Introduction.stories.mdx",
"renderer": "test",
},
"storiesImports": Array [],
"tags": Array [
"stories-mdx",
"docs",
],
"title": "Introduction",
"type": "docs",
},
},
"v": 4,
}
`);
// Wait a second to let the docs "render" finish (and maybe throw)
await waitForQuiescence();
});
it('errors on .mdx files', async () => {
const renderToCanvas = jest.fn();
const { configure } = start(renderToCanvas);
configure(
'test',
makeRequireContext({
'./Introduction.mdx': {
default: () => 'some mdx function',
},
})
);
await waitForEvents([CONFIG_ERROR]);
expect(mockChannel.emit.mock.calls.find((call) => call[0] === CONFIG_ERROR)?.[1])
.toMatchInlineSnapshot(`
[Error: Cannot index \`.mdx\` file (\`./Introduction.mdx\`) in \`storyStoreV7: false\` mode.
The legacy story store does not support new-style \`.mdx\` files. If the file above
is not intended to be indexed (i.e. displayed as an entry in the sidebar), either
exclude it from your \`stories\` glob, or add <Meta isTemplate /> to it.
If you wanted to index the file, you'll need to name it \`stories.mdx\` and stick to the
legacy (6.x) MDX API, or use the new store.]
`);
});
});
});
describe('when configure is called with a combination', () => {
it('loads and renders the first story correctly', async () => {
const renderToCanvas = jest.fn();
const { configure, clientApi } = start(renderToCanvas);
configure('test', () => {
clientApi
.storiesOf('Component A', { id: 'file1' } as NodeModule)
.add('Story One', jest.fn())
.add('Story Two', jest.fn());
clientApi
.storiesOf('Component B', { id: 'file2' } as NodeModule)
.add('Story Three', jest.fn());
return [componentCExports];
});
await waitForRender();
expect(mockChannel.emit.mock.calls.find((call) => call[0] === SET_INDEX)?.[1])
.toMatchInlineSnapshot(`
Object {
"entries": Object {
"component-a--story-one": Object {
"argTypes": Object {},
"args": Object {},
"componentId": "component-a",
"id": "component-a--story-one",
"importPath": "file1",
"initialArgs": Object {},
"name": "Story One",
"parameters": Object {
"__id": "component-a--story-one",
"__isArgsStory": false,
"fileName": "file1",
"renderer": "test",
},
"tags": Array [
"story",
],
"title": "Component A",
"type": "story",
},
"component-a--story-two": Object {
"argTypes": Object {},
"args": Object {},
"componentId": "component-a",
"id": "component-a--story-two",
"importPath": "file1",
"initialArgs": Object {},
"name": "Story Two",
"parameters": Object {
"__id": "component-a--story-two",
"__isArgsStory": false,
"fileName": "file1",
"renderer": "test",
},
"tags": Array [
"story",
],
"title": "Component A",
"type": "story",
},
"component-b--story-three": Object {
"argTypes": Object {},
"args": Object {},
"componentId": "component-b",
"id": "component-b--story-three",
"importPath": "file2",
"initialArgs": Object {},
"name": "Story Three",
"parameters": Object {
"__id": "component-b--story-three",
"__isArgsStory": false,
"fileName": "file2",
"renderer": "test",
},
"tags": Array [
"story",
],
"title": "Component B",
"type": "story",
},
"component-c--story-one": Object {
"argTypes": Object {},
"args": Object {},
"id": "component-c--story-one",
"importPath": "exports-map-0",
"initialArgs": Object {},
"name": "Story One",
"parameters": Object {
"__isArgsStory": false,
"fileName": "exports-map-0",
"renderer": "test",
},
"tags": Array [
"story-tag",
"story",
],
"title": "Component C",
"type": "story",
},
"component-c--story-two": Object {
"argTypes": Object {},
"args": Object {},
"id": "component-c--story-two",
"importPath": "exports-map-0",
"initialArgs": Object {},
"name": "Story Two",
"parameters": Object {
"__isArgsStory": false,
"fileName": "exports-map-0",
"renderer": "test",
},
"tags": Array [
"component-tag",
"autodocs",
"story",
],
"title": "Component C",
"type": "story",
},
},
"v": 4,
}
`);
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-a--story-one');
expect(renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
id: 'component-a--story-one',
}),
'story-root'
);
});
describe('autodocs', () => {
beforeEach(() => {
global.DOCS_OPTIONS = { autodocs: 'tag', defaultName: 'Docs' };
});
it('adds stories for each component with autodocs tag', async () => {
const renderToCanvas = jest.fn();
const { configure, clientApi } = start(renderToCanvas);
configure('test', () => {
clientApi
.storiesOf('Component A', { id: 'file1' } as NodeModule)
.add('Story One', jest.fn())
.add('Story Two', jest.fn());
clientApi
.storiesOf('Component B', { id: 'file2' } as NodeModule)
.addParameters({ tags: ['autodocs'] })
.add('Story Three', jest.fn());
return [componentCExports];
});
await waitForRender();
expect(mockChannel.emit.mock.calls.find((call) => call[0] === SET_INDEX)?.[1])
.toMatchInlineSnapshot(`
Object {
"entries": Object {
"component-a--story-one": Object {
"argTypes": Object {},
"args": Object {},
"componentId": "component-a",
"id": "component-a--story-one",
"importPath": "file1",
"initialArgs": Object {},
"name": "Story One",
"parameters": Object {
"__id": "component-a--story-one",
"__isArgsStory": false,
"fileName": "file1",
"renderer": "test",
},
"tags": Array [
"story",
],
"title": "Component A",
"type": "story",
},
"component-a--story-two": Object {
"argTypes": Object {},
"args": Object {},
"componentId": "component-a",
"id": "component-a--story-two",
"importPath": "file1",
"initialArgs": Object {},
"name": "Story Two",
"parameters": Object {
"__id": "component-a--story-two",
"__isArgsStory": false,
"fileName": "file1",
"renderer": "test",
},
"tags": Array [
"story",
],
"title": "Component A",
"type": "story",
},
"component-b--docs": Object {
"componentId": "component-b",
"id": "component-b--docs",
"importPath": "file2",
"name": "Docs",
"parameters": Object {
"fileName": "file2",
"renderer": "test",
},
"storiesImports": Array [],
"tags": Array [
"autodocs",
"docs",
],
"title": "Component B",
"type": "docs",
},
"component-b--story-three": Object {
"argTypes": Object {},
"args": Object {},
"componentId": "component-b",
"id": "component-b--story-three",
"importPath": "file2",
"initialArgs": Object {},
"name": "Story Three",
"parameters": Object {
"__id": "component-b--story-three",
"__isArgsStory": false,
"fileName": "file2",
"renderer": "test",
},
"tags": Array [
"autodocs",
"story",
],
"title": "Component B",
"type": "story",
},
"component-c--docs": Object {
"id": "component-c--docs",
"importPath": "exports-map-0",
"name": "Docs",
"parameters": Object {
"fileName": "exports-map-0",
"renderer": "test",
},
"storiesImports": Array [],
"tags": Array [
"component-tag",
"autodocs",
"docs",
],
"title": "Component C",
"type": "docs",
},
"component-c--story-one": Object {
"argTypes": Object {},
"args": Object {},
"id": "component-c--story-one",
"importPath": "exports-map-0",
"initialArgs": Object {},
"name": "Story One",
"parameters": Object {
"__isArgsStory": false,
"fileName": "exports-map-0",
"renderer": "test",
},
"tags": Array [
"story-tag",
"story",
],
"title": "Component C",
"type": "story",
},
"component-c--story-two": Object {
"argTypes": Object {},
"args": Object {},
"id": "component-c--story-two",
"importPath": "exports-map-0",
"initialArgs": Object {},
"name": "Story Two",
"parameters": Object {
"__isArgsStory": false,
"fileName": "exports-map-0",
"renderer": "test",
},
"tags": Array [
"component-tag",
"autodocs",
"story",
],
"title": "Component C",
"type": "story",
},
},
"v": 4,
}
`);
});
});
describe('when docsOptions.autodocs = true', () => {
beforeEach(() => {
global.DOCS_OPTIONS = { autodocs: true, defaultName: 'Docs' };
});
it('adds stories for each component with autodocs tag', async () => {
const renderToDOM = jest.fn();
const { configure, clientApi } = start(renderToDOM);
configure('test', () => {
(clientApi as any).addParameters({
docs: { renderer: () => ({ render: jest.fn((_, _2, _3, d) => d()) }) },
});
clientApi
.storiesOf('Component A', { id: 'file1' } as NodeModule)
.add('Story One', jest.fn())
.add('Story Two', jest.fn());
clientApi
.storiesOf('Component B', { id: 'file2' } as NodeModule)
.addParameters({ tags: ['autodocs'] })
.add('Story Three', jest.fn());
return [componentCExports];
});
await waitForRender();
const setIndexData = mockChannel.emit.mock.calls.find((call) => call[0] === SET_INDEX)?.[1];
expect(Object.keys(setIndexData.entries)).toMatchInlineSnapshot(`
Array [
"component-a--docs",
"component-a--story-one",
"component-a--story-two",
"component-b--docs",
"component-b--story-three",
"component-c--docs",
"component-c--story-one",
"component-c--story-two",
]
`);
});
});
});
describe('auto-title', () => {
const componentDExports = {
default: {
component: 'Component D',
},
StoryOne: jest.fn(),
};
it('loads and renders the first story correctly', async () => {
const renderToCanvas = jest.fn();
const { configure } = start(renderToCanvas);
configure('test', () => [componentDExports]);
await waitForEvents([SET_INDEX]);
expect(mockChannel.emit.mock.calls.find((call) => call[0] === SET_INDEX)?.[1])
.toMatchInlineSnapshot(`
Object {
"entries": Object {
"auto-title--story-one": Object {
"argTypes": Object {},
"args": Object {},
"id": "auto-title--story-one",
"importPath": "exports-map-0",
"initialArgs": Object {},
"name": "Story One",
"parameters": Object {
"__isArgsStory": false,
"fileName": "exports-map-0",
"renderer": "test",
},
"tags": Array [
"story",
],
"title": "auto-title",
"type": "story",
},
},
"v": 4,
}
`);
await waitForRender();
});
});
});
|
1,134 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/preview-web/PreviewWeb.integration.test.ts | /**
* @jest-environment jsdom
*/
import React from 'react';
import { global } from '@storybook/global';
import type { RenderContext } from '@storybook/types';
import { addons, mockChannel as createMockChannel } from '../addons';
import { PreviewWeb } from './PreviewWeb';
import { WebView } from './WebView';
import {
componentOneExports,
importFn,
projectAnnotations,
getProjectAnnotations,
emitter,
mockChannel,
waitForRender,
storyIndex as mockStoryIndex,
} from './PreviewWeb.mockdata';
// PreviewWeb.test mocks out all rendering
// - ie. from`renderToCanvas()` (stories) or`ReactDOM.render()` (docs) in.
// This file lets them rip.
jest.mock('@storybook/channels', () => ({
...jest.requireActual('@storybook/channels'),
createBrowserChannel: () => mockChannel,
}));
jest.mock('@storybook/client-logger');
jest.mock('./WebView');
const { document } = global;
jest.mock('@storybook/global', () => ({
global: {
...globalThis,
history: { replaceState: jest.fn() },
document: {
createElement: globalThis.document.createElement.bind(globalThis.document),
location: {
pathname: 'pathname',
search: '?id=*',
},
},
FEATURES: {
storyStoreV7: true,
},
fetch: async () => ({ status: 200, json: async () => mockStoryIndex }),
},
}));
beforeEach(() => {
document.location.search = '';
mockChannel.emit.mockClear();
emitter.removeAllListeners();
componentOneExports.default.loaders[0].mockReset().mockImplementation(async () => ({ l: 7 }));
componentOneExports.default.parameters.docs.container.mockClear();
componentOneExports.a.play.mockReset();
projectAnnotations.renderToCanvas.mockReset();
projectAnnotations.render.mockClear();
projectAnnotations.decorators[0].mockClear();
// We need to import DocsRenderer async because MDX2 is ESM-only so we inline
// this in each of the async tests below to get it working in Jest
// projectAnnotations.parameters.docs.renderer = () => new DocsRenderer() as any;
addons.setChannel(mockChannel as any);
addons.setServerChannel(createMockChannel());
jest.mocked(WebView.prototype).prepareForDocs.mockReturnValue('docs-element' as any);
jest.mocked(WebView.prototype).prepareForStory.mockReturnValue('story-element' as any);
});
describe('PreviewWeb', () => {
describe('initial render', () => {
it('renders story mode through the stack', async () => {
const { DocsRenderer } = await import('@storybook/addon-docs');
projectAnnotations.parameters.docs.renderer = () => new DocsRenderer() as any;
projectAnnotations.renderToCanvas.mockImplementationOnce(({ storyFn }: RenderContext<any>) =>
storyFn()
);
document.location.search = '?id=component-one--a';
await new PreviewWeb().initialize({ importFn, getProjectAnnotations });
await waitForRender();
expect(projectAnnotations.decorators[0]).toHaveBeenCalled();
expect(projectAnnotations.render).toHaveBeenCalled();
});
it('renders docs mode through docs page', async () => {
const { DocsRenderer } = await import('@storybook/addon-docs');
projectAnnotations.parameters.docs.renderer = () => new DocsRenderer() as any;
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = new PreviewWeb();
const docsRoot = document.createElement('div');
(
preview.view.prepareForDocs as any as jest.Mock<typeof preview.view.prepareForDocs>
).mockReturnValue(docsRoot as any);
componentOneExports.default.parameters.docs.container.mockImplementationOnce(() =>
React.createElement('div', {}, 'INSIDE')
);
await preview.initialize({ importFn, getProjectAnnotations });
await waitForRender();
expect(docsRoot.outerHTML).toMatchInlineSnapshot(`
<div>
<div>
INSIDE
</div>
</div>
`);
});
it('sends docs rendering exceptions to showException', async () => {
const { DocsRenderer } = await import('@storybook/addon-docs');
projectAnnotations.parameters.docs.renderer = () => new DocsRenderer() as any;
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = new PreviewWeb();
const docsRoot = document.createElement('div');
(
preview.view.prepareForDocs as any as jest.Mock<typeof preview.view.prepareForDocs>
).mockReturnValue(docsRoot as any);
componentOneExports.default.parameters.docs.container.mockImplementationOnce(() => {
throw new Error('Docs rendering error');
});
(
preview.view.showErrorDisplay as any as jest.Mock<typeof preview.view.showErrorDisplay>
).mockClear();
await preview.initialize({ importFn, getProjectAnnotations });
await waitForRender();
expect(preview.view.showErrorDisplay).toHaveBeenCalled();
});
});
describe('onGetGlobalMeta changed (HMR)', () => {
const newGlobalDecorator = jest.fn((s) => s());
const newGetProjectAnnotations = () => {
return {
...projectAnnotations,
args: { a: 'second' },
globals: { a: 'second' },
decorators: [newGlobalDecorator],
};
};
it('renders story mode through the updated stack', async () => {
const { DocsRenderer } = await import('@storybook/addon-docs');
projectAnnotations.parameters.docs.renderer = () => new DocsRenderer() as any;
document.location.search = '?id=component-one--a';
const preview = new PreviewWeb();
await preview.initialize({ importFn, getProjectAnnotations });
await waitForRender();
projectAnnotations.renderToCanvas.mockImplementationOnce(({ storyFn }: RenderContext<any>) =>
storyFn()
);
projectAnnotations.decorators[0].mockClear();
mockChannel.emit.mockClear();
preview.onGetProjectAnnotationsChanged({ getProjectAnnotations: newGetProjectAnnotations });
await waitForRender();
expect(projectAnnotations.decorators[0]).not.toHaveBeenCalled();
expect(newGlobalDecorator).toHaveBeenCalled();
expect(projectAnnotations.render).toHaveBeenCalled();
});
});
});
|
1,136 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/preview-web/PreviewWeb.test.ts | /**
* @jest-environment jsdom
*/
import { global } from '@storybook/global';
import merge from 'lodash/merge.js';
import {
CONFIG_ERROR,
CURRENT_STORY_WAS_SET,
DOCS_RENDERED,
FORCE_REMOUNT,
FORCE_RE_RENDER,
GLOBALS_UPDATED,
IGNORED_EXCEPTION,
PREVIEW_KEYDOWN,
RESET_STORY_ARGS,
SET_CURRENT_STORY,
SET_GLOBALS,
STORY_ARGS_UPDATED,
STORY_CHANGED,
STORY_ERRORED,
STORY_MISSING,
STORY_PREPARED,
STORY_RENDERED,
STORY_SPECIFIED,
STORY_THREW_EXCEPTION,
PLAY_FUNCTION_THREW_EXCEPTION,
STORY_UNCHANGED,
UPDATE_GLOBALS,
UPDATE_STORY_ARGS,
DOCS_PREPARED,
} from '@storybook/core-events';
import { logger } from '@storybook/client-logger';
import type { Renderer, ModuleImportFn, ProjectAnnotations } from '@storybook/types';
import { addons, mockChannel as createMockChannel } from '../addons';
import { PreviewWeb } from './PreviewWeb';
import {
componentOneExports,
componentTwoExports,
importFn,
projectAnnotations,
getProjectAnnotations,
storyIndex,
emitter,
mockChannel,
waitForEvents,
waitForRender,
waitForQuiescence,
waitForRenderPhase,
docsRenderer,
unattachedDocsExports,
teardownrenderToCanvas,
} from './PreviewWeb.mockdata';
import { WebView } from './WebView';
const { history, document } = global;
const mockStoryIndex = jest.fn(() => storyIndex);
let mockFetchResult: any;
jest.mock('@storybook/global', () => ({
global: {
...(jest.requireActual('@storybook/global') as any),
history: { replaceState: jest.fn() },
document: {
location: {
pathname: 'pathname',
search: '?id=*',
},
},
FEATURES: {
storyStoreV7: true,
// xxx
},
fetch: async () => mockFetchResult,
},
}));
jest.mock('@storybook/client-logger');
jest.mock('react-dom');
jest.mock('./WebView');
const serializeError = (error: Error) => {
const { name = 'Error', message = String(error), stack } = error;
return { name, message, stack };
};
const createGate = (): [Promise<any | undefined>, (_?: any) => void] => {
let openGate = (_?: any) => {};
const gate = new Promise<any | undefined>((resolve) => {
openGate = resolve;
});
return [gate, openGate];
};
// SET_CURRENT_STORY does some stuff in promises, then waits for
// a timer, so we need to first setImmediate (to get past the resolution), then run the timers
// Probably jest modern timers do this but they aren't working for some bizarre reason.
async function waitForSetCurrentStory() {
jest.useFakeTimers({ doNotFake: ['setTimeout'] });
await new Promise((r) => setTimeout(r, 0));
jest.runAllTimers();
}
async function createAndRenderPreview({
importFn: inputImportFn = importFn,
getProjectAnnotations: inputGetProjectAnnotations = getProjectAnnotations,
}: {
importFn?: ModuleImportFn;
getProjectAnnotations?: () => ProjectAnnotations<Renderer>;
} = {}) {
const preview = new PreviewWeb();
await preview.initialize({
importFn: inputImportFn,
getProjectAnnotations: inputGetProjectAnnotations,
});
await waitForRender();
return preview;
}
beforeEach(() => {
document.location.search = '';
mockChannel.emit.mockClear();
emitter.removeAllListeners();
componentOneExports.default.loaders[0].mockReset().mockImplementation(async () => ({ l: 7 }));
componentOneExports.a.play.mockReset();
teardownrenderToCanvas.mockReset();
projectAnnotations.renderToCanvas.mockReset().mockReturnValue(teardownrenderToCanvas);
projectAnnotations.render.mockClear();
projectAnnotations.decorators[0].mockClear();
docsRenderer.render.mockClear();
(logger.warn as jest.Mock<typeof logger.warn>).mockClear();
mockStoryIndex.mockReset().mockReturnValue(storyIndex);
addons.setChannel(mockChannel as any);
addons.setServerChannel(createMockChannel());
mockFetchResult = { status: 200, json: mockStoryIndex, text: () => 'error text' };
jest.mocked(WebView.prototype).prepareForDocs.mockReturnValue('docs-element' as any);
jest.mocked(WebView.prototype).prepareForStory.mockReturnValue('story-element' as any);
});
describe('PreviewWeb', () => {
describe('initialize', () => {
it('shows an error if getProjectAnnotations throws', async () => {
const err = new Error('meta error');
const preview = new PreviewWeb();
await expect(
preview.initialize({
importFn,
getProjectAnnotations: () => {
throw err;
},
})
).rejects.toThrow(err);
expect(preview.view.showErrorDisplay).toHaveBeenCalled();
expect(mockChannel.emit).toHaveBeenCalledWith(CONFIG_ERROR, err);
});
it('shows an error if the stories.json endpoint 500s', async () => {
const err = new Error('sort error');
mockFetchResult = { status: 500, text: async () => err.toString() };
const preview = new PreviewWeb();
await expect(preview.initialize({ importFn, getProjectAnnotations })).rejects.toThrow(
'sort error'
);
expect(preview.view.showErrorDisplay).toHaveBeenCalled();
expect(mockChannel.emit).toHaveBeenCalledWith(CONFIG_ERROR, expect.any(Error));
});
it('sets globals from the URL', async () => {
document.location.search = '?id=*&globals=a:c';
const preview = await createAndRenderPreview();
expect(preview.storyStore.globals!.get()).toEqual({ a: 'c' });
});
it('emits the SET_GLOBALS event', async () => {
await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(SET_GLOBALS, {
globals: { a: 'b' },
globalTypes: {},
});
});
it('SET_GLOBALS sets globals and types even when undefined', async () => {
await createAndRenderPreview({
getProjectAnnotations: () => ({ renderToCanvas: jest.fn() }),
});
expect(mockChannel.emit).toHaveBeenCalledWith(SET_GLOBALS, {
globals: {},
globalTypes: {},
});
});
it('emits the SET_GLOBALS event from the URL', async () => {
document.location.search = '?id=*&globals=a:c';
await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(SET_GLOBALS, {
globals: { a: 'c' },
globalTypes: {},
});
});
it('sets args from the URL', async () => {
document.location.search = '?id=component-one--a&args=foo:url';
const preview = await createAndRenderPreview();
expect(preview.storyStore.args.get('component-one--a')).toEqual({
foo: 'url',
one: 1,
});
});
it('updates args from the URL', async () => {
document.location.search = '?id=component-one--a&args=foo:url';
await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_ARGS_UPDATED, {
storyId: 'component-one--a',
args: { foo: 'url', one: 1 },
});
});
it('allows async getProjectAnnotations', async () => {
const preview = new PreviewWeb();
await preview.initialize({
importFn,
getProjectAnnotations: async () => {
return getProjectAnnotations();
},
});
expect(preview.storyStore.globals!.get()).toEqual({ a: 'b' });
});
});
describe('initial selection', () => {
it('selects the story specified in the URL', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
expect(preview.selectionStore.selection).toEqual({
storyId: 'component-one--a',
viewMode: 'story',
});
expect(history.replaceState).toHaveBeenCalledWith(
{},
'',
'pathname?id=component-one--a&viewMode=story'
);
});
it('emits the STORY_SPECIFIED event', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_SPECIFIED, {
storyId: 'component-one--a',
viewMode: 'story',
});
});
it('emits the CURRENT_STORY_WAS_SET event', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(CURRENT_STORY_WAS_SET, {
storyId: 'component-one--a',
viewMode: 'story',
});
});
describe('when the first entry is a docs entry', () => {
it('emits the STORY_SPECIFIED event with viewMode=docs', async () => {
document.location.search = '?id=*';
await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_SPECIFIED, {
storyId: 'component-one--docs',
viewMode: 'docs',
});
});
});
describe('if the story specified does not exist', () => {
it('renders a loading error', async () => {
document.location.search = '?id=random';
const preview = await createAndRenderPreview();
expect(preview.view.showErrorDisplay).toHaveBeenCalled();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_MISSING, 'random');
});
it('tries again with a specifier if CSF file changes', async () => {
document.location.search = '?id=component-one--missing';
const preview = await createAndRenderPreview();
expect(preview.view.showErrorDisplay).toHaveBeenCalled();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_MISSING, 'component-one--missing');
mockChannel.emit.mockClear();
const newComponentOneExports = merge({}, componentOneExports, {
d: { args: { foo: 'd' }, play: jest.fn() },
});
const newImportFn = jest.fn(async (path) => {
return path === './src/ComponentOne.stories.js'
? newComponentOneExports
: componentTwoExports;
});
preview.onStoriesChanged({
importFn: newImportFn,
storyIndex: {
v: 4,
entries: {
...storyIndex.entries,
'component-one--missing': {
type: 'story',
id: 'component-one--missing',
title: 'Component One',
name: 'D',
importPath: './src/ComponentOne.stories.js',
},
},
},
});
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_SPECIFIED, {
storyId: 'component-one--missing',
viewMode: 'story',
});
});
describe('after selection changes', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
it('DOES NOT try again if CSF file changes', async () => {
document.location.search = '?id=component-one--missing';
const preview = await createAndRenderPreview();
expect(preview.view.showErrorDisplay).toHaveBeenCalled();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_MISSING, 'component-one--missing');
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
const newComponentOneExports = merge({}, componentOneExports, {
d: { args: { foo: 'd' }, play: jest.fn() },
});
const newImportFn = jest.fn(async (path) => {
return path === './src/ComponentOne.stories.js'
? newComponentOneExports
: componentTwoExports;
});
preview.onStoriesChanged({
importFn: newImportFn,
storyIndex: {
v: 4,
entries: {
...storyIndex.entries,
'component-one--missing': {
type: 'story',
id: 'component-one--missing',
title: 'Component One',
name: 'D',
importPath: './src/ComponentOne.stories.js',
},
},
},
});
expect(mockChannel.emit).not.toHaveBeenCalledWith(STORY_SPECIFIED, {
storyId: 'component-one--missing',
viewMode: 'story',
});
});
});
});
it('renders missing if no selection', async () => {
const preview = await createAndRenderPreview();
expect(preview.view.showNoPreview).toHaveBeenCalled();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_MISSING);
});
describe('story entries', () => {
it('calls view.prepareForStory', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
expect(preview.view.prepareForStory).toHaveBeenCalledWith(
expect.objectContaining({
id: 'component-one--a',
})
);
});
it('emits STORY_PREPARED', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_PREPARED, {
id: 'component-one--a',
parameters: {
__isArgsStory: false,
docs: expect.any(Object),
fileName: './src/ComponentOne.stories.js',
},
initialArgs: { foo: 'a', one: 1 },
argTypes: {
foo: { name: 'foo', type: { name: 'string' } },
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped-1' } },
},
args: { foo: 'a', one: 1 },
});
});
it('applies loaders with story context', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
expect(componentOneExports.default.loaders[0]).toHaveBeenCalledWith(
expect.objectContaining({
id: 'component-one--a',
parameters: {
__isArgsStory: false,
docs: expect.any(Object),
fileName: './src/ComponentOne.stories.js',
},
initialArgs: { foo: 'a', one: 1 },
argTypes: {
foo: { name: 'foo', type: { name: 'string' } },
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped-1' } },
},
args: { foo: 'a', one: 'mapped-1' },
})
);
});
it('passes loaded context to renderToCanvas', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: true,
storyContext: expect.objectContaining({
id: 'component-one--a',
parameters: {
__isArgsStory: false,
docs: expect.any(Object),
fileName: './src/ComponentOne.stories.js',
},
globals: { a: 'b' },
initialArgs: { foo: 'a', one: 1 },
argTypes: {
foo: { name: 'foo', type: { name: 'string' } },
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped-1' } },
},
args: { foo: 'a', one: 'mapped-1' },
loaded: { l: 7 },
}),
}),
'story-element'
);
});
it('renders exception if a loader throws', async () => {
const error = new Error('error');
componentOneExports.default.loaders[0].mockImplementationOnce(() => {
throw error;
});
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_THREW_EXCEPTION, serializeError(error));
expect(preview.view.showErrorDisplay).toHaveBeenCalledWith(error);
});
it('renders exception if renderToCanvas throws', async () => {
const error = new Error('error');
projectAnnotations.renderToCanvas.mockImplementation(() => {
throw error;
});
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_THREW_EXCEPTION, serializeError(error));
expect(preview.view.showErrorDisplay).toHaveBeenCalledWith(error);
});
it('renders helpful message if renderToCanvas is undefined', async () => {
document.location.search = '?id=component-one--a';
getProjectAnnotations.mockReturnValueOnce({
...projectAnnotations,
renderToCanvas: undefined,
});
const preview = new PreviewWeb();
await expect(preview.initialize({ importFn, getProjectAnnotations })).rejects.toThrow();
expect(preview.view.showErrorDisplay).toHaveBeenCalled();
expect((preview.view.showErrorDisplay as jest.Mock).mock.calls[0][0])
.toMatchInlineSnapshot(`
[Error: Expected your framework's preset to export a \`renderToCanvas\` field.
Perhaps it needs to be upgraded for Storybook 6.4?
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mainjs-framework-field]
`);
});
describe('when `throwPlayFunctionExceptions` is set', () => {
it('emits but does not render exception if the play function throws', async () => {
const error = new Error('error');
componentOneExports.a.play.mockImplementationOnce(() => {
throw error;
});
getProjectAnnotations.mockReturnValueOnce({
...projectAnnotations,
parameters: {
...projectAnnotations.parameters,
throwPlayFunctionExceptions: false,
},
});
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(
PLAY_FUNCTION_THREW_EXCEPTION,
serializeError(error)
);
expect(preview.view.showErrorDisplay).not.toHaveBeenCalled();
expect(mockChannel.emit).not.toHaveBeenCalledWith(
STORY_THREW_EXCEPTION,
serializeError(error)
);
});
});
describe('when `throwPlayFunctionExceptions` is unset', () => {
it('emits AND renders exception if the play function throws', async () => {
const error = new Error('error');
componentOneExports.a.play.mockImplementationOnce(() => {
throw error;
});
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(
PLAY_FUNCTION_THREW_EXCEPTION,
serializeError(error)
);
expect(preview.view.showErrorDisplay).toHaveBeenCalled();
expect(mockChannel.emit).toHaveBeenCalledWith(
STORY_THREW_EXCEPTION,
serializeError(error)
);
});
});
it('renders exception if the story calls showException', async () => {
const error = new Error('error');
projectAnnotations.renderToCanvas.mockImplementation((context) =>
context.showException(error)
);
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_THREW_EXCEPTION, serializeError(error));
expect(preview.view.showErrorDisplay).toHaveBeenCalledWith(error);
});
it('renders error if the story calls showError', async () => {
const error = { title: 'title', description: 'description' };
projectAnnotations.renderToCanvas.mockImplementation((context) => context.showError(error));
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_ERRORED, error);
expect(preview.view.showErrorDisplay).toHaveBeenCalledWith({
message: error.title,
stack: error.description,
});
});
it('executes playFunction', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
expect(componentOneExports.a.play).toHaveBeenCalled();
});
it('emits STORY_RENDERED', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-one--a');
});
it('does not show error display if the render function throws IGNORED_EXCEPTION', async () => {
document.location.search = '?id=component-one--a';
projectAnnotations.renderToCanvas.mockImplementation(() => {
throw IGNORED_EXCEPTION;
});
const preview = new PreviewWeb();
await preview.initialize({ importFn, getProjectAnnotations });
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(
STORY_THREW_EXCEPTION,
serializeError(IGNORED_EXCEPTION)
);
expect(preview.view.showErrorDisplay).not.toHaveBeenCalled();
});
});
describe('CSF docs entries', () => {
it('emits DOCS_PREPARED', async () => {
document.location.search = '?id=component-one--docs';
await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(DOCS_PREPARED, {
id: 'component-one--docs',
parameters: {
docs: expect.any(Object),
fileName: './src/ComponentOne.stories.js',
},
});
});
it('always renders in docs viewMode', async () => {
document.location.search = '?id=component-one--docs';
await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(DOCS_RENDERED, 'component-one--docs');
});
it('calls view.prepareForDocs', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = await createAndRenderPreview();
expect(preview.view.prepareForDocs).toHaveBeenCalled();
});
it('renders with docs parameters from the first story', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
await createAndRenderPreview();
expect(docsRenderer.render).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({
page: componentOneExports.default.parameters.docs.page,
renderer: projectAnnotations.parameters.docs.renderer,
}),
'docs-element'
);
});
it('loads imports of the docs entry', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
await createAndRenderPreview();
expect(importFn).toHaveBeenCalledWith('./src/ExtraComponentOne.stories.js');
});
it('renders with componentStories loaded from the attached CSF file', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
await createAndRenderPreview();
const context = docsRenderer.render.mock.calls[0][0];
expect(context.componentStories().map((s: any) => s.id)).toEqual([
'component-one--a',
'component-one--b',
'component-one--e',
]);
});
it('emits DOCS_RENDERED', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(DOCS_RENDERED, 'component-one--docs');
});
});
describe('MDX docs entries', () => {
it('always renders in docs viewMode', async () => {
document.location.search = '?id=introduction--docs';
await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(DOCS_RENDERED, 'introduction--docs');
});
it('emits DOCS_PREPARED', async () => {
document.location.search = '?id=introduction--docs';
await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(DOCS_PREPARED, {
id: 'introduction--docs',
parameters: {
docs: expect.any(Object),
},
});
});
describe('attached', () => {
it('emits DOCS_PREPARED with component parameters', async () => {
document.location.search = '?id=component-one--attached-docs';
await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(DOCS_PREPARED, {
id: 'component-one--attached-docs',
parameters: {
docs: expect.any(Object),
fileName: './src/ComponentOne.stories.js',
},
});
});
});
it('calls view.prepareForDocs', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = await createAndRenderPreview();
expect(preview.view.prepareForDocs).toHaveBeenCalled();
});
it('renders with the generated docs parameters', async () => {
document.location.search = '?id=introduction--docs&viewMode=docs';
await createAndRenderPreview();
expect(docsRenderer.render).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({
page: unattachedDocsExports.default,
renderer: projectAnnotations.parameters.docs.renderer,
}),
'docs-element'
);
});
it('loads imports of the docs entry', async () => {
document.location.search = '?id=introduction--docs';
await createAndRenderPreview();
expect(importFn).toHaveBeenCalledWith('./src/ComponentTwo.stories.js');
});
it('emits DOCS_RENDERED', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
await createAndRenderPreview();
expect(mockChannel.emit).toHaveBeenCalledWith(DOCS_RENDERED, 'component-one--docs');
});
});
});
describe('onUpdateGlobals', () => {
it('emits GLOBALS_UPDATED', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
emitter.emit(UPDATE_GLOBALS, { globals: { a: 'c' } });
await waitForEvents([GLOBALS_UPDATED]);
expect(mockChannel.emit).toHaveBeenCalledWith(GLOBALS_UPDATED, {
globals: { a: 'c' },
initialGlobals: { a: 'b' },
});
});
it('doet not allow new globals on the store', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
emitter.emit(UPDATE_GLOBALS, { globals: { foo: 'bar' } });
expect(preview.storyStore.globals!.get()).toEqual({ a: 'b' });
});
it('passes globals in context to renderToCanvas', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
projectAnnotations.renderToCanvas.mockClear();
emitter.emit(UPDATE_GLOBALS, { globals: { a: 'd' } });
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: false,
storyContext: expect.objectContaining({
globals: { a: 'd' },
}),
}),
'story-element'
);
});
it('emits STORY_RENDERED', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(UPDATE_GLOBALS, { globals: { a: 'c' } });
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-one--a');
});
describe('in docs mode', () => {
it('re-renders the docs container', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
await createAndRenderPreview();
mockChannel.emit.mockClear();
docsRenderer.render.mockClear();
emitter.emit(UPDATE_GLOBALS, { globals: { a: 'd' } });
await waitForEvents([GLOBALS_UPDATED]);
expect(docsRenderer.render).toHaveBeenCalled();
});
});
});
describe('onUpdateArgs', () => {
it('emits STORY_ARGS_UPDATED', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { new: 'arg', one: 1 },
});
await waitForEvents([STORY_ARGS_UPDATED]);
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_ARGS_UPDATED, {
storyId: 'component-one--a',
args: { foo: 'a', new: 'arg', one: 1 },
});
});
it('sets new args on the store', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { new: 'arg' },
});
expect(preview.storyStore.args.get('component-one--a')).toEqual({
foo: 'a',
new: 'arg',
one: 1,
});
});
it('passes new args in context to renderToCanvas', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
projectAnnotations.renderToCanvas.mockClear();
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { new: 'arg' },
});
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: false,
storyContext: expect.objectContaining({
initialArgs: { foo: 'a', one: 1 },
args: { foo: 'a', new: 'arg', one: 'mapped-1' },
}),
}),
'story-element'
);
});
it('emits STORY_RENDERED', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { new: 'arg' },
});
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-one--a');
});
describe('while story is still rendering', () => {
it('runs loaders again', async () => {
const [gate, openGate] = createGate();
document.location.search = '?id=component-one--a';
componentOneExports.default.loaders[0].mockImplementationOnce(async () => gate);
await new PreviewWeb().initialize({ importFn, getProjectAnnotations });
await waitForRenderPhase('loading');
expect(componentOneExports.default.loaders[0]).toHaveBeenCalledWith(
expect.objectContaining({
args: { foo: 'a', one: 'mapped-1' },
})
);
componentOneExports.default.loaders[0].mockClear();
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { new: 'arg' },
});
await waitForRender();
expect(componentOneExports.default.loaders[0]).toHaveBeenCalledWith(
expect.objectContaining({
args: { foo: 'a', new: 'arg', one: 'mapped-1' },
})
);
// Story gets rendered with updated args
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledTimes(1);
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: true, // Wasn't yet rendered so we need to force remount
storyContext: expect.objectContaining({
loaded: { l: 7 }, // This is the value returned by the *second* loader call
args: { foo: 'a', new: 'arg', one: 'mapped-1' },
}),
}),
'story-element'
);
// Now let the first loader call resolve
mockChannel.emit.mockClear();
projectAnnotations.renderToCanvas.mockClear();
openGate({ l: 8 });
await waitForRender();
// Now the first call comes through, but picks up the new args
// Note this isn't a particularly realistic case (the second loader being quicker than the first)
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledTimes(1);
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
storyContext: expect.objectContaining({
loaded: { l: 8 },
args: { foo: 'a', new: 'arg', one: 'mapped-1' },
}),
}),
'story-element'
);
});
it('renders a second time if renderToCanvas is running', async () => {
const [gate, openGate] = createGate();
document.location.search = '?id=component-one--a';
projectAnnotations.renderToCanvas.mockImplementation(async () => gate);
await new PreviewWeb().initialize({ importFn, getProjectAnnotations });
await waitForRenderPhase('rendering');
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { new: 'arg' },
});
// Now let the renderToCanvas call resolve
openGate();
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledTimes(2);
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: true,
storyContext: expect.objectContaining({
loaded: { l: 7 },
args: { foo: 'a', one: 'mapped-1' },
}),
}),
'story-element'
);
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: false,
storyContext: expect.objectContaining({
loaded: { l: 7 },
args: { foo: 'a', new: 'arg', one: 'mapped-1' },
}),
}),
'story-element'
);
});
it('works if it is called directly from inside non async renderToCanvas', async () => {
document.location.search = '?id=component-one--a';
projectAnnotations.renderToCanvas.mockImplementation(() => {
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { new: 'arg' },
});
});
await createAndRenderPreview();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledTimes(2);
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: true,
storyContext: expect.objectContaining({
loaded: { l: 7 },
args: { foo: 'a', one: 'mapped-1' },
}),
}),
'story-element'
);
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: false,
storyContext: expect.objectContaining({
loaded: { l: 7 },
args: { foo: 'a', new: 'arg', one: 'mapped-1' },
}),
}),
'story-element'
);
});
it('calls renderToCanvas again if play function is running', async () => {
const [gate, openGate] = createGate();
componentOneExports.a.play.mockImplementationOnce(async () => gate);
const renderToCanvasCalled = new Promise((resolve) => {
projectAnnotations.renderToCanvas.mockImplementation(() => {
resolve(null);
});
});
document.location.search = '?id=component-one--a';
await new PreviewWeb().initialize({ importFn, getProjectAnnotations });
await waitForRenderPhase('playing');
await renderToCanvasCalled;
// Story gets rendered with original args
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: true,
storyContext: expect.objectContaining({
loaded: { l: 7 },
args: { foo: 'a', one: 'mapped-1' },
}),
}),
'story-element'
);
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { new: 'arg' },
});
// The second call should emit STORY_RENDERED
await waitForRender();
// Story gets rendered with updated args
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: false,
storyContext: expect.objectContaining({
loaded: { l: 7 },
args: { foo: 'a', new: 'arg', one: 'mapped-1' },
}),
}),
'story-element'
);
// Now let the playFunction call resolve
openGate();
});
});
describe('in docs mode', () => {
it('does not re-render the docs container', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
await createAndRenderPreview();
docsRenderer.render.mockClear();
mockChannel.emit.mockClear();
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { new: 'arg' },
});
await waitForEvents([STORY_ARGS_UPDATED]);
expect(docsRenderer.render).not.toHaveBeenCalled();
});
describe('when renderStoryToElement was called', () => {
const callbacks = { showMain: jest.fn(), showError: jest.fn(), showException: jest.fn() };
it('re-renders the story', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = await createAndRenderPreview();
await waitForRender();
mockChannel.emit.mockClear();
const story = await preview.storyStore.loadStory({ storyId: 'component-one--a' });
preview.renderStoryToElement(story, 'story-element' as any, callbacks, {});
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
storyContext: expect.objectContaining({
args: { foo: 'a', one: 'mapped-1' },
}),
}),
'story-element'
);
docsRenderer.render.mockClear();
mockChannel.emit.mockClear();
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { new: 'arg' },
});
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
storyContext: expect.objectContaining({
args: { foo: 'a', new: 'arg', one: 'mapped-1' },
}),
}),
'story-element'
);
});
it('does not re-render the story when forceInitialArgs=true', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = await createAndRenderPreview();
await waitForRender();
mockChannel.emit.mockClear();
const story = await preview.storyStore.loadStory({ storyId: 'component-one--a' });
preview.renderStoryToElement(story, 'story-element' as any, callbacks, {
forceInitialArgs: true,
});
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
storyContext: expect.objectContaining({
args: { foo: 'a', one: 'mapped-1' },
}),
}),
'story-element'
);
docsRenderer.render.mockClear();
mockChannel.emit.mockClear();
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { new: 'arg' },
});
await waitForEvents([STORY_ARGS_UPDATED]);
// We don't re-render the story
await expect(waitForRender).rejects.toThrow();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledTimes(1);
});
});
});
});
describe('onPreloadStories', () => {
it('loads stories', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = await createAndRenderPreview();
await waitForRender();
// @ts-expect-error (jest mock)
importFn.mockClear();
await preview.onPreloadStories({ ids: ['component-two--c'] });
expect(importFn).toHaveBeenCalledWith('./src/ComponentTwo.stories.js');
});
it('loads legacy docs entries', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = await createAndRenderPreview();
await waitForRender();
// @ts-expect-error (jest mock)
importFn.mockClear();
await preview.onPreloadStories({ ids: ['component-one--docs'] });
expect(importFn).toHaveBeenCalledWith('./src/ComponentOne.stories.js');
});
it('loads modern docs entries', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = await createAndRenderPreview();
await waitForRender();
// @ts-expect-error (jest mock)
importFn.mockClear();
await preview.onPreloadStories({ ids: ['introduction--docs'] });
expect(importFn).toHaveBeenCalledWith('./src/Introduction.mdx');
});
it('loads imports of modern docs entries', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = await createAndRenderPreview();
await waitForRender();
// @ts-expect-error (jest mock)
importFn.mockClear();
await preview.onPreloadStories({ ids: ['introduction--docs'] });
expect(importFn).toHaveBeenCalledWith('./src/ComponentTwo.stories.js');
});
});
describe('onResetArgs', () => {
it('emits STORY_ARGS_UPDATED', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { foo: 'new' },
});
await waitForEvents([STORY_ARGS_UPDATED]);
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_ARGS_UPDATED, {
storyId: 'component-one--a',
args: { foo: 'new', one: 1 },
});
mockChannel.emit.mockClear();
emitter.emit(RESET_STORY_ARGS, {
storyId: 'component-one--a',
argNames: ['foo'],
});
await waitForEvents([STORY_ARGS_UPDATED]);
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_ARGS_UPDATED, {
storyId: 'component-one--a',
args: { foo: 'a', one: 1 },
});
});
it('resets a single arg', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
const onUpdateArgsSpy = jest.spyOn(preview, 'onUpdateArgs');
mockChannel.emit.mockClear();
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { foo: 'new', new: 'value' },
});
await waitForEvents([STORY_ARGS_UPDATED]);
mockChannel.emit.mockClear();
emitter.emit(RESET_STORY_ARGS, {
storyId: 'component-one--a',
argNames: ['foo'],
});
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: false,
storyContext: expect.objectContaining({
initialArgs: { foo: 'a', one: 1 },
args: { foo: 'a', new: 'value', one: 'mapped-1' },
}),
}),
'story-element'
);
await waitForEvents([STORY_ARGS_UPDATED]);
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_ARGS_UPDATED, {
storyId: 'component-one--a',
args: { foo: 'a', new: 'value', one: 1 },
});
expect(onUpdateArgsSpy).toHaveBeenCalledWith({
storyId: 'component-one--a',
updatedArgs: { foo: 'a' },
});
});
it('resets all args after one is updated', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
const onUpdateArgsSpy = jest.spyOn(preview, 'onUpdateArgs');
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { foo: 'new' },
});
await waitForEvents([STORY_ARGS_UPDATED]);
mockChannel.emit.mockClear();
emitter.emit(RESET_STORY_ARGS, {
storyId: 'component-one--a',
});
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: false,
storyContext: expect.objectContaining({
initialArgs: { foo: 'a', one: 1 },
args: { foo: 'a', one: 'mapped-1' },
}),
}),
'story-element'
);
await waitForEvents([STORY_ARGS_UPDATED]);
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_ARGS_UPDATED, {
storyId: 'component-one--a',
args: { foo: 'a', one: 1 },
});
expect(onUpdateArgsSpy).toHaveBeenCalledWith({
storyId: 'component-one--a',
updatedArgs: { foo: 'a', one: 1 },
});
});
it('resets all args', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
const onUpdateArgsSpy = jest.spyOn(preview, 'onUpdateArgs');
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { foo: 'new', new: 'value' },
});
await waitForEvents([STORY_ARGS_UPDATED]);
mockChannel.emit.mockClear();
emitter.emit(RESET_STORY_ARGS, {
storyId: 'component-one--a',
});
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: false,
storyContext: expect.objectContaining({
initialArgs: { foo: 'a', one: 1 },
args: { foo: 'a', one: 'mapped-1' },
}),
}),
'story-element'
);
await waitForEvents([STORY_ARGS_UPDATED]);
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_ARGS_UPDATED, {
storyId: 'component-one--a',
args: { foo: 'a', one: 1 },
});
expect(onUpdateArgsSpy).toHaveBeenCalledWith({
storyId: 'component-one--a',
updatedArgs: { foo: 'a', new: undefined, one: 1 },
});
});
it('resets all args when one arg is undefined', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
const onUpdateArgsSpy = jest.spyOn(preview, 'onUpdateArgs');
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { foo: undefined },
});
await waitForEvents([STORY_ARGS_UPDATED]);
mockChannel.emit.mockClear();
emitter.emit(RESET_STORY_ARGS, {
storyId: 'component-one--a',
});
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: false,
storyContext: expect.objectContaining({
initialArgs: { foo: 'a', one: 1 },
args: { foo: 'a', one: 'mapped-1' },
}),
}),
'story-element'
);
await waitForEvents([STORY_ARGS_UPDATED]);
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_ARGS_UPDATED, {
storyId: 'component-one--a',
args: { foo: 'a', one: 1 },
});
expect(onUpdateArgsSpy).toHaveBeenCalledWith({
storyId: 'component-one--a',
updatedArgs: { foo: 'a', one: 1 },
});
});
});
describe('on FORCE_RE_RENDER', () => {
it('rerenders the story with the same args', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
projectAnnotations.renderToCanvas.mockClear();
emitter.emit(FORCE_RE_RENDER);
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({ forceRemount: false }),
'story-element'
);
});
});
describe('on FORCE_REMOUNT', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
it('remounts the story with the same args', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
projectAnnotations.renderToCanvas.mockClear();
emitter.emit(FORCE_REMOUNT, { storyId: 'component-one--a' });
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({ forceRemount: true }),
'story-element'
);
});
it('aborts render function for initial story', async () => {
const [gate, openGate] = createGate();
document.location.search = '?id=component-one--a';
projectAnnotations.renderToCanvas.mockImplementation(async () => gate);
await new PreviewWeb().initialize({ importFn, getProjectAnnotations });
await waitForRenderPhase('rendering');
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: true,
storyContext: expect.objectContaining({
id: 'component-one--a',
loaded: { l: 7 },
}),
}),
'story-element'
);
mockChannel.emit.mockClear();
emitter.emit(FORCE_REMOUNT, { storyId: 'component-one--a' });
await waitForSetCurrentStory();
// Now let the renderToCanvas call resolve
openGate();
await waitForRenderPhase('aborted');
await waitForSetCurrentStory();
await waitForRenderPhase('rendering');
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledTimes(2);
await waitForRenderPhase('playing');
expect(componentOneExports.a.play).toHaveBeenCalledTimes(1);
await waitForRenderPhase('completed');
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-one--a');
await waitForQuiescence();
});
});
describe('onSetCurrentStory', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
it('updates URL', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
expect(history.replaceState).toHaveBeenCalledWith(
{},
'',
'pathname?id=component-one--b&viewMode=story'
);
});
it('emits CURRENT_STORY_WAS_SET', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
expect(mockChannel.emit).toHaveBeenCalledWith(CURRENT_STORY_WAS_SET, {
storyId: 'component-one--b',
viewMode: 'story',
});
});
it('renders loading error if the story specified does not exist', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'random',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForEvents([STORY_MISSING]);
expect(preview.view.showErrorDisplay).toHaveBeenCalled();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_MISSING, 'random');
});
describe('if called before the preview is initialized', () => {
it('works when there was no selection specifier', async () => {
document.location.search = '';
// We intentionally are *not* awaiting here
new PreviewWeb().initialize({ importFn, getProjectAnnotations });
emitter.emit(SET_CURRENT_STORY, { storyId: 'component-one--b', viewMode: 'story' });
await waitForEvents([STORY_RENDERED]);
// Check we don't render the default "story missing" UI / emit the default message
expect(mockChannel.emit).not.toHaveBeenCalledWith(STORY_MISSING);
// We of course should emit for the selected story
expect(mockChannel.emit).toHaveBeenCalledWith(CURRENT_STORY_WAS_SET, {
storyId: 'component-one--b',
viewMode: 'story',
});
expect(history.replaceState).toHaveBeenCalledWith(
{},
'',
'pathname?id=component-one--b&viewMode=story'
);
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-one--b');
});
it('works when there was a selection specifier', async () => {
document.location.search = '?id=component-one--a';
const initialized = new PreviewWeb().initialize({
importFn,
getProjectAnnotations,
});
emitter.emit(SET_CURRENT_STORY, { storyId: 'component-one--b', viewMode: 'story' });
await initialized;
await waitForEvents([STORY_RENDERED]);
// If we emitted CURRENT_STORY_WAS_SET for the original selection, the manager might
// get confused, so check that we don't
expect(mockChannel.emit).not.toHaveBeenCalledWith(CURRENT_STORY_WAS_SET, {
storyId: 'component-one--a',
viewMode: 'story',
});
// Double check this doesn't happen either
expect(mockChannel.emit).not.toHaveBeenCalledWith(STORY_MISSING);
expect(history.replaceState).toHaveBeenCalledWith(
{},
'',
'pathname?id=component-one--b&viewMode=story'
);
expect(mockChannel.emit).toHaveBeenCalledWith(CURRENT_STORY_WAS_SET, {
storyId: 'component-one--b',
viewMode: 'story',
});
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-one--b');
});
});
describe('if called on a storybook without selection', () => {
it('sets viewMode to story by default', async () => {
await createAndRenderPreview();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
});
await waitForSetCurrentStory();
expect(history.replaceState).toHaveBeenCalledWith(
{},
'',
'pathname?id=component-one--b&viewMode=story'
);
});
});
describe('if the selection is unchanged', () => {
it('emits STORY_UNCHANGED', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForEvents([STORY_UNCHANGED]);
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_UNCHANGED, 'component-one--a');
});
it('does NOT call renderToCanvas', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
projectAnnotations.renderToCanvas.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
// The renderToCanvas would have been async so we need to wait a tick.
await waitForQuiescence();
expect(projectAnnotations.renderToCanvas).not.toHaveBeenCalled();
});
it('does NOT call renderToCanvass teardown', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
projectAnnotations.renderToCanvas.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
expect(teardownrenderToCanvas).not.toHaveBeenCalled();
});
describe('while preparing', () => {
// For https://github.com/storybookjs/storybook/issues/17214
it('does NOT render a second time in story mode', async () => {
document.location.search = '?id=component-one--a';
const [gate, openGate] = createGate();
const [importedGate, openImportedGate] = createGate();
importFn
// @ts-expect-error (jest mock)
.mockImplementationOnce(async (...args) => {
await gate;
// @ts-expect-error (jest mock)
return importFn(...args);
})
// @ts-expect-error (jest mock)
.mockImplementationOnce(async (...args) => {
// The second time we `import()` we open the "imported" gate
openImportedGate();
await gate;
// @ts-expect-error (jest mock)
return importFn(...args);
});
const preview = new PreviewWeb();
// We can't wait for the initialize function, as it waits for `renderSelection()`
// which prepares, but it does emit `CURRENT_STORY_WAS_SET` right before that
preview.initialize({ importFn, getProjectAnnotations });
await waitForEvents([CURRENT_STORY_WAS_SET]);
mockChannel.emit.mockClear();
projectAnnotations.renderToCanvas.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await importedGate;
// We are blocking import so this won't render yet
expect(projectAnnotations.renderToCanvas).not.toHaveBeenCalled();
mockChannel.emit.mockClear();
openGate();
await waitForRender();
// We should only render *once*
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledTimes(1);
// We should not show an error either
expect(preview.view.showErrorDisplay).not.toHaveBeenCalled();
});
// For https://github.com/storybookjs/storybook/issues/19015
it('does NOT render a second time in template docs mode', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
const [gate, openGate] = createGate();
const [importedGate, openImportedGate] = createGate();
importFn
// @ts-expect-error (jest mock)
.mockImplementationOnce(async (...args) => {
await gate;
// @ts-expect-error (jest mock)
return importFn(...args);
})
// @ts-expect-error (jest mock)
.mockImplementationOnce(async (...args) => {
// The second time we `import()` we open the "imported" gate
openImportedGate();
await gate;
// @ts-expect-error (jest mock)
return importFn(...args);
});
const preview = new PreviewWeb();
// We can't wait for the initialize function, as it waits for `renderSelection()`
// which prepares, but it does emit `CURRENT_STORY_WAS_SET` right before that
preview.initialize({ importFn, getProjectAnnotations });
await waitForEvents([CURRENT_STORY_WAS_SET]);
mockChannel.emit.mockClear();
projectAnnotations.renderToCanvas.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--docs',
viewMode: 'docs',
});
await importedGate;
// We are blocking import so this won't render yet
expect(docsRenderer.render).not.toHaveBeenCalled();
mockChannel.emit.mockClear();
openGate();
await waitForRender();
// We should only render *once*
expect(docsRenderer.render).toHaveBeenCalledTimes(1);
// We should not show an error either
expect(preview.view.showErrorDisplay).not.toHaveBeenCalled();
});
it('does NOT render a second time in mdx docs mode', async () => {
document.location.search = '?id=introduction--docs&viewMode=docs';
const [gate, openGate] = createGate();
const [importedGate, openImportedGate] = createGate();
importFn
// @ts-expect-error (jest mock)
.mockImplementationOnce(async (...args) => {
await gate;
// @ts-expect-error (jest mock)
return importFn(...args);
})
// @ts-expect-error (jest mock)
.mockImplementationOnce(async (...args) => {
// The second time we `import()` we open the "imported" gate
openImportedGate();
await gate;
// @ts-expect-error (jest mock)
return importFn(...args);
});
const preview = new PreviewWeb();
// We can't wait for the initialize function, as it waits for `renderSelection()`
// which prepares, but it does emit `CURRENT_STORY_WAS_SET` right before that
preview.initialize({ importFn, getProjectAnnotations });
await waitForEvents([CURRENT_STORY_WAS_SET]);
mockChannel.emit.mockClear();
projectAnnotations.renderToCanvas.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'introduction--docs',
viewMode: 'docs',
});
await importedGate;
// We are blocking import so this won't render yet
expect(docsRenderer.render).not.toHaveBeenCalled();
mockChannel.emit.mockClear();
openGate();
await waitForRender();
// We should only render *once*
expect(docsRenderer.render).toHaveBeenCalledTimes(1);
// We should not show an error either
expect(preview.view.showErrorDisplay).not.toHaveBeenCalled();
});
});
});
describe('when changing story in story viewMode', () => {
it('calls renderToCanvass teardown', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
projectAnnotations.renderToCanvas.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
expect(teardownrenderToCanvas).toHaveBeenCalled();
});
it('updates URL', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
expect(history.replaceState).toHaveBeenCalledWith(
{},
'',
'pathname?id=component-one--b&viewMode=story'
);
});
it('renders preparing state', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
expect(preview.view.showPreparingStory).toHaveBeenCalled();
});
it('emits STORY_CHANGED', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForEvents([STORY_CHANGED]);
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_CHANGED, 'component-one--b');
});
it('emits STORY_PREPARED', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForEvents([STORY_PREPARED]);
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_PREPARED, {
id: 'component-one--b',
parameters: {
__isArgsStory: false,
docs: expect.any(Object),
fileName: './src/ComponentOne.stories.js',
},
initialArgs: { foo: 'b', one: 1 },
argTypes: {
foo: { name: 'foo', type: { name: 'string' } },
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped-1' } },
},
args: { foo: 'b', one: 1 },
});
});
it('applies loaders with story context', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(componentOneExports.default.loaders[0]).toHaveBeenCalledWith(
expect.objectContaining({
id: 'component-one--b',
parameters: {
__isArgsStory: false,
docs: expect.any(Object),
fileName: './src/ComponentOne.stories.js',
},
initialArgs: { foo: 'b', one: 1 },
argTypes: {
foo: { name: 'foo', type: { name: 'string' } },
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped-1' } },
},
args: { foo: 'b', one: 'mapped-1' },
})
);
});
it('passes loaded context to renderToCanvas', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: true,
storyContext: expect.objectContaining({
id: 'component-one--b',
parameters: {
__isArgsStory: false,
docs: expect.any(Object),
fileName: './src/ComponentOne.stories.js',
},
globals: { a: 'b' },
initialArgs: { foo: 'b', one: 1 },
argTypes: {
foo: { name: 'foo', type: { name: 'string' } },
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped-1' } },
},
args: { foo: 'b', one: 'mapped-1' },
loaded: { l: 7 },
}),
}),
'story-element'
);
});
it('renders exception if renderToCanvas throws', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
const error = new Error('error');
projectAnnotations.renderToCanvas.mockImplementation(() => {
throw error;
});
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_THREW_EXCEPTION, serializeError(error));
expect(preview.view.showErrorDisplay).toHaveBeenCalledWith(error);
});
it('renders error if the story calls showError', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
const error = { title: 'title', description: 'description' };
projectAnnotations.renderToCanvas.mockImplementation((context) => context.showError(error));
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_ERRORED, error);
expect(preview.view.showErrorDisplay).toHaveBeenCalledWith({
message: error.title,
stack: error.description,
});
});
it('renders exception if the story calls showException', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
const error = new Error('error');
projectAnnotations.renderToCanvas.mockImplementation((context) =>
context.showException(error)
);
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_THREW_EXCEPTION, serializeError(error));
expect(preview.view.showErrorDisplay).toHaveBeenCalledWith(error);
});
it('executes playFunction', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(componentOneExports.b.play).toHaveBeenCalled();
});
it('emits STORY_RENDERED', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-one--b');
});
it('retains any arg changes', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { foo: 'updated' },
});
await waitForRender();
expect(preview.storyStore.args.get('component-one--a')).toEqual({
foo: 'updated',
one: 1,
});
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(preview.storyStore.args.get('component-one--a')).toEqual({
foo: 'updated',
one: 1,
});
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(preview.storyStore.args.get('component-one--a')).toEqual({
foo: 'updated',
one: 1,
});
});
describe('while story is still rendering', () => {
let originalLocation = window.location;
beforeEach(() => {
originalLocation = window.location;
delete (window as Partial<Window>).location;
window.location = { ...originalLocation, reload: jest.fn() };
});
afterEach(() => {
delete (window as Partial<Window>).location;
window.location = { ...originalLocation, reload: originalLocation.reload };
});
it('stops initial story after loaders if running', async () => {
const [gate, openGate] = createGate();
componentOneExports.default.loaders[0].mockImplementationOnce(async () => gate);
document.location.search = '?id=component-one--a';
await new PreviewWeb().initialize({ importFn, getProjectAnnotations });
await waitForRenderPhase('loading');
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
// Now let the loader resolve
openGate({ l: 8 });
await waitForRender();
// Story gets rendered with updated args
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledTimes(1);
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: true,
storyContext: expect.objectContaining({
id: 'component-one--b',
loaded: { l: 7 },
}),
}),
'story-element'
);
});
it('aborts render for initial story', async () => {
const [gate, openGate] = createGate();
document.location.search = '?id=component-one--a';
projectAnnotations.renderToCanvas.mockImplementation(async () => gate);
await new PreviewWeb().initialize({ importFn, getProjectAnnotations });
await waitForRenderPhase('rendering');
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
// Now let the renderToCanvas call resolve
openGate();
await waitForRenderPhase('aborted');
await waitForSetCurrentStory();
await waitForRenderPhase('rendering');
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledTimes(2);
await waitForRenderPhase('playing');
expect(componentOneExports.a.play).not.toHaveBeenCalled();
expect(componentOneExports.b.play).toHaveBeenCalled();
await waitForRenderPhase('completed');
expect(mockChannel.emit).not.toHaveBeenCalledWith(STORY_RENDERED, 'component-one--a');
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-one--b');
await waitForQuiescence();
});
it('aborts play function for initial story', async () => {
const [gate, openGate] = createGate();
componentOneExports.a.play.mockImplementationOnce(async () => gate);
document.location.search = '?id=component-one--a';
await new PreviewWeb().initialize({ importFn, getProjectAnnotations });
await waitForRenderPhase('playing');
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: true,
storyContext: expect.objectContaining({
id: 'component-one--a',
loaded: { l: 7 },
}),
}),
'story-element'
);
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
// Now let the playFunction call resolve
openGate();
await waitForRenderPhase('aborted');
await waitForSetCurrentStory();
await waitForRenderPhase('rendering');
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_CHANGED, 'component-one--b');
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: true,
storyContext: expect.objectContaining({
id: 'component-one--b',
loaded: { l: 7 },
}),
}),
'story-element'
);
await waitForRenderPhase('playing');
await waitForRenderPhase('completed');
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-one--b');
// Final story rendered is not emitted for the first story
await waitForQuiescence();
expect(mockChannel.emit).not.toHaveBeenCalledWith(STORY_RENDERED, 'component-one--a');
});
it('reloads page if playFunction fails to abort in time', async () => {
const [gate] = createGate();
componentOneExports.a.play.mockImplementationOnce(async () => gate);
document.location.search = '?id=component-one--a';
await new PreviewWeb().initialize({ importFn, getProjectAnnotations });
await waitForRenderPhase('playing');
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: true,
storyContext: expect.objectContaining({
id: 'component-one--a',
loaded: { l: 7 },
}),
}),
'story-element'
);
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
// Wait three ticks without resolving the play function
await waitForSetCurrentStory();
// We can't mock setTimeout for this test, due to waitForSetCurrentStory hack,
// So give some (real) time for the reload to be called
await new Promise((r) => setTimeout(r, 100));
expect(window.location.reload).toHaveBeenCalled();
expect(mockChannel.emit).not.toHaveBeenCalledWith(STORY_CHANGED, 'component-one--b');
expect(projectAnnotations.renderToCanvas).not.toHaveBeenCalledWith(
expect.objectContaining({
storyContext: expect.objectContaining({ id: 'component-one--b' }),
}),
undefined
);
});
});
});
describe('when changing from story viewMode to docs', () => {
it('emits DOCS_PREPARED', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--docs',
viewMode: 'docs',
});
await waitForSetCurrentStory();
expect(mockChannel.emit).toHaveBeenCalledWith(DOCS_PREPARED, {
id: 'component-one--docs',
parameters: {
docs: expect.any(Object),
fileName: './src/ComponentOne.stories.js',
},
});
});
it('calls renderToCanvass teardown', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--docs',
viewMode: 'docs',
});
await waitForSetCurrentStory();
expect(teardownrenderToCanvas).toHaveBeenCalled();
});
it('updates URL', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--docs',
viewMode: 'docs',
});
await waitForSetCurrentStory();
expect(history.replaceState).toHaveBeenCalledWith(
{},
'',
'pathname?id=component-one--docs&viewMode=docs'
);
});
it('renders preparing state', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--docs',
viewMode: 'docs',
});
await waitForSetCurrentStory();
expect(preview.view.showPreparingDocs).toHaveBeenCalled();
});
it('emits STORY_CHANGED', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--docs',
viewMode: 'docs',
});
await waitForSetCurrentStory();
await waitForEvents([STORY_CHANGED]);
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_CHANGED, 'component-one--docs');
});
it('calls view.prepareForDocs', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--docs',
viewMode: 'docs',
});
await waitForSetCurrentStory();
await waitForRender();
expect(preview.view.prepareForDocs).toHaveBeenCalled();
});
it('render the docs container with the correct context, template render', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--docs',
viewMode: 'docs',
});
await waitForSetCurrentStory();
await waitForRender();
expect(docsRenderer.render).toHaveBeenCalled();
expect(docsRenderer.render.mock.calls[0][0].storyById()).toMatchObject({
id: 'component-one--a',
});
});
it('emits DOCS_RENDERED', async () => {
document.location.search = '?id=component-one--a';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--docs',
viewMode: 'docs',
});
await waitForSetCurrentStory();
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(DOCS_RENDERED, 'component-one--docs');
});
});
describe('when changing from docs viewMode to story', () => {
it('updates URL', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
await createAndRenderPreview();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
expect(history.replaceState).toHaveBeenCalledWith(
{},
'',
'pathname?id=component-one--a&viewMode=story'
);
});
it('unmounts docs', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(docsRenderer.unmount).toHaveBeenCalled();
});
// NOTE: I am not sure this entirely makes sense but this is the behaviour from 6.3
it('emits STORY_CHANGED', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForEvents([STORY_CHANGED]);
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_CHANGED, 'component-one--a');
});
it('calls view.prepareForStory', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(preview.view.prepareForStory).toHaveBeenCalledWith(
expect.objectContaining({
id: 'component-one--a',
})
);
});
it('emits STORY_PREPARED', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForEvents([STORY_PREPARED]);
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_PREPARED, {
id: 'component-one--a',
parameters: {
__isArgsStory: false,
docs: expect.any(Object),
fileName: './src/ComponentOne.stories.js',
},
initialArgs: { foo: 'a', one: 1 },
argTypes: {
foo: { name: 'foo', type: { name: 'string' } },
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped-1' } },
},
args: { foo: 'a', one: 1 },
});
});
it('applies loaders with story context', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(componentOneExports.default.loaders[0]).toHaveBeenCalledWith(
expect.objectContaining({
id: 'component-one--a',
parameters: {
__isArgsStory: false,
docs: expect.any(Object),
fileName: './src/ComponentOne.stories.js',
},
initialArgs: { foo: 'a', one: 1 },
argTypes: {
foo: { name: 'foo', type: { name: 'string' } },
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped-1' } },
},
args: { foo: 'a', one: 'mapped-1' },
})
);
});
it('passes loaded context to renderToCanvas', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: true,
storyContext: expect.objectContaining({
id: 'component-one--a',
parameters: {
__isArgsStory: false,
docs: expect.any(Object),
fileName: './src/ComponentOne.stories.js',
},
globals: { a: 'b' },
initialArgs: { foo: 'a', one: 1 },
argTypes: {
foo: { name: 'foo', type: { name: 'string' } },
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped-1' } },
},
args: { foo: 'a', one: 'mapped-1' },
loaded: { l: 7 },
}),
}),
'story-element'
);
});
it('renders exception if renderToCanvas throws', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = await createAndRenderPreview();
const error = new Error('error');
projectAnnotations.renderToCanvas.mockImplementation(() => {
throw error;
});
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_THREW_EXCEPTION, serializeError(error));
expect(preview.view.showErrorDisplay).toHaveBeenCalledWith(error);
});
it('renders error if the story calls showError', async () => {
const error = { title: 'title', description: 'description' };
projectAnnotations.renderToCanvas.mockImplementation((context) => context.showError(error));
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_ERRORED, error);
expect(preview.view.showErrorDisplay).toHaveBeenCalledWith({
message: error.title,
stack: error.description,
});
});
it('renders exception if the story calls showException', async () => {
const error = new Error('error');
projectAnnotations.renderToCanvas.mockImplementation((context) =>
context.showException(error)
);
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_THREW_EXCEPTION, serializeError(error));
expect(preview.view.showErrorDisplay).toHaveBeenCalledWith(error);
});
it('executes playFunction', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(componentOneExports.a.play).toHaveBeenCalled();
});
it('emits STORY_RENDERED', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-one--a');
});
});
});
describe('onStoriesChanged', () => {
describe('if stories.json endpoint 500s initially', () => {
it('recovers and renders the story', async () => {
document.location.search = '?id=component-one--a';
const err = new Error('sort error');
mockFetchResult = { status: 500, text: async () => err.toString() };
const preview = new PreviewWeb();
await expect(preview.initialize({ importFn, getProjectAnnotations })).rejects.toThrow(
'sort error'
);
expect(preview.view.showErrorDisplay).toHaveBeenCalled();
expect(mockChannel.emit).toHaveBeenCalledWith(CONFIG_ERROR, expect.any(Error));
mockChannel.emit.mockClear();
mockFetchResult = { status: 200, json: mockStoryIndex, text: () => 'error text' };
preview.onStoryIndexChanged();
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-one--a');
});
it('sets story args from the URL', async () => {
document.location.search = '?id=component-one--a&args=foo:url';
const err = new Error('sort error');
mockFetchResult = { status: 500, text: async () => err.toString() };
const preview = new PreviewWeb();
await expect(preview.initialize({ importFn, getProjectAnnotations })).rejects.toThrow(
'sort error'
);
expect(preview.view.showErrorDisplay).toHaveBeenCalled();
expect(mockChannel.emit).toHaveBeenCalledWith(CONFIG_ERROR, expect.any(Error));
mockChannel.emit.mockClear();
mockFetchResult = { status: 200, json: mockStoryIndex, text: () => 'error text' };
preview.onStoryIndexChanged();
await waitForRender();
expect(preview.storyStore.args.get('component-one--a')).toEqual({
foo: 'url',
one: 1,
});
});
});
describe('when the current story changes', () => {
const newComponentOneExports = merge({}, componentOneExports, {
a: { args: { foo: 'edited' } },
});
const newImportFn = jest.fn(async (path) => {
return path === './src/ComponentOne.stories.js'
? newComponentOneExports
: componentTwoExports;
});
it('calls renderToCanvass teardown', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
expect(teardownrenderToCanvas).toHaveBeenCalled();
});
it('does not emit STORY_UNCHANGED', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
expect(mockChannel.emit).not.toHaveBeenCalledWith(STORY_UNCHANGED, 'component-one--a');
});
it('does not emit STORY_CHANGED', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
expect(mockChannel.emit).not.toHaveBeenCalledWith(STORY_CHANGED, 'component-one--a');
});
it('emits STORY_PREPARED with new annotations', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_PREPARED, {
id: 'component-one--a',
parameters: {
__isArgsStory: false,
docs: expect.any(Object),
fileName: './src/ComponentOne.stories.js',
},
initialArgs: { foo: 'edited', one: 1 },
argTypes: {
foo: { name: 'foo', type: { name: 'string' } },
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped-1' } },
},
args: { foo: 'edited', one: 1 },
});
});
it('emits STORY_ARGS_UPDATED with new args', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_ARGS_UPDATED, {
storyId: 'component-one--a',
args: { foo: 'edited', one: 1 },
});
});
it('applies loaders with story context', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
componentOneExports.default.loaders[0].mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
expect(componentOneExports.default.loaders[0]).toHaveBeenCalledWith(
expect.objectContaining({
id: 'component-one--a',
parameters: {
__isArgsStory: false,
docs: expect.any(Object),
fileName: './src/ComponentOne.stories.js',
},
initialArgs: { foo: 'edited', one: 1 },
argTypes: {
foo: { name: 'foo', type: { name: 'string' } },
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped-1' } },
},
args: { foo: 'edited', one: 'mapped-1' },
})
);
});
it('passes loaded context to renderToCanvas', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
projectAnnotations.renderToCanvas.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: true,
storyContext: expect.objectContaining({
id: 'component-one--a',
parameters: {
__isArgsStory: false,
docs: expect.any(Object),
fileName: './src/ComponentOne.stories.js',
},
globals: { a: 'b' },
initialArgs: { foo: 'edited', one: 1 },
argTypes: {
foo: { name: 'foo', type: { name: 'string' } },
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped-1' } },
},
args: { foo: 'edited', one: 'mapped-1' },
loaded: { l: 7 },
}),
}),
'story-element'
);
});
it('retains the same delta to the args', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { foo: 'updated' },
});
await waitForRender();
mockChannel.emit.mockClear();
projectAnnotations.renderToCanvas.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: true,
storyContext: expect.objectContaining({
id: 'component-one--a',
args: { foo: 'updated', one: 'mapped-1' },
}),
}),
'story-element'
);
});
it('renders exception if renderToCanvas throws', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
const error = new Error('error');
projectAnnotations.renderToCanvas.mockImplementation(() => {
throw error;
});
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_THREW_EXCEPTION, serializeError(error));
expect(preview.view.showErrorDisplay).toHaveBeenCalledWith(error);
});
it('renders error if the story calls showError', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
const error = { title: 'title', description: 'description' };
projectAnnotations.renderToCanvas.mockImplementation((context) => context.showError(error));
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_ERRORED, error);
expect(preview.view.showErrorDisplay).toHaveBeenCalledWith({
message: error.title,
stack: error.description,
});
});
it('renders exception if the story calls showException', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
const error = new Error('error');
projectAnnotations.renderToCanvas.mockImplementation((context) =>
context.showException(error)
);
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_THREW_EXCEPTION, serializeError(error));
expect(preview.view.showErrorDisplay).toHaveBeenCalledWith(error);
});
it('executes playFunction', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
componentOneExports.a.play.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
expect(componentOneExports.a.play).toHaveBeenCalled();
});
it('emits STORY_RENDERED', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-one--a');
});
});
describe('when the current story changes importPath', () => {
const newImportFn = jest.fn(async (path) => ({ ...componentOneExports }));
const newStoryIndex = {
v: 4,
entries: {
...storyIndex.entries,
'component-one--a': {
...storyIndex.entries['component-one--a'],
importPath: './src/ComponentOne-new.stories.js',
},
},
};
beforeEach(() => {
newImportFn.mockClear();
});
it('re-imports the component', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn, storyIndex: newStoryIndex });
await waitForRender();
expect(newImportFn).toHaveBeenCalledWith('./src/ComponentOne-new.stories.js');
});
describe('if it was previously rendered', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
it('is reloaded when it is re-selected', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
preview.onStoriesChanged({ importFn: newImportFn, storyIndex: newStoryIndex });
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(newImportFn).toHaveBeenCalledWith('./src/ComponentOne-new.stories.js');
});
});
});
describe('when the current story has not changed', () => {
const newComponentTwoExports = { ...componentTwoExports };
const newImportFn = jest.fn(async (path) => {
return path === './src/ComponentOne.stories.js'
? componentOneExports
: newComponentTwoExports;
});
it('does NOT call renderToCanvass teardown', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForEvents([STORY_UNCHANGED]);
expect(teardownrenderToCanvas).not.toHaveBeenCalled();
});
it('emits STORY_UNCHANGED', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForEvents([STORY_UNCHANGED]);
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_UNCHANGED, 'component-one--a');
expect(mockChannel.emit).not.toHaveBeenCalledWith(STORY_CHANGED, 'component-one--a');
});
it('clears preparing state', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
(preview.view.showMain as jest.Mock).mockClear();
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForEvents([STORY_UNCHANGED]);
expect(preview.view.showMain).toHaveBeenCalled();
});
it('does not re-render the story', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
projectAnnotations.renderToCanvas.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForQuiescence();
expect(projectAnnotations.renderToCanvas).not.toHaveBeenCalled();
expect(mockChannel.emit).not.toHaveBeenCalledWith(STORY_RENDERED, 'component-one--a');
});
});
describe('when another (not current) story changes', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
const newComponentOneExports = merge({}, componentOneExports, {
a: { args: { bar: 'edited' }, argTypes: { bar: { type: { name: 'string' } } } },
});
const newImportFn = jest.fn(async (path) => {
return path === './src/ComponentOne.stories.js'
? newComponentOneExports
: componentTwoExports;
});
it('retains the same delta to the args', async () => {
// Start at Story A
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
// Change A's args
mockChannel.emit.mockClear();
emitter.emit(UPDATE_STORY_ARGS, {
storyId: 'component-one--a',
updatedArgs: { foo: 'updated' },
});
await waitForRender();
// Change to story B
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--b',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(preview.storyStore.args.get('component-one--a')).toEqual({
foo: 'updated',
one: 1,
});
// Update story A's args via HMR
mockChannel.emit.mockClear();
projectAnnotations.renderToCanvas.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
// Change back to Story A
mockChannel.emit.mockClear();
emitter.emit(SET_CURRENT_STORY, {
storyId: 'component-one--a',
viewMode: 'story',
});
await waitForSetCurrentStory();
await waitForRender();
expect(preview.storyStore.args.get('component-one--a')).toEqual({
foo: 'updated',
bar: 'edited',
one: 1,
});
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
forceRemount: true,
storyContext: expect.objectContaining({
id: 'component-one--a',
args: { foo: 'updated', bar: 'edited', one: 'mapped-1' },
}),
}),
'story-element'
);
});
});
describe('if the story no longer exists', () => {
const { a, ...componentOneExportsWithoutA } = componentOneExports;
const newImportFn = jest.fn(async (path) => {
return path === './src/ComponentOne.stories.js'
? componentOneExportsWithoutA
: componentTwoExports;
});
const newStoryIndex = {
v: 4,
entries: {
'component-one--b': storyIndex.entries['component-one--b'],
},
};
it('calls renderToCanvass teardown', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn, storyIndex: newStoryIndex });
await waitForEvents([STORY_MISSING]);
expect(teardownrenderToCanvas).toHaveBeenCalled();
});
it('renders loading error', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn, storyIndex: newStoryIndex });
await waitForEvents([STORY_MISSING]);
expect(preview.view.showErrorDisplay).toHaveBeenCalled();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_MISSING, 'component-one--a');
});
it('does not re-render the story', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
projectAnnotations.renderToCanvas.mockClear();
preview.onStoriesChanged({ importFn: newImportFn, storyIndex: newStoryIndex });
await waitForQuiescence();
expect(projectAnnotations.renderToCanvas).not.toHaveBeenCalled();
expect(mockChannel.emit).not.toHaveBeenCalledWith(STORY_RENDERED, 'component-one--a');
});
it('re-renders the story if it is readded', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn, storyIndex: newStoryIndex });
await waitForEvents([STORY_MISSING]);
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn, storyIndex });
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-one--a');
});
});
describe('when a mdx docs file changes', () => {
const newUnattachedDocsExports = { default: jest.fn() };
const newImportFn = jest.fn(async (path: string) => {
return path === './src/Introduction.mdx' ? newUnattachedDocsExports : importFn(path);
});
it('emits DOCS_PREPARED', async () => {
document.location.search = '?id=introduction--docs';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
docsRenderer.render.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(DOCS_PREPARED, {
id: 'introduction--docs',
parameters: {
docs: expect.any(Object),
},
});
});
it('renders with the generated docs parameters', async () => {
document.location.search = '?id=introduction--docs&viewMode=docs';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
docsRenderer.render.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
expect(docsRenderer.render).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({
page: newUnattachedDocsExports.default,
renderer: projectAnnotations.parameters.docs.renderer,
}),
'docs-element'
);
});
it('emits DOCS_RENDERED', async () => {
document.location.search = '?id=introduction--docs&viewMode=docs';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onStoriesChanged({ importFn: newImportFn });
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(DOCS_RENDERED, 'introduction--docs');
});
});
});
describe('onGetProjectAnnotationsChanged', () => {
describe('if initial getProjectAnnotations threw', () => {
it('recovers and renders the story', async () => {
document.location.search = '?id=component-one--a';
const err = new Error('meta error');
const preview = new PreviewWeb();
await expect(
preview.initialize({
importFn,
getProjectAnnotations: () => {
throw err;
},
})
).rejects.toThrow(err);
preview.onGetProjectAnnotationsChanged({ getProjectAnnotations });
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_RENDERED, 'component-one--a');
});
it('sets globals from the URL', async () => {
document.location.search = '?id=*&globals=a:c';
const err = new Error('meta error');
const preview = new PreviewWeb();
await expect(
preview.initialize({
importFn,
getProjectAnnotations: () => {
throw err;
},
})
).rejects.toThrow(err);
preview.onGetProjectAnnotationsChanged({ getProjectAnnotations });
await waitForRender();
expect(preview.storyStore.globals!.get()).toEqual({ a: 'c' });
});
});
describe('with no selection', () => {
// eslint-disable-next-line jest/expect-expect
it('does not error', async () => {
const preview = await createAndRenderPreview();
await preview.onGetProjectAnnotationsChanged({
getProjectAnnotations: newGetProjectAnnotations,
});
});
});
it('shows an error the new value throws', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
const err = new Error('error getting meta');
await expect(
preview.onGetProjectAnnotationsChanged({
getProjectAnnotations: () => {
throw err;
},
})
).rejects.toThrow(err);
expect(preview.view.showErrorDisplay).toHaveBeenCalled();
expect(mockChannel.emit).toHaveBeenCalledWith(CONFIG_ERROR, err);
});
const newGlobalDecorator = jest.fn((s: any) => s());
const newGetProjectAnnotations = () => {
return {
...projectAnnotations,
args: { global: 'added' },
globals: { a: 'edited' },
decorators: [newGlobalDecorator],
};
};
it('updates globals to their new values', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onGetProjectAnnotationsChanged({ getProjectAnnotations: newGetProjectAnnotations });
await waitForRender();
expect(preview.storyStore.globals!.get()).toEqual({ a: 'edited' });
});
it('emits SET_GLOBALS with new values', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onGetProjectAnnotationsChanged({ getProjectAnnotations: newGetProjectAnnotations });
await waitForRender();
await waitForEvents([SET_GLOBALS]);
expect(mockChannel.emit).toHaveBeenCalledWith(SET_GLOBALS, {
globals: { a: 'edited' },
globalTypes: {},
});
});
it('updates args to their new values', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onGetProjectAnnotationsChanged({ getProjectAnnotations: newGetProjectAnnotations });
await waitForRender();
expect(preview.storyStore.args.get('component-one--a')).toEqual({
foo: 'a',
one: 1,
global: 'added',
});
});
it('emits SET_STORY_ARGS with new values', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
preview.onGetProjectAnnotationsChanged({ getProjectAnnotations: newGetProjectAnnotations });
await waitForRender();
expect(mockChannel.emit).toHaveBeenCalledWith(STORY_ARGS_UPDATED, {
storyId: 'component-one--a',
args: { foo: 'a', one: 1, global: 'added' },
});
});
it('calls renderToCanvass teardown', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
projectAnnotations.renderToCanvas.mockClear();
mockChannel.emit.mockClear();
preview.onGetProjectAnnotationsChanged({ getProjectAnnotations: newGetProjectAnnotations });
await waitForRender();
expect(teardownrenderToCanvas).toHaveBeenCalled();
});
it('rerenders the current story with new global meta-generated context', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
projectAnnotations.renderToCanvas.mockClear();
mockChannel.emit.mockClear();
preview.onGetProjectAnnotationsChanged({ getProjectAnnotations: newGetProjectAnnotations });
await waitForRender();
expect(projectAnnotations.renderToCanvas).toHaveBeenCalledWith(
expect.objectContaining({
storyContext: expect.objectContaining({
args: { foo: 'a', one: 'mapped-1', global: 'added' },
globals: { a: 'edited' },
}),
}),
'story-element'
);
});
});
describe('onKeydown', () => {
it('emits PREVIEW_KEYDOWN for regular elements', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = await createAndRenderPreview();
preview.onKeydown({
composedPath: jest
.fn()
.mockReturnValue([{ tagName: 'div', getAttribute: jest.fn().mockReturnValue(null) }]),
} as any);
expect(mockChannel.emit).toHaveBeenCalledWith(PREVIEW_KEYDOWN, expect.objectContaining({}));
});
it('emits PREVIEW_KEYDOWN for regular elements, fallback to event.target', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = await createAndRenderPreview();
preview.onKeydown({
target: { tagName: 'div', getAttribute: jest.fn().mockReturnValue(null) },
} as any);
expect(mockChannel.emit).toHaveBeenCalledWith(PREVIEW_KEYDOWN, expect.objectContaining({}));
});
it('does not emit PREVIEW_KEYDOWN for input elements', async () => {
document.location.search = '?id=component-one--docs&viewMode=docs';
const preview = await createAndRenderPreview();
preview.onKeydown({
composedPath: jest
.fn()
.mockReturnValue([{ tagName: 'input', getAttribute: jest.fn().mockReturnValue(null) }]),
} as any);
expect(mockChannel.emit).not.toHaveBeenCalledWith(
PREVIEW_KEYDOWN,
expect.objectContaining({})
);
});
it('does not emit PREVIEW_KEYDOWN during story play functions', async () => {
document.location.search = '?id=component-one--a';
const [gate, openGate] = createGate();
componentOneExports.a.play.mockImplementationOnce(async () => gate);
const preview = new PreviewWeb();
await preview.initialize({ importFn, getProjectAnnotations });
await waitForRenderPhase('playing');
await preview.onKeydown({
target: { tagName: 'div', getAttribute: jest.fn().mockReturnValue(null) },
} as any);
expect(mockChannel.emit).not.toHaveBeenCalledWith(
PREVIEW_KEYDOWN,
expect.objectContaining({})
);
openGate();
});
it('does not emit PREVIEW_KEYDOWN during docs play functions', async () => {
document.location.search = '?id=component-one--a';
const preview = await createAndRenderPreview();
mockChannel.emit.mockClear();
const [gate, openGate] = createGate();
componentOneExports.b.play.mockImplementationOnce(async () => gate);
// @ts-expect-error (not strict)
preview.renderStoryToElement(
await preview.storyStore.loadStory({ storyId: 'component-one--b' }),
{} as any
);
await waitForRenderPhase('playing');
await preview.onKeydown({
target: { tagName: 'div', getAttribute: jest.fn().mockReturnValue(null) },
} as any);
expect(mockChannel.emit).not.toHaveBeenCalledWith(
PREVIEW_KEYDOWN,
expect.objectContaining({})
);
openGate();
});
});
describe('extract', () => {
// NOTE: if you are using storyStoreV6, and your `preview.js` throws, we do not currently
// detect it (as we do not wrap the import of `preview.js` in a `try/catch`). The net effect
// of that is that the `PreviewWeb`/`StoryStore` end up in an uninitalized state.
it('throws an error if the preview is uninitialized', async () => {
const preview = new PreviewWeb();
await expect(preview.extract()).rejects.toThrow(/Failed to initialize/);
});
it('throws an error if preview.js throws', async () => {
const err = new Error('meta error');
const preview = new PreviewWeb();
await expect(
preview.initialize({
importFn,
getProjectAnnotations: () => {
throw err;
},
})
).rejects.toThrow(err);
await expect(preview.extract()).rejects.toThrow(err);
});
it('shows an error if the stories.json endpoint 500s', async () => {
const err = new Error('sort error');
mockFetchResult = { status: 500, text: async () => err.toString() };
const preview = new PreviewWeb();
await expect(preview.initialize({ importFn, getProjectAnnotations })).rejects.toThrow(
'sort error'
);
await expect(preview.extract()).rejects.toThrow('sort error');
});
it('waits for stories to be cached', async () => {
const [gate, openGate] = createGate();
const gatedImportFn = async (path: string) => {
await gate;
return importFn(path);
};
const preview = await createAndRenderPreview({ importFn: gatedImportFn });
let extracted = false;
preview.extract().then(() => {
extracted = true;
});
expect(extracted).toBe(false);
openGate();
await new Promise((r) => setTimeout(r, 0)); // Let the promise resolve
expect(extracted).toBe(true);
expect(await preview.extract()).toMatchInlineSnapshot(`
Object {
"component-one--a": Object {
"argTypes": Object {
"foo": Object {
"name": "foo",
"type": Object {
"name": "string",
},
},
"one": Object {
"mapping": Object {
"1": "mapped-1",
},
"name": "one",
"type": Object {
"name": "string",
},
},
},
"args": Object {
"foo": "a",
"one": 1,
},
"component": undefined,
"componentId": "component-one",
"id": "component-one--a",
"initialArgs": Object {
"foo": "a",
"one": 1,
},
"kind": "Component One",
"name": "A",
"parameters": Object {
"__isArgsStory": false,
"docs": Object {
"container": [MockFunction],
"page": [MockFunction],
"renderer": [Function],
},
"fileName": "./src/ComponentOne.stories.js",
},
"story": "A",
"subcomponents": undefined,
"tags": Array [
"story",
],
"title": "Component One",
},
"component-one--b": Object {
"argTypes": Object {
"foo": Object {
"name": "foo",
"type": Object {
"name": "string",
},
},
"one": Object {
"mapping": Object {
"1": "mapped-1",
},
"name": "one",
"type": Object {
"name": "string",
},
},
},
"args": Object {
"foo": "b",
"one": 1,
},
"component": undefined,
"componentId": "component-one",
"id": "component-one--b",
"initialArgs": Object {
"foo": "b",
"one": 1,
},
"kind": "Component One",
"name": "B",
"parameters": Object {
"__isArgsStory": false,
"docs": Object {
"container": [MockFunction],
"page": [MockFunction],
"renderer": [Function],
},
"fileName": "./src/ComponentOne.stories.js",
},
"story": "B",
"subcomponents": undefined,
"tags": Array [
"story",
],
"title": "Component One",
},
"component-one--e": Object {
"argTypes": Object {},
"args": Object {},
"component": undefined,
"componentId": "component-one",
"id": "component-one--e",
"initialArgs": Object {},
"kind": "Component One",
"name": "E",
"parameters": Object {
"__isArgsStory": false,
"docs": Object {
"page": [MockFunction],
"renderer": [Function],
},
"fileName": "./src/ExtraComponentOne.stories.js",
},
"playFunction": undefined,
"story": "E",
"subcomponents": undefined,
"tags": Array [
"story",
],
"title": "Component One",
},
"component-two--c": Object {
"argTypes": Object {
"foo": Object {
"name": "foo",
"type": Object {
"name": "string",
},
},
},
"args": Object {
"foo": "c",
},
"component": undefined,
"componentId": "component-two",
"id": "component-two--c",
"initialArgs": Object {
"foo": "c",
},
"kind": "Component Two",
"name": "C",
"parameters": Object {
"__isArgsStory": false,
"docs": Object {
"renderer": [Function],
},
"fileName": "./src/ComponentTwo.stories.js",
},
"playFunction": undefined,
"story": "C",
"subcomponents": undefined,
"tags": Array [
"story",
],
"title": "Component Two",
},
}
`);
});
});
});
|