level_0
int64 0
10k
| index
int64 0
0
| repo_id
stringlengths 22
152
| file_path
stringlengths 41
203
| content
stringlengths 11
11.5M
|
---|---|---|---|---|
1,140 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/preview-web/UrlStore.test.ts | import { global } from '@storybook/global';
import { pathToId, setPath, getSelectionSpecifierFromPath } from './UrlStore';
const { history, document } = global;
jest.mock('@storybook/global', () => ({
global: {
history: { replaceState: jest.fn() },
document: {
location: {
pathname: 'pathname',
search: '',
},
},
},
}));
describe('UrlStore', () => {
describe('pathToId', () => {
it('should parse valid ids', () => {
expect(pathToId('/story/story--id')).toEqual('story--id');
});
it('should error on invalid ids', () => {
[null, '', '/whatever/story/story--id'].forEach((path: any) => {
expect(() => pathToId(path)).toThrow(/Invalid/);
});
});
});
describe('setPath', () => {
it('should navigate to storyId', () => {
setPath({ storyId: 'story--id', viewMode: 'story' });
expect(history.replaceState).toHaveBeenCalledWith(
{},
'',
'pathname?id=story--id&viewMode=story'
);
});
it('should replace legacy parameters but preserve others', () => {
document.location.search = 'foo=bar&selectedStory=selStory&selectedKind=selKind';
setPath({ storyId: 'story--id', viewMode: 'story' });
expect(history.replaceState).toHaveBeenCalledWith(
{},
'',
'pathname?foo=bar&id=story--id&viewMode=story'
);
});
it('should ignore + keep hashes', () => {
document.location.search = 'foo=bar&selectedStory=selStory&selectedKind=selKind';
document.location.hash = '#foobar';
setPath({ storyId: 'story--id', viewMode: 'story' });
expect(history.replaceState).toHaveBeenCalledWith(
{},
'',
'pathname?foo=bar&id=story--id&viewMode=story#foobar'
);
});
});
describe('getSelectionSpecifierFromPath', () => {
it('should handle no search', () => {
document.location.search = '';
expect(getSelectionSpecifierFromPath()).toEqual(null);
});
it('should handle id queries', () => {
document.location.search = '?id=story--id';
expect(getSelectionSpecifierFromPath()).toEqual({
storySpecifier: 'story--id',
viewMode: 'story',
});
});
it('should handle id queries with *', () => {
document.location.search = '?id=*';
expect(getSelectionSpecifierFromPath()).toEqual({
storySpecifier: '*',
viewMode: 'story',
});
});
it('should parse args', () => {
document.location.search = '?id=story--id&args=obj.key:val';
expect(getSelectionSpecifierFromPath()).toEqual({
storySpecifier: 'story--id',
viewMode: 'story',
args: { obj: { key: 'val' } },
});
});
it('should handle singleStory param', () => {
document.location.search = '?id=abc&singleStory=true';
expect(getSelectionSpecifierFromPath()).toEqual({
storySpecifier: 'abc',
viewMode: 'story',
});
});
});
});
|
1,145 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/preview-web/parseArgsParam.test.ts | import { parseArgsParam } from './parseArgsParam';
jest.mock('@storybook/client-logger', () => ({
once: { warn: jest.fn() },
}));
describe('parseArgsParam', () => {
it('parses a simple key-value pair', () => {
const args = parseArgsParam('key:val');
expect(args).toStrictEqual({ key: 'val' });
});
it('parses spaces', () => {
const args = parseArgsParam('key:one+two+three');
expect(args).toStrictEqual({ key: 'one two three' });
});
it('parses null', () => {
const args = parseArgsParam('key:!null');
expect(args).toStrictEqual({ key: null });
});
it('parses undefined', () => {
const args = parseArgsParam('key:!undefined');
expect(args).toStrictEqual({ key: undefined });
});
it('parses true', () => {
const args = parseArgsParam('key:!true');
expect(args).toStrictEqual({ key: true });
});
it('parses false', () => {
const args = parseArgsParam('key:!false');
expect(args).toStrictEqual({ key: false });
});
it('parses hex color values', () => {
const args = parseArgsParam('key:!hex(ff4785)');
expect(args).toStrictEqual({ key: '#ff4785' });
});
it('parses rgba color values', () => {
const args = parseArgsParam('rgb:!rgb(255,71,133);rgba:!rgba(255,71,133,0.5)');
expect(args).toStrictEqual({ rgb: 'rgb(255, 71, 133)', rgba: 'rgba(255, 71, 133, 0.5)' });
});
it('parses hsla color values', () => {
const args = parseArgsParam('hsl:!hsl(45,99,70);hsla:!hsla(45,99,70,0.5)');
expect(args).toStrictEqual({ hsl: 'hsl(45, 99%, 70%)', hsla: 'hsla(45, 99%, 70%, 0.5)' });
});
it('parses Date', () => {
const args = parseArgsParam('key:!date(2001-02-03T04:05:06.789Z)');
expect(args).toStrictEqual({ key: new Date('2001-02-03T04:05:06.789Z') });
});
it('parses Date with timezone offset', () => {
const args = parseArgsParam('key:!date(2001-02-03T04:05:06.789+09:00)');
expect(args).toStrictEqual({ key: new Date('2001-02-03T04:05:06.789+09:00') });
});
it('parses Date without timezone', () => {
const args = parseArgsParam('key:!date(2001-02-03T04:05:06.789)');
expect(args).toStrictEqual({ key: expect.any(Date) }); // depends on local timezone
});
it('parses Date without second fraction', () => {
const args = parseArgsParam('key:!date(2001-02-03T04:05:06Z)');
expect(args).toStrictEqual({ key: new Date('2001-02-03T04:05:06.000Z') });
});
it('parses Date without time', () => {
const args = parseArgsParam('key:!date(2001-02-03)');
expect(args).toStrictEqual({ key: expect.any(Date) }); // depends on local timezone
});
it('does not parse Date without prefix', () => {
const args = parseArgsParam('key:2001-02-03T04:05:06.789Z');
expect(args).toStrictEqual({});
});
it('parses multiple values', () => {
const args = parseArgsParam('one:A;two:B;three:C');
expect(args).toStrictEqual({ one: 'A', two: 'B', three: 'C' });
});
it('parses arrays', () => {
const args = parseArgsParam('arr[]:A;arr[]:B;arr[]:C');
expect(args).toStrictEqual({ arr: ['A', 'B', 'C'] });
});
it('parses arrays with indices', () => {
const args = parseArgsParam('arr[0]:A;arr[1]:B;arr[2]:C');
expect(args).toStrictEqual({ arr: ['A', 'B', 'C'] });
});
it('parses sparse arrays', () => {
const args = parseArgsParam('arr[0]:A;arr[2]:C');
// eslint-disable-next-line no-sparse-arrays
expect(args).toStrictEqual({ arr: ['A', , 'C'] });
});
it('parses repeated values as arrays', () => {
const args = parseArgsParam('arr:A;arr:B;arr:C');
expect(args).toStrictEqual({ arr: ['A', 'B', 'C'] });
});
it('parses simple objects', () => {
const args = parseArgsParam('obj.one:A;obj.two:B');
expect(args).toStrictEqual({ obj: { one: 'A', two: 'B' } });
});
it('parses nested objects', () => {
const args = parseArgsParam('obj.foo.one:A;obj.foo.two:B;obj.bar.one:A');
expect(args).toStrictEqual({ obj: { foo: { one: 'A', two: 'B' }, bar: { one: 'A' } } });
});
it('parses arrays in objects', () => {
expect(parseArgsParam('obj.foo[]:A;obj.foo[]:B')).toStrictEqual({ obj: { foo: ['A', 'B'] } });
expect(parseArgsParam('obj.foo[0]:A;obj.foo[1]:B')).toStrictEqual({ obj: { foo: ['A', 'B'] } });
// eslint-disable-next-line no-sparse-arrays
expect(parseArgsParam('obj.foo[1]:B')).toStrictEqual({ obj: { foo: [, 'B'] } });
expect(parseArgsParam('obj.foo:A;obj.foo:B')).toStrictEqual({ obj: { foo: ['A', 'B'] } });
});
it('parses single object in array', () => {
const args = parseArgsParam('arr[].one:A;arr[].two:B');
expect(args).toStrictEqual({ arr: [{ one: 'A', two: 'B' }] });
});
it('parses multiple objects in array', () => {
expect(parseArgsParam('arr[0].key:A;arr[1].key:B')).toStrictEqual({
arr: [{ key: 'A' }, { key: 'B' }],
});
expect(parseArgsParam('arr[0][key]:A;arr[1][key]:B')).toStrictEqual({
arr: [{ key: 'A' }, { key: 'B' }],
});
});
it('parses nested object in array', () => {
expect(parseArgsParam('arr[].foo.bar:val')).toStrictEqual({ arr: [{ foo: { bar: 'val' } }] });
expect(parseArgsParam('arr[][foo][bar]:val')).toStrictEqual({ arr: [{ foo: { bar: 'val' } }] });
});
describe('key sanitization', () => {
it("omits keys that aren't in the extended alphanumeric set", () => {
expect(parseArgsParam('a`b:val')).toStrictEqual({});
expect(parseArgsParam('a~b:val')).toStrictEqual({});
expect(parseArgsParam('a!b:val')).toStrictEqual({});
expect(parseArgsParam('a@b:val')).toStrictEqual({});
expect(parseArgsParam('a#b:val')).toStrictEqual({});
expect(parseArgsParam('a$b:val')).toStrictEqual({});
expect(parseArgsParam('a%b:val')).toStrictEqual({});
expect(parseArgsParam('a^b:val')).toStrictEqual({});
expect(parseArgsParam('a&b:val')).toStrictEqual({});
expect(parseArgsParam('a*b:val')).toStrictEqual({});
expect(parseArgsParam('a(b:val')).toStrictEqual({});
expect(parseArgsParam('a)b:val')).toStrictEqual({});
expect(parseArgsParam('a=b:val')).toStrictEqual({});
expect(parseArgsParam('"b":val')).toStrictEqual({});
expect(parseArgsParam('a/b:val')).toStrictEqual({});
expect(parseArgsParam('a\\b:val')).toStrictEqual({});
expect(parseArgsParam('a|b:val')).toStrictEqual({});
expect(parseArgsParam('a[b:val')).toStrictEqual({});
expect(parseArgsParam('a]b:val')).toStrictEqual({});
expect(parseArgsParam('a{b:val')).toStrictEqual({});
expect(parseArgsParam('a}b:val')).toStrictEqual({});
expect(parseArgsParam('a?b:val')).toStrictEqual({});
expect(parseArgsParam('a<b:val')).toStrictEqual({});
expect(parseArgsParam('a>b:val')).toStrictEqual({});
expect(parseArgsParam('a,b:val')).toStrictEqual({});
});
it('allows keys that are in the extended alphanumeric set', () => {
expect(parseArgsParam(' key :val')).toStrictEqual({ ' key ': 'val' });
expect(parseArgsParam('+key+:val')).toStrictEqual({ ' key ': 'val' });
expect(parseArgsParam('-key-:val')).toStrictEqual({ '-key-': 'val' });
expect(parseArgsParam('_key_:val')).toStrictEqual({ _key_: 'val' });
expect(parseArgsParam('KEY123:val')).toStrictEqual({ KEY123: 'val' });
expect(parseArgsParam('1:val')).toStrictEqual({ '1': 'val' });
});
it('also applies to nested object keys', () => {
expect(parseArgsParam('obj.a!b:val')).toStrictEqual({});
expect(parseArgsParam('obj[a!b]:val')).toStrictEqual({});
expect(parseArgsParam('arr[][a!b]:val')).toStrictEqual({});
expect(parseArgsParam('arr[0][a!b]:val')).toStrictEqual({});
});
it('completely omits an arg when a (deeply) nested key is invalid', () => {
expect(parseArgsParam('obj.foo.a!b:val;obj.foo.bar:val;obj.baz:val')).toStrictEqual({});
expect(parseArgsParam('obj.foo[][a!b]:val;obj.foo.bar:val;obj.baz:val')).toStrictEqual({});
expect(parseArgsParam('obj.foo.a!b:val;key:val')).toStrictEqual({ key: 'val' });
});
});
describe('value sanitization', () => {
it("omits values that aren't in the extended alphanumeric set", () => {
expect(parseArgsParam('key:a`b')).toStrictEqual({});
expect(parseArgsParam('key:a~b')).toStrictEqual({});
expect(parseArgsParam('key:a!b')).toStrictEqual({});
expect(parseArgsParam('key:a@b')).toStrictEqual({});
expect(parseArgsParam('key:a#b')).toStrictEqual({});
expect(parseArgsParam('key:a$b')).toStrictEqual({});
expect(parseArgsParam('key:a%b')).toStrictEqual({});
expect(parseArgsParam('key:a^b')).toStrictEqual({});
expect(parseArgsParam('key:a&b')).toStrictEqual({});
expect(parseArgsParam('key:a*b')).toStrictEqual({});
expect(parseArgsParam('key:a(b')).toStrictEqual({});
expect(parseArgsParam('key:a)b')).toStrictEqual({});
expect(parseArgsParam('key:a=b')).toStrictEqual({});
expect(parseArgsParam('key:a[b')).toStrictEqual({});
expect(parseArgsParam('key:a]b')).toStrictEqual({});
expect(parseArgsParam('key:a{b')).toStrictEqual({});
expect(parseArgsParam('key:a}b')).toStrictEqual({});
expect(parseArgsParam('key:a\\b')).toStrictEqual({});
expect(parseArgsParam('key:a|b')).toStrictEqual({});
expect(parseArgsParam("key:a'b")).toStrictEqual({});
expect(parseArgsParam('key:a"b')).toStrictEqual({});
expect(parseArgsParam('key:a,b')).toStrictEqual({});
expect(parseArgsParam('key:a.b')).toStrictEqual({});
expect(parseArgsParam('key:a<b')).toStrictEqual({});
expect(parseArgsParam('key:a>b')).toStrictEqual({});
expect(parseArgsParam('key:a/b')).toStrictEqual({});
expect(parseArgsParam('key:a?b')).toStrictEqual({});
});
it('allows values that are in the extended alphanumeric set', () => {
expect(parseArgsParam('key: val ')).toStrictEqual({ key: ' val ' });
expect(parseArgsParam('key:+val+')).toStrictEqual({ key: ' val ' });
expect(parseArgsParam('key:_val_')).toStrictEqual({ key: '_val_' });
expect(parseArgsParam('key:-val-')).toStrictEqual({ key: '-val-' });
expect(parseArgsParam('key:VAL123')).toStrictEqual({ key: 'VAL123' });
});
it('allows and parses valid (fractional) numbers', () => {
expect(parseArgsParam('key:1')).toStrictEqual({ key: 1 });
expect(parseArgsParam('key:1.2')).toStrictEqual({ key: 1.2 });
expect(parseArgsParam('key:-1.2')).toStrictEqual({ key: -1.2 });
expect(parseArgsParam('key:1.')).toStrictEqual({});
expect(parseArgsParam('key:.2')).toStrictEqual({});
expect(parseArgsParam('key:1.2.3')).toStrictEqual({});
});
it('also applies to nested object and array values', () => {
expect(parseArgsParam('obj.key:a!b')).toStrictEqual({});
expect(parseArgsParam('obj[key]:a!b')).toStrictEqual({});
expect(parseArgsParam('arr[][key]:a!b')).toStrictEqual({});
expect(parseArgsParam('arr[0][key]:a!b')).toStrictEqual({});
expect(parseArgsParam('arr[]:a!b')).toStrictEqual({});
expect(parseArgsParam('arr[0]:a!b')).toStrictEqual({});
});
it('completely omits an arg when a (deeply) nested value is invalid', () => {
expect(parseArgsParam('obj.key:a!b;obj.foo:val;obj.bar.baz:val')).toStrictEqual({});
expect(parseArgsParam('obj.arr[]:a!b;obj.foo:val;obj.bar.baz:val')).toStrictEqual({});
expect(parseArgsParam('obj.arr[0]:val;obj.arr[1]:a!b;obj.foo:val')).toStrictEqual({});
expect(parseArgsParam('obj.arr[][one]:a!b;obj.arr[][two]:val')).toStrictEqual({});
expect(parseArgsParam('arr[]:val;arr[]:a!b;key:val')).toStrictEqual({ key: 'val' });
expect(parseArgsParam('arr[0]:val;arr[1]:a!1;key:val')).toStrictEqual({ key: 'val' });
expect(parseArgsParam('arr[0]:val;arr[2]:a!1;key:val')).toStrictEqual({ key: 'val' });
});
});
});
|
1,147 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/preview-web/simulate-pageload.test.ts | /**
* @jest-environment jsdom
*/
import { global } from '@storybook/global';
import { simulatePageLoad } from './simulate-pageload';
const { document } = global;
describe('simulatePageLoad', () => {
it('should add script with type module to scripts root', () => {
const container = document.createElement('div');
const script = document.createElement('script');
script.type = 'module';
container.appendChild(script);
simulatePageLoad(container);
expect(document.body.innerHTML).toEqual(
'<div id="scripts-root"><script type="module"></script></div>'
);
});
it('should add script with proper mime type to scripts root', () => {
const container = document.createElement('div');
const script = document.createElement('script');
script.type = 'application/javascript';
container.appendChild(script);
simulatePageLoad(container);
expect(document.body.innerHTML).toEqual(
'<div id="scripts-root"><script type="text/javascript"></script></div>'
);
});
it('should add script without type to scripts root', () => {
const container = document.createElement('div');
const script = document.createElement('script');
container.appendChild(script);
simulatePageLoad(container);
expect(document.body.innerHTML).toEqual(
'<div id="scripts-root"><script type="text/javascript"></script></div>'
);
});
});
|
1,149 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/preview-web | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/preview-web/docs-context/DocsContext.test.ts | import { Channel } from '@storybook/channels';
import type { CSFFile, Renderer } from '@storybook/types';
import type { StoryStore } from '../../store';
import { DocsContext } from './DocsContext';
import { csfFileParts } from './test-utils';
const channel = new Channel({});
const renderStoryToElement = jest.fn();
describe('referenceCSFFile', () => {
it('deals with unattached "docsOnly" csf files', () => {
const unattachedCsfFile = {
stories: {
'meta--page': {
id: 'meta--page',
name: 'Page',
parameters: { docsOnly: true },
moduleExport: {},
},
},
meta: { id: 'meta', title: 'Meta' },
moduleExports: {},
} as CSFFile;
const store = {
componentStoriesFromCSFFile: () => [],
} as unknown as StoryStore<Renderer>;
const context = new DocsContext(channel, store, renderStoryToElement, [unattachedCsfFile]);
expect(() => context.storyById()).toThrow(/No primary story/);
});
});
describe('resolveOf', () => {
const { story, csfFile, storyExport, metaExport, moduleExports, component } = csfFileParts();
describe('attached', () => {
const projectAnnotations = { render: jest.fn() };
const store = {
componentStoriesFromCSFFile: () => [story],
preparedMetaFromCSFFile: () => ({ prepareMeta: 'preparedMeta' }),
projectAnnotations,
} as unknown as StoryStore<Renderer>;
const context = new DocsContext(channel, store, renderStoryToElement, [csfFile]);
context.attachCSFFile(csfFile);
it('works for story exports', () => {
expect(context.resolveOf(storyExport)).toEqual({ type: 'story', story });
});
it('works for meta exports', () => {
expect(context.resolveOf(metaExport)).toEqual({
type: 'meta',
csfFile,
preparedMeta: expect.any(Object),
});
});
it('works for full module exports', () => {
expect(context.resolveOf(moduleExports)).toEqual({
type: 'meta',
csfFile,
preparedMeta: expect.any(Object),
});
});
it('works for components', () => {
expect(context.resolveOf(component)).toEqual({
type: 'component',
component,
projectAnnotations: expect.objectContaining(projectAnnotations),
});
});
it('finds primary story', () => {
expect(context.resolveOf('story')).toEqual({ type: 'story', story });
});
it('finds attached CSF file', () => {
expect(context.resolveOf('meta')).toEqual({
type: 'meta',
csfFile,
preparedMeta: expect.any(Object),
});
});
it('finds attached component', () => {
expect(context.resolveOf('component')).toEqual({
type: 'component',
component,
projectAnnotations: expect.objectContaining(projectAnnotations),
});
});
describe('validation allowed', () => {
it('works for story exports', () => {
expect(context.resolveOf(storyExport, ['story'])).toEqual({ type: 'story', story });
});
it('works for meta exports', () => {
expect(context.resolveOf(metaExport, ['meta'])).toEqual({
type: 'meta',
csfFile,
preparedMeta: expect.any(Object),
});
});
it('works for full module exports', () => {
expect(context.resolveOf(moduleExports, ['meta'])).toEqual({
type: 'meta',
csfFile,
preparedMeta: expect.any(Object),
});
});
it('works for components', () => {
expect(context.resolveOf(component, ['component'])).toEqual({
type: 'component',
component,
projectAnnotations: expect.objectContaining(projectAnnotations),
});
});
it('finds primary story', () => {
expect(context.resolveOf('story', ['story'])).toEqual({ type: 'story', story });
});
it('finds attached CSF file', () => {
expect(context.resolveOf('meta', ['meta'])).toEqual({
type: 'meta',
csfFile,
preparedMeta: expect.any(Object),
});
});
it('finds attached component', () => {
expect(context.resolveOf('component', ['component'])).toEqual({
type: 'component',
component,
projectAnnotations: expect.objectContaining(projectAnnotations),
});
});
});
describe('validation rejected', () => {
it('works for story exports', () => {
expect(() => context.resolveOf(storyExport, ['meta'])).toThrow('Invalid value passed');
});
it('works for meta exports', () => {
expect(() => context.resolveOf(metaExport, ['story'])).toThrow('Invalid value passed');
});
it('works for full module exports', () => {
expect(() => context.resolveOf(moduleExports, ['story'])).toThrow('Invalid value passed');
});
it('works for components', () => {
expect(() => context.resolveOf(component, ['story', 'meta'])).toThrow(
'Invalid value passed'
);
});
it('finds primary story', () => {
expect(() => context.resolveOf('story', ['component'])).toThrow('Invalid value passed');
});
it('finds attached CSF file', () => {
expect(() => context.resolveOf('meta', ['story'])).toThrow('Invalid value passed');
});
it('finds attached component', () => {
expect(() => context.resolveOf('component', ['meta'])).toThrow('Invalid value passed');
});
});
});
describe('unattached', () => {
const projectAnnotations = { render: jest.fn() };
const store = {
componentStoriesFromCSFFile: () => [story],
preparedMetaFromCSFFile: () => ({ prepareMeta: 'preparedMeta' }),
projectAnnotations,
} as unknown as StoryStore<Renderer>;
const context = new DocsContext(channel, store, renderStoryToElement, [csfFile]);
it('works for story exports', () => {
expect(context.resolveOf(storyExport)).toEqual({ type: 'story', story });
});
it('works for meta exports', () => {
expect(context.resolveOf(metaExport)).toEqual({
type: 'meta',
csfFile,
preparedMeta: expect.any(Object),
});
});
it('works for full module exports', () => {
expect(context.resolveOf(moduleExports)).toEqual({
type: 'meta',
csfFile,
preparedMeta: expect.any(Object),
});
});
it('works for components', () => {
expect(context.resolveOf(component)).toEqual({
type: 'component',
component,
projectAnnotations: expect.objectContaining(projectAnnotations),
});
});
it('throws for primary story', () => {
expect(() => context.resolveOf('story')).toThrow('No primary story attached');
});
it('throws for attached CSF file', () => {
expect(() => context.resolveOf('meta')).toThrow('No CSF file attached');
});
it('throws for attached component', () => {
expect(() => context.resolveOf('component')).toThrow('No CSF file attached');
});
});
});
|
1,154 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/preview-web | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/preview-web/render/CsfDocsRender.test.ts | import { Channel } from '@storybook/channels';
import type { Renderer, DocsIndexEntry, RenderContextCallbacks } from '@storybook/types';
import type { StoryStore } from '../../store';
import { PREPARE_ABORTED } from './Render';
import { CsfDocsRender } from './CsfDocsRender';
import { csfFileParts } from '../docs-context/test-utils';
const entry = {
type: 'docs',
id: 'component--docs',
name: 'Docs',
title: 'Component',
importPath: './Component.stories.ts',
storiesImports: [],
tags: ['autodocs'],
} as DocsIndexEntry;
const createGate = (): [Promise<any | undefined>, (_?: any) => void] => {
let openGate = (_?: any) => {};
const gate = new Promise<any | undefined>((resolve) => {
openGate = resolve;
});
return [gate, openGate];
};
it('throws PREPARE_ABORTED if torndown during prepare', async () => {
const [importGate, openImportGate] = createGate();
const mockStore = {
loadEntry: jest.fn(async () => {
await importGate;
return {};
}),
};
const render = new CsfDocsRender(
new Channel({}),
mockStore as unknown as StoryStore<Renderer>,
entry,
{} as RenderContextCallbacks<Renderer>
);
const preparePromise = render.prepare();
render.teardown();
openImportGate();
await expect(preparePromise).rejects.toThrowError(PREPARE_ABORTED);
});
it('attached immediately', async () => {
const { story, csfFile, moduleExports } = csfFileParts();
const store = {
loadEntry: () => ({
entryExports: moduleExports,
csfFiles: [],
}),
processCSFFileWithCache: () => csfFile,
componentStoriesFromCSFFile: () => [story],
storyFromCSFFile: () => story,
} as unknown as StoryStore<Renderer>;
const render = new CsfDocsRender(
new Channel({}),
store,
entry,
{} as RenderContextCallbacks<Renderer>
);
await render.prepare();
const context = render.docsContext(jest.fn());
expect(context.storyById()).toEqual(story);
});
|
1,156 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/preview-web | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/preview-web/render/MdxDocsRender.test.ts | import { Channel } from '@storybook/channels';
import type { Renderer, DocsIndexEntry, RenderContextCallbacks } from '@storybook/types';
import type { StoryStore } from '../../store';
import { PREPARE_ABORTED } from './Render';
import { MdxDocsRender } from './MdxDocsRender';
import { csfFileParts } from '../docs-context/test-utils';
const entry = {
type: 'docs',
id: 'introduction--docs',
name: 'Docs',
title: 'Introduction',
importPath: './Introduction.mdx',
storiesImports: [],
} as DocsIndexEntry;
const createGate = (): [Promise<any | undefined>, (_?: any) => void] => {
let openGate = (_?: any) => {};
const gate = new Promise<any | undefined>((resolve) => {
openGate = resolve;
});
return [gate, openGate];
};
it('throws PREPARE_ABORTED if torndown during prepare', async () => {
const [importGate, openImportGate] = createGate();
const mockStore = {
loadEntry: jest.fn(async () => {
await importGate;
return {};
}),
};
const render = new MdxDocsRender(
new Channel({}),
mockStore as unknown as StoryStore<Renderer>,
entry,
{} as RenderContextCallbacks<Renderer>
);
const preparePromise = render.prepare();
render.teardown();
openImportGate();
await expect(preparePromise).rejects.toThrowError(PREPARE_ABORTED);
});
describe('attaching', () => {
const { story, csfFile, moduleExports } = csfFileParts();
const store = {
loadEntry: () => ({
entryExports: moduleExports,
csfFiles: [csfFile],
}),
processCSFFileWithCache: () => csfFile,
componentStoriesFromCSFFile: () => [story],
storyFromCSFFile: () => story,
} as unknown as StoryStore<Renderer>;
it('is not attached if you do not call setMeta', async () => {
const render = new MdxDocsRender(
new Channel({}),
store,
entry,
{} as RenderContextCallbacks<Renderer>
);
await render.prepare();
const context = render.docsContext(jest.fn());
expect(context.storyById).toThrow('No primary story defined');
});
it('is attached if you call referenceMeta with attach=true', async () => {
const render = new MdxDocsRender(
new Channel({}),
store,
entry,
{} as RenderContextCallbacks<Renderer>
);
await render.prepare();
const context = render.docsContext(jest.fn());
context.referenceMeta(moduleExports, true);
expect(context.storyById()).toEqual(story);
});
});
|
1,159 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/preview-web | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/preview-web/render/StoryRender.test.ts | import { Channel } from '@storybook/channels';
import type { Renderer, StoryIndexEntry } from '@storybook/types';
import type { StoryStore } from '../../store';
import { PREPARE_ABORTED } from './Render';
import { StoryRender } from './StoryRender';
const entry = {
type: 'story',
id: 'component--a',
name: 'A',
title: 'component',
importPath: './component.stories.ts',
} as StoryIndexEntry;
const createGate = (): [Promise<any | undefined>, (_?: any) => void] => {
let openGate = (_?: any) => {};
const gate = new Promise<any | undefined>((resolve) => {
openGate = resolve;
});
return [gate, openGate];
};
describe('StoryRender', () => {
it('throws PREPARE_ABORTED if torndown during prepare', async () => {
const [importGate, openImportGate] = createGate();
const mockStore = {
loadStory: jest.fn(async () => {
await importGate;
return {};
}),
cleanupStory: jest.fn(),
};
const render = new StoryRender(
new Channel({}),
mockStore as unknown as StoryStore<Renderer>,
jest.fn(),
{} as any,
entry.id,
'story'
);
const preparePromise = render.prepare();
render.teardown();
openImportGate();
await expect(preparePromise).rejects.toThrowError(PREPARE_ABORTED);
});
it('does run play function if passed autoplay=true', async () => {
const story = {
id: 'id',
title: 'title',
name: 'name',
tags: [],
applyLoaders: jest.fn(),
unboundStoryFn: jest.fn(),
playFunction: jest.fn(),
prepareContext: jest.fn(),
};
const render = new StoryRender(
new Channel({}),
{ getStoryContext: () => ({}) } as any,
jest.fn() as any,
{} as any,
entry.id,
'story',
{ autoplay: true },
story as any
);
await render.renderToElement({} as any);
expect(story.playFunction).toHaveBeenCalled();
});
it('does not run play function if passed autoplay=false', async () => {
const story = {
id: 'id',
title: 'title',
name: 'name',
tags: [],
applyLoaders: jest.fn(),
unboundStoryFn: jest.fn(),
playFunction: jest.fn(),
prepareContext: jest.fn(),
};
const render = new StoryRender(
new Channel({}),
{ getStoryContext: () => ({}) } as any,
jest.fn() as any,
{} as any,
entry.id,
'story',
{ autoplay: false },
story as any
);
await render.renderToElement({} as any);
expect(story.playFunction).not.toHaveBeenCalled();
});
});
|
1,161 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/ArgsStore.test.ts | import { expect } from '@jest/globals';
import { ArgsStore } from './ArgsStore';
jest.mock('@storybook/client-logger');
const stringType = { type: { name: 'string' } };
const booleanType = { type: { name: 'boolean' } };
describe('ArgsStore', () => {
describe('setInitial / get', () => {
it('returns in a straightforward way', () => {
const store = new ArgsStore();
store.setInitial({ id: 'id', initialArgs: { foo: 'bar' } } as any);
expect(store.get('id')).toEqual({ foo: 'bar' });
});
it('throws if you try to get non-existent', () => {
const store = new ArgsStore();
expect(() => store.get('id')).toThrow(/No args known/);
});
describe('on second call for same story', () => {
describe('if initialArgs are unchanged', () => {
it('does nothing if the args are untouched', () => {
const store = new ArgsStore();
const previousStory = {
id: 'id',
initialArgs: { a: '1', b: '1' },
argTypes: { a: stringType, b: stringType },
} as any;
store.setInitial(previousStory);
const story = {
id: 'id',
initialArgs: { a: '1', b: '1' },
argTypes: { a: stringType, b: stringType },
} as any;
store.setInitial(story);
expect(store.get(story.id)).toEqual({ a: '1', b: '1' });
});
it('retains any arg changes', () => {
const store = new ArgsStore();
const previousStory = {
id: 'id',
initialArgs: { a: '1', b: false, c: 'unchanged' },
argTypes: { a: stringType, b: booleanType, c: stringType },
} as any;
store.setInitial(previousStory);
// NOTE: I'm not sure technically you should be allowed to set d here, but
// let's make sure we behave sensibly if you do
store.update('id', { a: 'update', b: true, d: 'update' });
const story = {
id: 'id',
initialArgs: { a: '1', b: false, c: 'unchanged' },
argTypes: { a: stringType, b: booleanType, c: stringType },
} as any;
store.setInitial(story);
// In any case c is not retained.
expect(store.get(story.id)).toEqual({ a: 'update', b: true, c: 'unchanged' });
});
});
describe('when initialArgs change', () => {
it('replaces old args with new if the args are untouched', () => {
const store = new ArgsStore();
const previousStory = {
id: 'id',
initialArgs: { a: '1', b: '1' },
argTypes: { a: stringType, b: stringType },
} as any;
store.setInitial(previousStory);
const story = {
id: 'id',
initialArgs: { a: '1', c: '1' },
argTypes: { a: stringType, c: stringType },
} as any;
store.setInitial(story);
expect(store.get(story.id)).toEqual({ a: '1', c: '1' });
});
it('applies the same delta if the args are changed', () => {
const store = new ArgsStore();
const previousStory = {
id: 'id',
initialArgs: { a: '1', b: '1' },
argTypes: { a: stringType, b: stringType },
} as any;
store.setInitial(previousStory);
// NOTE: I'm not sure technically you should be allowed to set c here
store.update('id', { a: 'update', c: 'update' });
const story = {
id: 'id',
initialArgs: { a: '2', d: '2' },
argTypes: { a: stringType, d: stringType },
} as any;
store.setInitial(story);
// In any case c is not retained.
expect(store.get(story.id)).toEqual({ a: 'update', d: '2' });
});
});
});
});
describe('update', () => {
it('overrides on a per-key basis', () => {
const store = new ArgsStore();
store.setInitial({ id: 'id', initialArgs: {} } as any);
store.update('id', { foo: 'bar' });
expect(store.get('id')).toEqual({ foo: 'bar' });
store.update('id', { baz: 'bing' });
expect(store.get('id')).toEqual({ foo: 'bar', baz: 'bing' });
});
it('does not merge objects', () => {
const store = new ArgsStore();
store.setInitial({ id: 'id', initialArgs: {} } as any);
store.update('id', { obj: { foo: 'bar' } });
expect(store.get('id')).toEqual({ obj: { foo: 'bar' } });
store.update('id', { obj: { baz: 'bing' } });
expect(store.get('id')).toEqual({ obj: { baz: 'bing' } });
});
it('does not set keys to undefined, it simply unsets them', () => {
const store = new ArgsStore();
store.setInitial({ id: 'id', initialArgs: { foo: 'bar' } } as any);
store.update('id', { foo: undefined });
expect('foo' in store.get('id')).toBe(false);
});
});
describe('updateFromPersisted', () => {
it('ensures the types of args are correct', () => {
const store = new ArgsStore();
store.setInitial({ id: 'id', initialArgs: {} } as any);
const story = {
id: 'id',
argTypes: { a: stringType },
} as any;
store.updateFromPersisted(story, { a: 'str' });
expect(store.get('id')).toEqual({ a: 'str' });
store.updateFromPersisted(story, { a: 42 });
expect(store.get('id')).toEqual({ a: '42' });
});
it('merges objects and sparse arrays', () => {
const store = new ArgsStore();
store.setInitial({ id: 'id', initialArgs: { a: { foo: 'bar' }, b: ['1', '2', '3'] } } as any);
const story = {
id: 'id',
argTypes: {
a: { type: { name: 'object', value: { name: 'string' } } },
b: { type: { name: 'array', value: { name: 'string' } } },
},
} as any;
store.updateFromPersisted(story, { a: { baz: 'bing' } });
expect(store.get('id')).toEqual({
a: { foo: 'bar', baz: 'bing' },
b: ['1', '2', '3'],
});
// eslint-disable-next-line no-sparse-arrays
store.updateFromPersisted(story, { b: [, , '4'] });
expect(store.get('id')).toEqual({
a: { foo: 'bar', baz: 'bing' },
b: ['1', '2', '4'],
});
});
it('checks args are allowed options', () => {
const store = new ArgsStore();
store.setInitial({ id: 'id', initialArgs: {} } as any);
const story = {
id: 'id',
argTypes: { a: { type: { name: 'string' }, options: ['a', 'b'] } },
} as any;
store.updateFromPersisted(story, { a: 'random' });
expect(store.get('id')).toEqual({});
store.updateFromPersisted(story, { a: 'a' });
expect(store.get('id')).toEqual({ a: 'a' });
});
});
});
|
1,163 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/GlobalsStore.test.ts | import { expect } from '@jest/globals';
import { GlobalsStore } from './GlobalsStore';
jest.mock('@storybook/client-logger', () => ({
logger: {
warn: jest.fn(),
},
}));
describe('GlobalsStore', () => {
it('is initialized to the value in globals', () => {
const store = new GlobalsStore({
globals: {
arg1: 'arg1',
arg2: 2,
arg3: { complex: { object: ['type'] } },
},
globalTypes: {},
});
expect(store.get()).toEqual({
arg1: 'arg1',
arg2: 2,
arg3: { complex: { object: ['type'] } },
});
});
it('is initialized to the default values from globalTypes if global is unset', () => {
const store = new GlobalsStore({
globals: {
arg1: 'arg1',
arg2: 2,
},
globalTypes: {
arg2: { defaultValue: 'arg2' },
arg3: { defaultValue: { complex: { object: ['type'] } } },
},
});
expect(store.get()).toEqual({
// NOTE: we keep arg1, even though it doesn't have a globalArgType
arg1: 'arg1',
arg2: 2,
arg3: { complex: { object: ['type'] } },
});
});
describe('update', () => {
it('changes the global args', () => {
const store = new GlobalsStore({ globals: { foo: 'old' }, globalTypes: { baz: {} } });
store.update({ foo: 'bar' });
expect(store.get()).toEqual({ foo: 'bar' });
store.update({ baz: 'bing' });
expect(store.get()).toEqual({ foo: 'bar', baz: 'bing' });
});
it('does not merge objects', () => {
const store = new GlobalsStore({
globals: { obj: { foo: 'old' } },
globalTypes: { baz: {} },
});
store.update({ obj: { foo: 'bar' } });
expect(store.get()).toEqual({ obj: { foo: 'bar' } });
store.update({ obj: { baz: 'bing' } });
expect(store.get()).toEqual({ obj: { baz: 'bing' } });
});
});
describe('updateFromPersisted', () => {
it('only sets values for which globals or globalArgs exist', () => {
const store = new GlobalsStore({
globals: {
arg1: 'arg1',
},
globalTypes: {
arg2: { defaultValue: 'arg2' },
},
});
store.updateFromPersisted({
arg1: 'new-arg1',
arg2: 'new-arg2',
arg3: 'new-arg3',
});
expect(store.get()).toEqual({ arg1: 'new-arg1', arg2: 'new-arg2' });
});
});
describe('second call to set', () => {
it('is initialized to the (new) default values from globalTypes if the (new) global is unset', () => {
const store = new GlobalsStore({ globals: {}, globalTypes: {} });
expect(store.get()).toEqual({});
store.set({
globals: {
arg1: 'arg1',
arg2: 2,
},
globalTypes: {
arg2: { defaultValue: 'arg2' },
arg3: { defaultValue: { complex: { object: ['type'] } } },
},
});
expect(store.get()).toEqual({
// NOTE: we keep arg1, even though it doesn't have a globalArgType
arg1: 'arg1',
arg2: 2,
arg3: { complex: { object: ['type'] } },
});
});
describe('when underlying globals have not changed', () => {
it('retains updated values, but not if they are undeclared', () => {
const store = new GlobalsStore({
globals: {
arg1: 'arg1',
arg2: 'arg2',
arg3: 'arg3',
},
globalTypes: {
arg2: { defaultValue: 'arg2' },
},
});
store.update({
arg1: 'new-arg1',
arg2: 'new-arg2',
arg3: 'new-arg3',
});
// You can set undeclared values (currently, deprecated)
expect(store.get()).toEqual({ arg1: 'new-arg1', arg2: 'new-arg2', arg3: 'new-arg3' });
store.set({
globals: {
arg1: 'arg1',
},
globalTypes: {
arg2: { defaultValue: 'arg2' },
},
});
// However undeclared valuse aren't persisted
expect(store.get()).toEqual({ arg1: 'new-arg1', arg2: 'new-arg2' });
});
});
describe('when underlying globals have changed', () => {
it('retains a the same delta', () => {
const store = new GlobalsStore({
globals: {
arg1: 'arg1',
arg2: 'arg1',
arg3: 'arg1',
arg4: 'arg4',
},
globalTypes: {
arg2: { defaultValue: 'arg2' },
},
});
store.update({
arg1: 'new-arg1',
arg2: 'new-arg2',
arg3: 'new-arg3',
});
expect(store.get()).toEqual({
arg1: 'new-arg1',
arg2: 'new-arg2',
// You can set undeclared values (currently, deprecated)
arg3: 'new-arg3',
arg4: 'arg4',
});
store.set({
globals: {
arg1: 'edited-arg1',
arg4: 'edited-arg4',
},
globalTypes: {
arg5: { defaultValue: 'edited-arg5' },
},
});
// However undeclared values aren't persisted
expect(store.get()).toEqual({
arg1: 'new-arg1',
arg4: 'edited-arg4',
arg5: 'edited-arg5',
});
});
});
});
});
|
1,165 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/StoryIndexStore.test.ts | import { expect } from '@jest/globals';
import type { StoryIndex } from '@storybook/types';
import { StoryIndexStore } from './StoryIndexStore';
jest.mock('@storybook/channel-websocket', () => () => ({ on: jest.fn() }));
const storyIndex: StoryIndex = {
v: 4,
entries: {
'component-one--a': {
type: 'story',
id: 'component-one--a',
title: 'Component One',
name: 'A',
importPath: './src/ComponentOne.stories.js',
},
'component-one--b': {
type: 'story',
id: 'component-one--b',
title: 'Component One',
name: 'B',
importPath: './src/ComponentOne.stories.js',
},
'component-two--c': {
type: 'story',
id: 'component-two--c',
title: 'Component Two',
name: 'C',
importPath: './src/ComponentTwo.stories.js',
},
},
};
const makeStoryIndex = (titlesAndNames: any) => {
return {
v: 4,
entries: Object.fromEntries(
titlesAndNames.map(([title, name]: [any, any]) => {
const id = `${title}--${name}`.replace('/', '-');
return [
id,
{
id,
title,
name,
importPath: `./src/${title}.stories.js`,
},
];
})
),
};
};
describe('StoryIndexStore', () => {
describe('entryFromSpecifier', () => {
describe('if you use *', () => {
it('selects the first story in the store', async () => {
const store = new StoryIndexStore(storyIndex);
expect(store.entryFromSpecifier('*')).toEqual(store.entries['component-one--a']);
});
it('selects nothing if there are no stories', async () => {
const store = new StoryIndexStore(makeStoryIndex([]));
expect(store.entryFromSpecifier('*')).toBeUndefined();
});
});
describe('if you use a component or group id', () => {
it('selects the first story for the component', async () => {
const store = new StoryIndexStore(storyIndex);
expect(store.entryFromSpecifier('component-two')).toEqual(
store.entries['component-two--c']
);
});
it('selects the first story for the group', async () => {
const store = new StoryIndexStore(
makeStoryIndex([
['g1/a', '1'],
['g2/a', '1'],
['g2/b', '1'],
])
);
expect(store.entryFromSpecifier('g2')).toEqual(store.entries['g2-a--1']);
});
// Making sure the fix #11571 doesn't break this
it('selects the first story if there are two stories in the group of different lengths', async () => {
const store = new StoryIndexStore(
makeStoryIndex([
['a', 'long-long-long'],
['a', 'short'],
])
);
expect(store.entryFromSpecifier('a')).toEqual(store.entries['a--long-long-long']);
});
it('selects nothing if the component or group does not exist', async () => {
const store = new StoryIndexStore(storyIndex);
expect(store.entryFromSpecifier('random')).toBeUndefined();
});
});
describe('if you use a storyId', () => {
it('selects a specific story', async () => {
const store = new StoryIndexStore(storyIndex);
expect(store.entryFromSpecifier('component-one--a')).toEqual(
store.entries['component-one--a']
);
});
it('selects nothing if you the story does not exist', async () => {
const store = new StoryIndexStore(storyIndex);
expect(store.entryFromSpecifier('component-one--c')).toBeUndefined();
});
// See #11571
it('does NOT select an earlier story that this story id is a prefix of', async () => {
const store = new StoryIndexStore(
makeStoryIndex([
['a', '31'],
['a', '3'],
])
);
expect(store.entryFromSpecifier('a--3')).toEqual(store.entries['a--3']);
});
});
describe('storyIdToEntry', () => {
it('works when the story exists', async () => {
const store = new StoryIndexStore(storyIndex);
expect(store.storyIdToEntry('component-one--a')).toEqual(
storyIndex.entries['component-one--a']
);
expect(store.storyIdToEntry('component-one--b')).toEqual(
storyIndex.entries['component-one--b']
);
expect(store.storyIdToEntry('component-two--c')).toEqual(
storyIndex.entries['component-two--c']
);
});
it('throws when the story does not', async () => {
const store = new StoryIndexStore(storyIndex);
expect(() => store.storyIdToEntry('random')).toThrow(
/Couldn't find story matching id 'random'/
);
});
});
});
describe('importPathToEntry', () => {
it('works', () => {
const store = new StoryIndexStore(storyIndex);
expect(store.importPathToEntry('./src/ComponentOne.stories.js')).toEqual(
storyIndex.entries['component-one--a']
);
expect(store.importPathToEntry('./src/ComponentTwo.stories.js')).toEqual(
storyIndex.entries['component-two--c']
);
});
});
});
|
1,167 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/StoryStore.test.ts | import type { Renderer, ProjectAnnotations, StoryIndex } from '@storybook/types';
import { expect } from '@jest/globals';
import { prepareStory } from './csf/prepareStory';
import { processCSFFile } from './csf/processCSFFile';
import { StoryStore } from './StoryStore';
import type { HooksContext } from './hooks';
// Spy on prepareStory/processCSFFile
jest.mock('./csf/prepareStory', () => ({
...jest.requireActual('./csf/prepareStory'),
prepareStory: jest.fn(jest.requireActual('./csf/prepareStory').prepareStory),
}));
jest.mock('./csf/processCSFFile', () => ({
processCSFFile: jest.fn(jest.requireActual('./csf/processCSFFile').processCSFFile),
}));
jest.mock('@storybook/global', () => ({
global: {
...(jest.requireActual('@storybook/global') as any),
},
}));
const createGate = (): [Promise<any | undefined>, (_?: any) => void] => {
let openGate = (_?: any) => {};
const gate = new Promise<any | undefined>((resolve) => {
openGate = resolve;
});
return [gate, openGate];
};
const componentOneExports = {
default: { title: 'Component One' },
a: { args: { foo: 'a' } },
b: { args: { foo: 'b' } },
};
const componentTwoExports = {
default: { title: 'Component Two' },
c: { args: { foo: 'c' } },
};
const importFn = jest.fn(async (path) => {
return path === './src/ComponentOne.stories.js' ? componentOneExports : componentTwoExports;
});
const projectAnnotations: ProjectAnnotations<any> = {
globals: { a: 'b' },
globalTypes: { a: { type: 'string' } },
argTypes: { a: { type: 'string' } },
render: jest.fn(),
};
const storyIndex: StoryIndex = {
v: 4,
entries: {
'component-one--a': {
type: 'story',
id: 'component-one--a',
title: 'Component One',
name: 'A',
importPath: './src/ComponentOne.stories.js',
},
'component-one--b': {
type: 'story',
id: 'component-one--b',
title: 'Component One',
name: 'B',
importPath: './src/ComponentOne.stories.js',
},
'component-two--c': {
type: 'story',
id: 'component-two--c',
title: 'Component Two',
name: 'C',
importPath: './src/ComponentTwo.stories.js',
},
},
};
describe('StoryStore', () => {
describe('projectAnnotations', () => {
it('normalizes on initialization', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
expect(store.projectAnnotations!.globalTypes).toEqual({
a: { name: 'a', type: { name: 'string' } },
});
expect(store.projectAnnotations!.argTypes).toEqual({
a: { name: 'a', type: { name: 'string' } },
});
});
it('normalizes on updateGlobalAnnotations', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
store.setProjectAnnotations(projectAnnotations);
expect(store.projectAnnotations!.globalTypes).toEqual({
a: { name: 'a', type: { name: 'string' } },
});
expect(store.projectAnnotations!.argTypes).toEqual({
a: { name: 'a', type: { name: 'string' } },
});
});
});
describe('loadStory', () => {
it('pulls the story via the importFn', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
importFn.mockClear();
expect(await store.loadStory({ storyId: 'component-one--a' })).toMatchObject({
id: 'component-one--a',
name: 'A',
title: 'Component One',
initialArgs: { foo: 'a' },
});
expect(importFn).toHaveBeenCalledWith('./src/ComponentOne.stories.js');
});
it('uses a cache', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
const story = await store.loadStory({ storyId: 'component-one--a' });
expect(processCSFFile).toHaveBeenCalledTimes(1);
expect(prepareStory).toHaveBeenCalledTimes(1);
// We are intentionally checking exact equality here, we need the object to be identical
expect(await store.loadStory({ storyId: 'component-one--a' })).toBe(story);
expect(processCSFFile).toHaveBeenCalledTimes(1);
expect(prepareStory).toHaveBeenCalledTimes(1);
await store.loadStory({ storyId: 'component-one--b' });
expect(processCSFFile).toHaveBeenCalledTimes(1);
expect(prepareStory).toHaveBeenCalledTimes(2);
await store.loadStory({ storyId: 'component-two--c' });
expect(processCSFFile).toHaveBeenCalledTimes(2);
expect(prepareStory).toHaveBeenCalledTimes(3);
});
describe('if the store is not yet initialized', () => {
it('waits for initialization', async () => {
const store = new StoryStore();
importFn.mockClear();
const loadPromise = store.loadStory({ storyId: 'component-one--a' });
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
expect(await loadPromise).toMatchObject({
id: 'component-one--a',
name: 'A',
title: 'Component One',
initialArgs: { foo: 'a' },
});
expect(importFn).toHaveBeenCalledWith('./src/ComponentOne.stories.js');
});
});
});
describe('loadDocsFileById', () => {});
describe('setProjectAnnotations', () => {
it('busts the loadStory cache', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
const story = await store.loadStory({ storyId: 'component-one--a' });
expect(processCSFFile).toHaveBeenCalledTimes(1);
expect(prepareStory).toHaveBeenCalledTimes(1);
store.setProjectAnnotations({ ...projectAnnotations, decorators: [jest.fn()] });
// We are intentionally checking exact equality here, we need the object to be identical
expect(await store.loadStory({ storyId: 'component-one--a' })).not.toBe(story);
expect(processCSFFile).toHaveBeenCalledTimes(1);
expect(prepareStory).toHaveBeenCalledTimes(2);
});
});
describe('onStoriesChanged', () => {
it('busts the loadStory cache if the importFn returns a new module', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
const story = await store.loadStory({ storyId: 'component-one--a' });
expect(processCSFFile).toHaveBeenCalledTimes(1);
expect(prepareStory).toHaveBeenCalledTimes(1);
await store.onStoriesChanged({
importFn: async () => ({
...componentOneExports,
c: { args: { foo: 'c' } },
}),
});
// The object is not identical which will cause it to be treated as a new story
expect(await store.loadStory({ storyId: 'component-one--a' })).not.toBe(story);
expect(processCSFFile).toHaveBeenCalledTimes(2);
expect(prepareStory).toHaveBeenCalledTimes(2);
});
it('busts the loadStory cache if the csf file no longer appears in the index', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
await store.loadStory({ storyId: 'component-one--a' });
expect(processCSFFile).toHaveBeenCalledTimes(1);
expect(prepareStory).toHaveBeenCalledTimes(1);
// The stories are no longer in the index
await store.onStoriesChanged({ storyIndex: { v: 4, entries: {} } });
await expect(store.loadStory({ storyId: 'component-one--a' })).rejects.toThrow();
// We don't load or process any CSF
expect(processCSFFile).toHaveBeenCalledTimes(1);
expect(prepareStory).toHaveBeenCalledTimes(1);
});
it('reuses the cache if a story importPath has not changed', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
const story = await store.loadStory({ storyId: 'component-one--a' });
expect(processCSFFile).toHaveBeenCalledTimes(1);
expect(prepareStory).toHaveBeenCalledTimes(1);
// Add a new story to the index that isn't different
await store.onStoriesChanged({
storyIndex: {
v: 4,
entries: {
...storyIndex.entries,
'new-component--story': {
type: 'story',
id: 'new-component--story',
title: 'New Component',
name: 'Story',
importPath: './new-component.stories.js',
},
},
},
});
// We are intentionally checking exact equality here, we need the object to be identical
expect(await store.loadStory({ storyId: 'component-one--a' })).toEqual(story);
expect(processCSFFile).toHaveBeenCalledTimes(1);
expect(prepareStory).toHaveBeenCalledTimes(1);
});
it('imports with a new path for a story id if provided', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
await store.loadStory({ storyId: 'component-one--a' });
expect(importFn).toHaveBeenCalledWith(storyIndex.entries['component-one--a'].importPath);
const newImportPath = './src/ComponentOne-new.stories.js';
const newImportFn = jest.fn(async () => componentOneExports);
await store.onStoriesChanged({
importFn: newImportFn,
storyIndex: {
v: 4,
entries: {
'component-one--a': {
type: 'story',
id: 'component-one--a',
title: 'Component One',
name: 'A',
importPath: newImportPath,
},
},
},
});
await store.loadStory({ storyId: 'component-one--a' });
expect(newImportFn).toHaveBeenCalledWith(newImportPath);
});
it('re-caches stories if the were cached already', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
await store.cacheAllCSFFiles();
await store.loadStory({ storyId: 'component-one--a' });
expect(importFn).toHaveBeenCalledWith(storyIndex.entries['component-one--a'].importPath);
const newImportPath = './src/ComponentOne-new.stories.js';
const newImportFn = jest.fn(async () => componentOneExports);
await store.onStoriesChanged({
importFn: newImportFn,
storyIndex: {
v: 4,
entries: {
'component-one--a': {
type: 'story',
id: 'component-one--a',
title: 'Component One',
name: 'A',
importPath: newImportPath,
},
},
},
});
expect(store.extract()).toMatchInlineSnapshot(`
Object {
"component-one--a": Object {
"argTypes": Object {
"a": Object {
"name": "a",
"type": Object {
"name": "string",
},
},
"foo": Object {
"name": "foo",
"type": Object {
"name": "string",
},
},
},
"args": Object {
"foo": "a",
},
"component": undefined,
"componentId": "component-one",
"id": "component-one--a",
"initialArgs": Object {
"foo": "a",
},
"kind": "Component One",
"name": "A",
"parameters": Object {
"__isArgsStory": false,
"fileName": "./src/ComponentOne-new.stories.js",
},
"playFunction": undefined,
"story": "A",
"subcomponents": undefined,
"tags": Array [
"story",
],
"title": "Component One",
},
}
`);
});
});
describe('componentStoriesFromCSFFile', () => {
it('returns all the stories in the file', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
const csfFile = await store.loadCSFFileByStoryId('component-one--a');
const stories = store.componentStoriesFromCSFFile({ csfFile });
expect(stories).toHaveLength(2);
expect(stories.map((s) => s.id)).toEqual(['component-one--a', 'component-one--b']);
});
it('returns them in the order they are in the index, not the file', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
const reversedIndex = {
v: 4,
entries: {
'component-one--b': storyIndex.entries['component-one--b'],
'component-one--a': storyIndex.entries['component-one--a'],
},
};
store.initialize({ storyIndex: reversedIndex, importFn, cache: false });
const csfFile = await store.loadCSFFileByStoryId('component-one--a');
const stories = store.componentStoriesFromCSFFile({ csfFile });
expect(stories).toHaveLength(2);
expect(stories.map((s) => s.id)).toEqual(['component-one--b', 'component-one--a']);
});
});
describe('getStoryContext', () => {
it('returns the args and globals correctly', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
const story = await store.loadStory({ storyId: 'component-one--a' });
expect(store.getStoryContext(story)).toMatchObject({
args: { foo: 'a' },
globals: { a: 'b' },
});
});
it('returns the args and globals correctly when they change', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
const story = await store.loadStory({ storyId: 'component-one--a' });
store.args.update(story.id, { foo: 'bar' });
store.globals!.update({ a: 'c' });
expect(store.getStoryContext(story)).toMatchObject({
args: { foo: 'bar' },
globals: { a: 'c' },
});
});
it('can force initial args', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
const story = await store.loadStory({ storyId: 'component-one--a' });
store.args.update(story.id, { foo: 'bar' });
expect(store.getStoryContext(story, { forceInitialArgs: true })).toMatchObject({
args: { foo: 'a' },
});
});
it('returns the same hooks each time', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
const story = await store.loadStory({ storyId: 'component-one--a' });
const { hooks } = store.getStoryContext(story);
expect(store.getStoryContext(story).hooks).toBe(hooks);
// Now double check it doesn't get changed when you call `loadStory` again
const story2 = await store.loadStory({ storyId: 'component-one--a' });
expect(store.getStoryContext(story2).hooks).toBe(hooks);
});
});
describe('cleanupStory', () => {
it('cleans the hooks from the context', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
const story = await store.loadStory({ storyId: 'component-one--a' });
const { hooks } = store.getStoryContext(story) as { hooks: HooksContext<Renderer> };
hooks.clean = jest.fn();
store.cleanupStory(story);
expect(hooks.clean).toHaveBeenCalled();
});
});
describe('loadAllCSFFiles', () => {
it('imports *all* csf files', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
importFn.mockClear();
const csfFiles = await store.loadAllCSFFiles();
expect(csfFiles).not.toBeUndefined();
expect(Object.keys(csfFiles!)).toEqual([
'./src/ComponentOne.stories.js',
'./src/ComponentTwo.stories.js',
]);
});
it('imports in batches', async () => {
const [gate, openGate] = createGate();
const blockedImportFn = jest.fn(async (file) => {
await gate;
return importFn(file);
});
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn: blockedImportFn, cache: false });
const promise = store.loadAllCSFFiles({ batchSize: 1 });
expect(blockedImportFn).toHaveBeenCalledTimes(1);
openGate();
await promise;
expect(blockedImportFn).toHaveBeenCalledTimes(3);
});
});
describe('extract', () => {
it('throws if you have not called cacheAllCSFFiles', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
expect(() => store.extract()).toThrow(/Cannot call extract/);
});
it('produces objects with functions and hooks stripped', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
await store.cacheAllCSFFiles();
expect(store.extract()).toMatchInlineSnapshot(`
Object {
"component-one--a": Object {
"argTypes": Object {
"a": Object {
"name": "a",
"type": Object {
"name": "string",
},
},
"foo": Object {
"name": "foo",
"type": Object {
"name": "string",
},
},
},
"args": Object {
"foo": "a",
},
"component": undefined,
"componentId": "component-one",
"id": "component-one--a",
"initialArgs": Object {
"foo": "a",
},
"kind": "Component One",
"name": "A",
"parameters": Object {
"__isArgsStory": false,
"fileName": "./src/ComponentOne.stories.js",
},
"playFunction": undefined,
"story": "A",
"subcomponents": undefined,
"tags": Array [
"story",
],
"title": "Component One",
},
"component-one--b": Object {
"argTypes": Object {
"a": Object {
"name": "a",
"type": Object {
"name": "string",
},
},
"foo": Object {
"name": "foo",
"type": Object {
"name": "string",
},
},
},
"args": Object {
"foo": "b",
},
"component": undefined,
"componentId": "component-one",
"id": "component-one--b",
"initialArgs": Object {
"foo": "b",
},
"kind": "Component One",
"name": "B",
"parameters": Object {
"__isArgsStory": false,
"fileName": "./src/ComponentOne.stories.js",
},
"playFunction": undefined,
"story": "B",
"subcomponents": undefined,
"tags": Array [
"story",
],
"title": "Component One",
},
"component-two--c": Object {
"argTypes": Object {
"a": Object {
"name": "a",
"type": Object {
"name": "string",
},
},
"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,
"fileName": "./src/ComponentTwo.stories.js",
},
"playFunction": undefined,
"story": "C",
"subcomponents": undefined,
"tags": Array [
"story",
],
"title": "Component Two",
},
}
`);
});
it('does not include (legacy) docs only stories by default', async () => {
const docsOnlyImportFn = jest.fn(async (path) => {
return path === './src/ComponentOne.stories.js'
? {
...componentOneExports,
a: { ...componentOneExports.a, parameters: { docsOnly: true } },
}
: componentTwoExports;
});
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({
storyIndex,
importFn: docsOnlyImportFn,
cache: false,
});
await store.cacheAllCSFFiles();
expect(Object.keys(store.extract())).toEqual(['component-one--b', 'component-two--c']);
expect(Object.keys(store.extract({ includeDocsOnly: true }))).toEqual([
'component-one--a',
'component-one--b',
'component-two--c',
]);
});
it('does not include (modern) docs entries ever', async () => {
const unnattachedStoryIndex: StoryIndex = {
v: 4,
entries: {
...storyIndex.entries,
'introduction--docs': {
type: 'docs',
id: 'introduction--docs',
title: 'Introduction',
name: 'Docs',
importPath: './introduction.mdx',
storiesImports: [],
},
},
};
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({
storyIndex: unnattachedStoryIndex,
importFn,
cache: false,
});
await store.cacheAllCSFFiles();
expect(Object.keys(store.extract())).toEqual([
'component-one--a',
'component-one--b',
'component-two--c',
]);
expect(Object.keys(store.extract({ includeDocsOnly: true }))).toEqual([
'component-one--a',
'component-one--b',
'component-two--c',
]);
});
});
describe('raw', () => {
it('produces an array of stories', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
await store.cacheAllCSFFiles();
expect(store.raw()).toMatchInlineSnapshot(`
Array [
Object {
"applyLoaders": [Function],
"argTypes": Object {
"a": Object {
"name": "a",
"type": Object {
"name": "string",
},
},
"foo": Object {
"name": "foo",
"type": Object {
"name": "string",
},
},
},
"component": undefined,
"componentId": "component-one",
"id": "component-one--a",
"initialArgs": Object {
"foo": "a",
},
"kind": "Component One",
"moduleExport": Object {
"args": Object {
"foo": "a",
},
},
"name": "A",
"originalStoryFn": [MockFunction],
"parameters": Object {
"__isArgsStory": false,
"fileName": "./src/ComponentOne.stories.js",
},
"playFunction": undefined,
"story": "A",
"storyFn": [Function],
"subcomponents": undefined,
"tags": Array [
"story",
],
"title": "Component One",
"unboundStoryFn": [Function],
"undecoratedStoryFn": [Function],
},
Object {
"applyLoaders": [Function],
"argTypes": Object {
"a": Object {
"name": "a",
"type": Object {
"name": "string",
},
},
"foo": Object {
"name": "foo",
"type": Object {
"name": "string",
},
},
},
"component": undefined,
"componentId": "component-one",
"id": "component-one--b",
"initialArgs": Object {
"foo": "b",
},
"kind": "Component One",
"moduleExport": Object {
"args": Object {
"foo": "b",
},
},
"name": "B",
"originalStoryFn": [MockFunction],
"parameters": Object {
"__isArgsStory": false,
"fileName": "./src/ComponentOne.stories.js",
},
"playFunction": undefined,
"story": "B",
"storyFn": [Function],
"subcomponents": undefined,
"tags": Array [
"story",
],
"title": "Component One",
"unboundStoryFn": [Function],
"undecoratedStoryFn": [Function],
},
Object {
"applyLoaders": [Function],
"argTypes": Object {
"a": Object {
"name": "a",
"type": Object {
"name": "string",
},
},
"foo": Object {
"name": "foo",
"type": Object {
"name": "string",
},
},
},
"component": undefined,
"componentId": "component-two",
"id": "component-two--c",
"initialArgs": Object {
"foo": "c",
},
"kind": "Component Two",
"moduleExport": Object {
"args": Object {
"foo": "c",
},
},
"name": "C",
"originalStoryFn": [MockFunction],
"parameters": Object {
"__isArgsStory": false,
"fileName": "./src/ComponentTwo.stories.js",
},
"playFunction": undefined,
"story": "C",
"storyFn": [Function],
"subcomponents": undefined,
"tags": Array [
"story",
],
"title": "Component Two",
"unboundStoryFn": [Function],
"undecoratedStoryFn": [Function],
},
]
`);
});
});
describe('getSetStoriesPayload', () => {
it('maps stories list to payload correctly', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
await store.cacheAllCSFFiles();
expect(store.getSetStoriesPayload()).toMatchInlineSnapshot(`
Object {
"globalParameters": Object {},
"globals": Object {
"a": "b",
},
"kindParameters": Object {
"Component One": Object {},
"Component Two": Object {},
},
"stories": Object {
"component-one--a": Object {
"argTypes": Object {
"a": Object {
"name": "a",
"type": Object {
"name": "string",
},
},
"foo": Object {
"name": "foo",
"type": Object {
"name": "string",
},
},
},
"args": Object {
"foo": "a",
},
"component": undefined,
"componentId": "component-one",
"id": "component-one--a",
"initialArgs": Object {
"foo": "a",
},
"kind": "Component One",
"name": "A",
"parameters": Object {
"__isArgsStory": false,
"fileName": "./src/ComponentOne.stories.js",
},
"playFunction": undefined,
"story": "A",
"subcomponents": undefined,
"tags": Array [
"story",
],
"title": "Component One",
},
"component-one--b": Object {
"argTypes": Object {
"a": Object {
"name": "a",
"type": Object {
"name": "string",
},
},
"foo": Object {
"name": "foo",
"type": Object {
"name": "string",
},
},
},
"args": Object {
"foo": "b",
},
"component": undefined,
"componentId": "component-one",
"id": "component-one--b",
"initialArgs": Object {
"foo": "b",
},
"kind": "Component One",
"name": "B",
"parameters": Object {
"__isArgsStory": false,
"fileName": "./src/ComponentOne.stories.js",
},
"playFunction": undefined,
"story": "B",
"subcomponents": undefined,
"tags": Array [
"story",
],
"title": "Component One",
},
"component-two--c": Object {
"argTypes": Object {
"a": Object {
"name": "a",
"type": Object {
"name": "string",
},
},
"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,
"fileName": "./src/ComponentTwo.stories.js",
},
"playFunction": undefined,
"story": "C",
"subcomponents": undefined,
"tags": Array [
"story",
],
"title": "Component Two",
},
},
"v": 2,
}
`);
});
});
describe('getStoriesJsonData', () => {
describe('in back-compat mode', () => {
it('maps stories list to payload correctly', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
await store.cacheAllCSFFiles();
expect(store.getStoriesJsonData()).toMatchInlineSnapshot(`
Object {
"stories": Object {
"component-one--a": Object {
"id": "component-one--a",
"importPath": "./src/ComponentOne.stories.js",
"kind": "Component One",
"name": "A",
"parameters": Object {
"__isArgsStory": false,
"fileName": "./src/ComponentOne.stories.js",
},
"story": "A",
"title": "Component One",
},
"component-one--b": Object {
"id": "component-one--b",
"importPath": "./src/ComponentOne.stories.js",
"kind": "Component One",
"name": "B",
"parameters": Object {
"__isArgsStory": false,
"fileName": "./src/ComponentOne.stories.js",
},
"story": "B",
"title": "Component One",
},
"component-two--c": Object {
"id": "component-two--c",
"importPath": "./src/ComponentTwo.stories.js",
"kind": "Component Two",
"name": "C",
"parameters": Object {
"__isArgsStory": false,
"fileName": "./src/ComponentTwo.stories.js",
},
"story": "C",
"title": "Component Two",
},
},
"v": 3,
}
`);
});
});
});
describe('getSetIndexPayload', () => {
it('add parameters/args to index correctly', async () => {
const store = new StoryStore();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
await store.cacheAllCSFFiles();
expect(store.getSetIndexPayload()).toMatchInlineSnapshot(`
Object {
"entries": Object {
"component-one--a": Object {
"argTypes": Object {
"a": Object {
"name": "a",
"type": Object {
"name": "string",
},
},
"foo": Object {
"name": "foo",
"type": Object {
"name": "string",
},
},
},
"args": Object {
"foo": "a",
},
"id": "component-one--a",
"importPath": "./src/ComponentOne.stories.js",
"initialArgs": Object {
"foo": "a",
},
"name": "A",
"parameters": Object {
"__isArgsStory": false,
"fileName": "./src/ComponentOne.stories.js",
},
"title": "Component One",
"type": "story",
},
"component-one--b": Object {
"argTypes": Object {
"a": Object {
"name": "a",
"type": Object {
"name": "string",
},
},
"foo": Object {
"name": "foo",
"type": Object {
"name": "string",
},
},
},
"args": Object {
"foo": "b",
},
"id": "component-one--b",
"importPath": "./src/ComponentOne.stories.js",
"initialArgs": Object {
"foo": "b",
},
"name": "B",
"parameters": Object {
"__isArgsStory": false,
"fileName": "./src/ComponentOne.stories.js",
},
"title": "Component One",
"type": "story",
},
"component-two--c": Object {
"argTypes": Object {
"a": Object {
"name": "a",
"type": Object {
"name": "string",
},
},
"foo": Object {
"name": "foo",
"type": Object {
"name": "string",
},
},
},
"args": Object {
"foo": "c",
},
"id": "component-two--c",
"importPath": "./src/ComponentTwo.stories.js",
"initialArgs": Object {
"foo": "c",
},
"name": "C",
"parameters": Object {
"__isArgsStory": false,
"fileName": "./src/ComponentTwo.stories.js",
},
"title": "Component Two",
"type": "story",
},
},
"v": 4,
}
`);
});
});
describe('cacheAllCsfFiles', () => {
describe('if the store is not yet initialized', () => {
it('waits for initialization', async () => {
const store = new StoryStore();
importFn.mockClear();
const cachePromise = store.cacheAllCSFFiles();
store.setProjectAnnotations(projectAnnotations);
store.initialize({ storyIndex, importFn, cache: false });
await expect(cachePromise).resolves.toEqual(undefined);
});
});
});
});
|
1,169 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/args.test.ts | import { once } from '@storybook/client-logger';
import { expect } from '@jest/globals';
import type { SBType } from '@storybook/types';
import {
combineArgs,
groupArgsByTarget,
mapArgsToTypes,
UNTARGETED,
validateOptions,
} from './args';
const stringType: SBType = { name: 'string' };
const numberType: SBType = { name: 'number' };
const booleanType: SBType = { name: 'boolean' };
const enumType: SBType = { name: 'enum', value: [1, 2, 3] };
const functionType: SBType = { name: 'function' };
const numArrayType: SBType = { name: 'array', value: numberType };
const boolObjectType: SBType = { name: 'object', value: { bool: booleanType } };
jest.mock('@storybook/client-logger');
enum ArgsMapTestEnumWithoutInitializer {
EnumValue,
EnumValue2,
}
enum ArgsMapTestEnumWithStringInitializer {
EnumValue = 'EnumValue',
}
enum ArgsMapTestEnumWithNumericInitializer {
EnumValue = 4,
}
describe('mapArgsToTypes', () => {
it('maps strings', () => {
expect(mapArgsToTypes({ a: 'str' }, { a: { type: stringType } })).toStrictEqual({ a: 'str' });
expect(mapArgsToTypes({ a: 42 }, { a: { type: stringType } })).toStrictEqual({ a: '42' });
});
it('maps enums', () => {
expect(
mapArgsToTypes({ a: ArgsMapTestEnumWithoutInitializer.EnumValue }, { a: { type: enumType } })
).toEqual({ a: 0 });
expect(
mapArgsToTypes({ a: ArgsMapTestEnumWithoutInitializer.EnumValue2 }, { a: { type: enumType } })
).toEqual({ a: 1 });
expect(
mapArgsToTypes(
{ a: ArgsMapTestEnumWithStringInitializer.EnumValue },
{ a: { type: enumType } }
)
).toEqual({ a: 'EnumValue' });
expect(
mapArgsToTypes(
{ a: ArgsMapTestEnumWithNumericInitializer.EnumValue },
{ a: { type: enumType } }
)
).toEqual({ a: 4 });
});
it('maps numbers', () => {
expect(mapArgsToTypes({ a: '42' }, { a: { type: numberType } })).toStrictEqual({ a: 42 });
expect(mapArgsToTypes({ a: '4.2' }, { a: { type: numberType } })).toStrictEqual({ a: 4.2 });
expect(mapArgsToTypes({ a: 'a' }, { a: { type: numberType } })).toStrictEqual({ a: NaN });
});
it('maps booleans', () => {
expect(mapArgsToTypes({ a: 'true' }, { a: { type: booleanType } })).toStrictEqual({ a: true });
expect(mapArgsToTypes({ a: 'false' }, { a: { type: booleanType } })).toStrictEqual({
a: false,
});
expect(mapArgsToTypes({ a: 'yes' }, { a: { type: booleanType } })).toStrictEqual({ a: false });
});
it('maps sparse arrays', () => {
// eslint-disable-next-line no-sparse-arrays
expect(mapArgsToTypes({ a: [, '2', undefined] }, { a: { type: numArrayType } })).toStrictEqual({
// eslint-disable-next-line no-sparse-arrays
a: [, 2, undefined],
});
});
it('omits functions', () => {
expect(mapArgsToTypes({ a: 'something' }, { a: { type: functionType } })).toStrictEqual({});
});
it('includes functions if there is a mapping', () => {
expect(
mapArgsToTypes(
{ a: 'something' },
{ a: { type: functionType, mapping: { something: () => 'foo' } } }
)
).toStrictEqual({
a: 'something',
});
});
it('skips default mapping if there is a user-specified mapping', () => {
expect(
mapArgsToTypes({ a: 'something' }, { a: { type: numberType, mapping: { something: 10 } } })
).toStrictEqual({
a: 'something',
});
});
it('omits unknown keys', () => {
expect(mapArgsToTypes({ a: 'string' }, { b: { type: stringType } })).toStrictEqual({});
});
it('passes through unmodified if no type is specified', () => {
expect(mapArgsToTypes({ a: { b: 1 } }, { a: { type: undefined } })).toStrictEqual({
a: { b: 1 },
});
});
it('passes string for object type', () => {
expect(mapArgsToTypes({ a: 'A' }, { a: { type: boolObjectType } })).toStrictEqual({ a: 'A' });
});
it('passes number for object type', () => {
expect(mapArgsToTypes({ a: 1.2 }, { a: { type: boolObjectType } })).toStrictEqual({ a: 1.2 });
});
it('deeply maps objects', () => {
expect(
mapArgsToTypes(
{
key: {
arr: ['1', '2'],
obj: { bool: 'true' },
},
},
{
key: {
type: {
name: 'object',
value: {
arr: numArrayType,
obj: boolObjectType,
},
},
},
}
)
).toStrictEqual({
key: {
arr: [1, 2],
obj: { bool: true },
},
});
});
it('deeply maps arrays', () => {
expect(
mapArgsToTypes(
{
key: [
{
arr: ['1', '2'],
obj: { bool: 'true' },
},
],
},
{
key: {
type: {
name: 'array',
value: {
name: 'object',
value: {
arr: numArrayType,
obj: boolObjectType,
},
},
},
},
}
)
).toStrictEqual({
key: [
{
arr: [1, 2],
obj: { bool: true },
},
],
});
});
});
describe('combineArgs', () => {
it('merges args', () => {
expect(combineArgs({ foo: 1 }, { bar: 2 })).toStrictEqual({ foo: 1, bar: 2 });
});
it('merges sparse arrays', () => {
// eslint-disable-next-line no-sparse-arrays
expect(combineArgs({ foo: [1, 2, 3] }, { foo: [, 4, undefined] })).toStrictEqual({
foo: [1, 4],
});
});
it('deeply merges args', () => {
expect(combineArgs({ foo: { bar: [1, 2], baz: true } }, { foo: { bar: [3] } })).toStrictEqual({
foo: { bar: [3, 2], baz: true },
});
});
it('omits keys with undefined value', () => {
expect(combineArgs({ foo: 1 }, { foo: undefined })).toStrictEqual({});
});
});
describe('validateOptions', () => {
// https://github.com/storybookjs/storybook/issues/15630
it('does not set args to `undefined` if they are unset', () => {
expect(validateOptions({}, { a: {} })).toStrictEqual({});
});
it('omits arg and warns if value is not one of options', () => {
expect(validateOptions({ a: 1 }, { a: { options: [2, 3] } })).toStrictEqual({});
expect(once.warn).toHaveBeenCalledWith(
"Received illegal value for 'a'. Supported options: 2, 3"
);
});
it('includes arg if value is one of options', () => {
expect(validateOptions({ a: 1 }, { a: { options: [1, 2] } })).toStrictEqual({ a: 1 });
});
// https://github.com/storybookjs/storybook/issues/17063
it('does not set args to `undefined` if they are unset and there are options', () => {
expect(validateOptions({}, { a: { options: [2, 3] } })).toStrictEqual({});
});
it('includes arg if value is undefined', () => {
expect(validateOptions({ a: undefined }, { a: { options: [1, 2] } })).toStrictEqual({
a: undefined,
});
});
it('includes arg if no options are specified', () => {
expect(validateOptions({ a: 1 }, { a: {} })).toStrictEqual({ a: 1 });
});
it('ignores options and logs an error if options is not an array', () => {
expect(validateOptions({ a: 1 }, { a: { options: { 2: 'two' } } })).toStrictEqual({ a: 1 });
expect(once.error).toHaveBeenCalledWith(
expect.stringContaining("Invalid argType: 'a.options' should be an array")
);
});
it('logs an error if options contains non-primitive values', () => {
expect(
validateOptions({ a: { one: 1 } }, { a: { options: [{ one: 1 }, { two: 2 }] } })
).toStrictEqual({ a: { one: 1 } });
expect(once.error).toHaveBeenCalledWith(
expect.stringContaining("Invalid argType: 'a.options' should only contain primitives")
);
expect(once.warn).not.toHaveBeenCalled();
});
it('supports arrays', () => {
expect(validateOptions({ a: [1, 2] }, { a: { options: [1, 2, 3] } })).toStrictEqual({
a: [1, 2],
});
expect(validateOptions({ a: [1, 2, 4] }, { a: { options: [2, 3] } })).toStrictEqual({});
expect(once.warn).toHaveBeenCalledWith(
"Received illegal value for 'a[0]'. Supported options: 2, 3"
);
});
});
describe('groupArgsByTarget', () => {
it('groups targeted args', () => {
const groups = groupArgsByTarget({
args: { a: 1, b: 2, c: 3 },
argTypes: {
a: { name: 'a', target: 'group1' },
b: { name: 'b', target: 'group2' },
c: { name: 'c', target: 'group2' },
},
});
expect(groups).toEqual({
group1: {
a: 1,
},
group2: {
b: 2,
c: 3,
},
});
});
it('groups non-targetted args into a group with no name', () => {
const groups = groupArgsByTarget({
args: { a: 1, b: 2, c: 3 },
argTypes: { a: { name: 'a' }, b: { name: 'b', target: 'group2' }, c: { name: 'c' } },
});
expect(groups).toEqual({
[UNTARGETED]: {
a: 1,
c: 3,
},
group2: {
b: 2,
},
});
});
});
|
1,171 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/autoTitle.test.ts | import { normalizeStoriesEntry } from '@storybook/core-common';
import { expect } from '@jest/globals';
import { userOrAutoTitleFromSpecifier as userOrAuto } from './autoTitle';
expect.addSnapshotSerializer({
print: (val: any) => val,
test: (val: any) => true,
});
// Make these two the same so `normalizeStoriesEntry` doesn't change anything
const options = {
configDir: '/path',
workingDir: '/path',
};
const winOptions = {
configDir: '\\path',
workingDir: '\\path',
};
describe('userOrAutoTitleFromSpecifier', () => {
describe('user title', () => {
it('no match', () => {
expect(
userOrAuto(
'./ path / to / file.stories.js',
normalizeStoriesEntry({ directory: './ other' }, options),
'title'
)
).toBeFalsy();
});
describe('no trailing slash', () => {
it('match with no titlePrefix', () => {
expect(
userOrAuto(
'./path/to/file.stories.js',
normalizeStoriesEntry({ directory: './path' }, options),
'title'
)
).toMatchInlineSnapshot(`title`);
});
it('match with titlePrefix', () => {
expect(
userOrAuto(
'./path/to/file.stories.js',
normalizeStoriesEntry({ directory: './path', titlePrefix: 'atoms' }, options),
'title'
)
).toMatchInlineSnapshot(`atoms/title`);
});
it('match with hyphen path', () => {
expect(
userOrAuto(
'./path/to-my/file.stories.js',
normalizeStoriesEntry({ directory: './path', titlePrefix: 'atoms' }, options),
'title'
)
).toMatchInlineSnapshot(`atoms/title`);
});
it('match with underscore path', () => {
expect(
userOrAuto(
'./path/to_my/file.stories.js',
normalizeStoriesEntry({ directory: './path', titlePrefix: 'atoms' }, options),
'title'
)
).toMatchInlineSnapshot(`atoms/title`);
});
it('match with windows path', () => {
expect(
userOrAuto(
'./path/to_my/file.stories.js',
normalizeStoriesEntry({ directory: '.\\path', titlePrefix: 'atoms' }, winOptions),
'title'
)
).toMatchInlineSnapshot(`atoms/title`);
});
});
describe('trailing slash', () => {
it('match with no titlePrefix', () => {
expect(
userOrAuto(
'./path/to/file.stories.js',
normalizeStoriesEntry({ directory: './path/' }, options),
'title'
)
).toMatchInlineSnapshot(`title`);
});
it('match with titlePrefix', () => {
expect(
userOrAuto(
'./path/to/file.stories.js',
normalizeStoriesEntry({ directory: './path/', titlePrefix: 'atoms' }, options),
'title'
)
).toMatchInlineSnapshot(`atoms/title`);
});
it('match with hyphen path', () => {
expect(
userOrAuto(
'./path/to-my/file.stories.js',
normalizeStoriesEntry({ directory: './path/', titlePrefix: 'atoms' }, options),
'title'
)
).toMatchInlineSnapshot(`atoms/title`);
});
it('match with underscore path', () => {
expect(
userOrAuto(
'./path/to_my/file.stories.js',
normalizeStoriesEntry({ directory: './path/', titlePrefix: 'atoms' }, options),
'title'
)
).toMatchInlineSnapshot(`atoms/title`);
});
it('match with windows path', () => {
expect(
userOrAuto(
'./path/to_my/file.stories.js',
normalizeStoriesEntry({ directory: '.\\path\\', titlePrefix: 'atoms' }, winOptions),
'title'
)
).toMatchInlineSnapshot(`atoms/title`);
});
});
});
describe('auto title', () => {
it('no match', () => {
expect(
userOrAuto(
'./ path / to / file.stories.js',
normalizeStoriesEntry({ directory: './ other' }, options),
undefined
)
).toBeFalsy();
});
describe('no trailing slash', () => {
it('match with no titlePrefix', () => {
expect(
userOrAuto(
'./path/to/file.stories.js',
normalizeStoriesEntry({ directory: './path' }, options),
undefined
)
).toMatchInlineSnapshot(`to/file`);
});
it('match with titlePrefix', () => {
expect(
userOrAuto(
'./path/to/file.stories.js',
normalizeStoriesEntry({ directory: './path', titlePrefix: 'atoms' }, options),
undefined
)
).toMatchInlineSnapshot(`atoms/to/file`);
});
it('match with trailing duplicate', () => {
expect(
userOrAuto(
'./path/to/button/button.stories.js',
normalizeStoriesEntry({ directory: './path' }, options),
undefined
)
).toMatchInlineSnapshot(`to/button`);
});
it('match with trailing index', () => {
expect(
userOrAuto(
'./path/to/button/index.stories.js',
normalizeStoriesEntry({ directory: './path' }, options),
undefined
)
).toMatchInlineSnapshot(`to/button`);
});
it('match with hyphen path', () => {
expect(
userOrAuto(
'./path/to-my/file.stories.js',
normalizeStoriesEntry({ directory: './path' }, options),
undefined
)
).toMatchInlineSnapshot(`to-my/file`);
});
it('match with underscore path', () => {
expect(
userOrAuto(
'./path/to_my/file.stories.js',
normalizeStoriesEntry({ directory: './path' }, options),
undefined
)
).toMatchInlineSnapshot(`to_my/file`);
});
it('match with windows path', () => {
expect(
userOrAuto(
'./path/to_my/file.stories.js',
normalizeStoriesEntry({ directory: '.\\path' }, winOptions),
undefined
)
).toMatchInlineSnapshot(`to_my/file`);
});
});
describe('trailing slash', () => {
it('match with no titlePrefix', () => {
expect(
userOrAuto(
'./path/to/file.stories.js',
normalizeStoriesEntry({ directory: './path/' }, options),
undefined
)
).toMatchInlineSnapshot(`to/file`);
});
it('match with titlePrefix', () => {
expect(
userOrAuto(
'./path/to/file.stories.js',
normalizeStoriesEntry({ directory: './path/', titlePrefix: 'atoms' }, options),
undefined
)
).toMatchInlineSnapshot(`atoms/to/file`);
});
it('match with hyphen path', () => {
expect(
userOrAuto(
'./path/to-my/file.stories.js',
normalizeStoriesEntry({ directory: './path/' }, options),
undefined
)
).toMatchInlineSnapshot(`to-my/file`);
});
it('match with underscore path', () => {
expect(
userOrAuto(
'./path/to_my/file.stories.js',
normalizeStoriesEntry({ directory: './path/' }, options),
undefined
)
).toMatchInlineSnapshot(`to_my/file`);
});
it('match with windows path', () => {
expect(
userOrAuto(
'./path/to_my/file.stories.js',
normalizeStoriesEntry({ directory: '.\\path\\' }, winOptions),
undefined
)
).toMatchInlineSnapshot(`to_my/file`);
});
it('camel-case file', () => {
expect(
userOrAuto(
'./path/to_my/MyButton.stories.js',
normalizeStoriesEntry({ directory: './path' }, options),
undefined
)
).toMatchInlineSnapshot(`to_my/MyButton`);
});
});
});
});
|
1,173 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/decorators.test.ts | import { expect } from '@jest/globals';
import type { Renderer, StoryContext } from '@storybook/types';
import { defaultDecorateStory } from './decorators';
function makeContext(input: Record<string, any> = {}): StoryContext<Renderer> {
return {
id: 'id',
kind: 'kind',
name: 'name',
viewMode: 'story',
parameters: {},
...input,
} as StoryContext<Renderer>;
}
describe('client-api.decorators', () => {
it('calls decorators in out to in order', () => {
const order: number[] = [];
const decorators = [
// @ts-expect-error (not defined)
(s) => order.push(1) && s(),
// @ts-expect-error (not defined)
(s) => order.push(2) && s(),
// @ts-expect-error (not defined)
(s) => order.push(3) && s(),
];
const decorated = defaultDecorateStory(() => order.push(4), decorators);
expect(order).toEqual([]);
decorated(makeContext());
expect(order).toEqual([3, 2, 1, 4]);
});
it('passes context through to sub decorators', () => {
const contexts: StoryContext[] = [];
const decorators = [
// @ts-expect-error (not defined)
(s, c) => contexts.push(c) && s({ args: { k: 1 } }),
// @ts-expect-error (not defined)
(s, c) => contexts.push(c) && s({ args: { k: 2 } }),
// @ts-expect-error (not defined)
(s, c) => contexts.push(c) && s({ args: { k: 3 } }),
];
const decorated = defaultDecorateStory((c) => contexts.push(c), decorators);
expect(contexts).toEqual([]);
decorated(makeContext({ args: { k: 0 } }));
expect(contexts.map((c) => c.args.k)).toEqual([0, 3, 2, 1]);
});
it('passes context through to sub decorators additively', () => {
const contexts: StoryContext[] = [];
const decorators = [
// @ts-expect-error (not defined)
(s, c) => contexts.push(c) && s({ args: { a: 1 } }),
// @ts-expect-error (not defined)
(s, c) => contexts.push(c) && s({ globals: { g: 2 } }),
];
const decorated = defaultDecorateStory((c) => contexts.push(c), decorators);
expect(contexts).toEqual([]);
decorated(makeContext({}));
expect(contexts.map(({ args, globals }) => ({ args, globals }))).toEqual([
{ args: undefined, globals: undefined },
{ globals: { g: 2 } },
{ args: { a: 1 }, globals: { g: 2 } },
]);
});
it('does not recreate decorated story functions each time', () => {
// @ts-expect-error (not defined)
const decoratedStories = [];
const decorators = [
// @ts-expect-error (not defined)
(s, c) => {
// @ts-expect-error (not defined)
decoratedStories.push = s;
return s();
},
];
const decorated = defaultDecorateStory(() => 0, decorators);
decorated(makeContext());
decorated(makeContext());
// @ts-expect-error (not defined)
expect(decoratedStories[0]).toBe(decoratedStories[1]);
});
// NOTE: important point--this test would not work if we called `decoratedOne` twice simultaneously
// both story functions would receive {story: 2}. The assumption here is that we'll never render
// the same story twice at the same time.
it('does not interleave contexts if two decorated stories are call simultaneously', async () => {
const contexts: StoryContext[] = [];
let resolve: (value?: unknown) => void = () => {};
const fence = new Promise((r) => {
resolve = r;
});
const decorators = [
// @ts-expect-error (not defined)
async (s, c) => {
// The fence here simulates async-ness in react rendering an element (`<S />` doesn't run `S()` straight away)
await fence;
s();
},
];
const decoratedOne = defaultDecorateStory((c) => contexts.push(c), decorators);
const decoratedTwo = defaultDecorateStory((c) => contexts.push(c), decorators);
decoratedOne(makeContext({ value: 1 }));
decoratedTwo(makeContext({ value: 2 }));
resolve();
await fence;
expect(contexts[0].value).toBe(1);
expect(contexts[1].value).toBe(2);
});
it('DOES NOT merge core metadata or pass through core metadata keys in context', () => {
const contexts: StoryContext[] = [];
const decorators = [
// @ts-expect-error (not defined)
(s, c) =>
contexts.push(c) &&
s({ parameters: { c: 'd' }, id: 'notId', kind: 'notKind', name: 'notName' }),
];
const decorated = defaultDecorateStory((c) => contexts.push(c), decorators);
expect(contexts).toEqual([]);
decorated(makeContext({ parameters: { a: 'b' } }));
expect(contexts).toEqual([
expect.objectContaining({ parameters: { a: 'b' }, id: 'id', kind: 'kind', name: 'name' }),
expect.objectContaining({ parameters: { a: 'b' }, id: 'id', kind: 'kind', name: 'name' }),
]);
});
});
|
1,176 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/hooks.test.ts | import { expect } from '@jest/globals';
import {
FORCE_RE_RENDER,
STORY_RENDERED,
UPDATE_STORY_ARGS,
RESET_STORY_ARGS,
UPDATE_GLOBALS,
} from '@storybook/core-events';
import type { DecoratorFunction, StoryContext } from '@storybook/types';
import {
addons,
applyHooks,
useEffect,
useMemo,
useCallback,
useRef,
useState,
useReducer,
useChannel,
useParameter,
useStoryContext,
HooksContext,
useArgs,
useGlobals,
} from '../addons';
import { defaultDecorateStory } from './decorators';
jest.mock('@storybook/client-logger', () => ({
logger: { warn: jest.fn(), log: jest.fn() },
}));
const SOME_EVENT = 'someEvent';
let mockChannel: any;
let hooks: any;
let onSomeEvent: any;
let removeSomeEventListener: any;
beforeEach(() => {
onSomeEvent = jest.fn();
removeSomeEventListener = jest.fn();
mockChannel = {
emit: jest.fn(),
on(event: any, callback: any) {
switch (event) {
case STORY_RENDERED:
callback();
break;
case SOME_EVENT:
onSomeEvent(event, callback);
break;
default:
}
},
removeListener(event: any, callback: any) {
if (event === SOME_EVENT) {
removeSomeEventListener(event, callback);
}
},
};
hooks = new HooksContext();
addons.setChannel(mockChannel);
});
const decorateStory = applyHooks(defaultDecorateStory);
const run = (storyFn: any, decorators: DecoratorFunction[] = [], context = {}) =>
decorateStory(storyFn, decorators)({ ...context, hooks } as StoryContext);
describe('Preview hooks', () => {
describe('useEffect', () => {
it('triggers the effect from story function', () => {
const effect = jest.fn();
run(() => {
useEffect(effect);
});
expect(effect).toHaveBeenCalledTimes(1);
});
it('triggers the effect from decorator', () => {
const effect = jest.fn();
run(() => {}, [
(storyFn) => {
useEffect(effect);
return storyFn();
},
]);
expect(effect).toHaveBeenCalledTimes(1);
});
it('triggers the effect from decorator if story call comes before useEffect', () => {
const effect = jest.fn();
run(() => {}, [
(storyFn) => {
const story = storyFn();
useEffect(effect);
return story;
},
]);
expect(effect).toHaveBeenCalledTimes(1);
});
it('retriggers the effect if no deps array is provided', () => {
const effect = jest.fn();
const storyFn = () => {
useEffect(effect);
};
run(storyFn);
run(storyFn);
expect(effect).toHaveBeenCalledTimes(2);
});
it("doesn't retrigger the effect if empty deps array is provided", () => {
const effect = jest.fn();
const storyFn = () => {
useEffect(effect, []);
};
run(storyFn);
run(storyFn);
expect(effect).toHaveBeenCalledTimes(1);
});
it("doesn't retrigger the effect from decorator if story has changed", () => {
const effect = jest.fn();
const decorator = (storyFn: any) => {
useEffect(effect, []);
return storyFn();
};
run(() => {}, [decorator]);
run(() => {}, [decorator]);
expect(effect).toHaveBeenCalledTimes(1);
});
it("doesn't retrigger the effect from decorator if story has changed and story call comes before useEffect", () => {
const effect = jest.fn();
const decorator = (storyFn: any) => {
const story = storyFn();
useEffect(effect, []);
return story;
};
run(() => {}, [decorator]);
run(() => {}, [decorator]);
expect(effect).toHaveBeenCalledTimes(1);
});
it("doesn't retrigger the effect from if decorator calls story twice", () => {
const effect = jest.fn();
const story = () => {
useEffect(effect, []);
};
const decorator = (storyFn: any) => {
storyFn();
return storyFn();
};
run(story, [decorator]);
expect(effect).toHaveBeenCalledTimes(1);
});
it('handles decorator conditionally rendering the story', () => {
const effect = jest.fn();
const story = () => {
useEffect(effect, []);
};
const decorator = (storyFn: any) => {
const [counter, setCounter] = useState(0);
useEffect(() => {
setCounter((prevCounter) => prevCounter + 1);
}, [counter]);
if (counter % 2 === 1) storyFn();
return 'placeholder while waiting';
};
run(story, [decorator]);
run(story, [decorator]);
run(story, [decorator]);
run(story, [decorator]);
expect(effect).toHaveBeenCalledTimes(2);
});
it('retriggers the effect if some of the deps are changed', () => {
const effect = jest.fn();
let counter = 0;
const storyFn = () => {
useEffect(effect, [counter]);
counter += 1;
};
run(storyFn);
run(storyFn);
expect(effect).toHaveBeenCalledTimes(2);
});
it("doesn't retrigger the effect if none of the deps are changed", () => {
const effect = jest.fn();
const storyFn = () => {
useEffect(effect, [0]);
};
run(storyFn);
run(storyFn);
expect(effect).toHaveBeenCalledTimes(1);
});
it('performs cleanup when retriggering', () => {
const destroy = jest.fn();
const storyFn = () => {
useEffect(() => destroy);
};
run(storyFn);
run(storyFn);
expect(destroy).toHaveBeenCalledTimes(1);
});
it("doesn't perform cleanup when keeping the current effect", () => {
const destroy = jest.fn();
const storyFn = () => {
useEffect(() => destroy, []);
};
run(storyFn);
run(storyFn);
expect(destroy).not.toHaveBeenCalled();
});
it('performs cleanup when removing the decorator', () => {
const destroy = jest.fn();
run(() => {}, [
(storyFn) => {
useEffect(() => destroy);
return storyFn();
},
]);
run(() => {});
expect(destroy).toHaveBeenCalledTimes(1);
});
});
describe('useChannel', () => {
it('calls .on when rendering the decorator', () => {
const handler = () => {};
run(() => {}, [
(storyFn) => {
useChannel({
[SOME_EVENT]: handler,
});
return storyFn();
},
]);
expect(onSomeEvent).toHaveBeenCalledTimes(1);
expect(removeSomeEventListener).toHaveBeenCalledTimes(0);
});
it('calls .removeListener when removing the decorator', () => {
const handler = () => {};
run(() => {}, [
(storyFn) => {
useChannel({
[SOME_EVENT]: handler,
});
return storyFn();
},
]);
expect(onSomeEvent).toHaveBeenCalledTimes(1);
expect(removeSomeEventListener).toHaveBeenCalledTimes(0);
run(() => {});
expect(removeSomeEventListener).toHaveBeenCalledTimes(1);
});
});
describe('useStoryContext', () => {
it('returns current context', () => {
const context = {};
run(
() => {
expect(useStoryContext()).toEqual({ ...context, hooks });
},
[],
context
);
});
});
describe('useParameter', () => {
it('will pull value from storyStore', () => {
run(
() => {},
[
(storyFn) => {
expect(useParameter('foo', 4)).toEqual(42);
return storyFn();
},
],
{ parameters: { foo: 42 } }
);
});
it('will return default value', () => {
run(
() => {},
[
(storyFn) => {
expect(useParameter('bar', 4)).toEqual(4);
return storyFn();
},
],
{ parameters: {} }
);
});
it('will return undefined when no value is found', () => {
run(
() => {},
[
(storyFn) => {
expect(useParameter('bar')).toBe(undefined);
return storyFn();
},
],
{ parameters: {} }
);
});
});
describe('useMemo', () => {
it('performs the calculation', () => {
let result;
const nextCreate = jest.fn(() => 'foo');
const storyFn = () => {
result = useMemo(nextCreate, []);
};
run(storyFn);
expect(nextCreate).toHaveBeenCalledTimes(1);
expect(result).toBe('foo');
});
it('performs the calculation once if deps are unchanged', () => {
let result;
const nextCreate = jest.fn(() => 'foo');
const storyFn = () => {
result = useMemo(nextCreate, []);
};
run(storyFn);
run(storyFn);
expect(nextCreate).toHaveBeenCalledTimes(1);
expect(result).toBe('foo');
});
it('performs the calculation again if deps are changed', () => {
let result;
let counter = 0;
const nextCreate = jest.fn(() => counter);
const storyFn = () => {
counter += 1;
result = useMemo(nextCreate, [counter]);
};
run(storyFn);
run(storyFn);
expect(nextCreate).toHaveBeenCalledTimes(2);
expect(result).toBe(counter);
});
});
describe('useCallback', () => {
it('returns the callback', () => {
let result;
const callback = () => {};
const storyFn = () => {
result = useCallback(callback, []);
};
run(storyFn);
expect(result).toBe(callback);
});
it('returns the previous callback reference if deps are unchanged', () => {
const callbacks: (() => void)[] = [];
const storyFn = () => {
const callback = useCallback(() => {}, []);
callbacks.push(callback);
};
run(storyFn);
run(storyFn);
expect(callbacks[0]).toBe(callbacks[1]);
});
it('creates new callback reference if deps are changed', () => {
const callbacks: (() => void)[] = [];
let counter = 0;
const storyFn = () => {
counter += 1;
const callback = useCallback(() => {}, [counter]);
callbacks.push(callback);
};
run(storyFn);
run(storyFn);
expect(callbacks[0]).not.toBe(callbacks[1]);
});
});
describe('useRef', () => {
it('attaches initial value', () => {
let ref: any;
const storyFn = () => {
ref = useRef('foo');
};
run(storyFn);
expect(ref.current).toBe('foo');
});
it('stores mutations', () => {
let refValueFromSecondRender;
let counter = 0;
const storyFn = () => {
counter += 1;
const ref = useRef('foo');
if (counter === 1) {
ref.current = 'bar';
} else {
refValueFromSecondRender = ref.current;
}
};
run(storyFn);
run(storyFn);
expect(refValueFromSecondRender).toBe('bar');
});
});
describe('useState', () => {
it('sets initial state', () => {
let state;
const storyFn = () => {
[state] = useState('foo');
};
run(storyFn);
expect(state).toBe('foo');
});
it('calculates initial state', () => {
let state;
const storyFn = () => {
[state] = useState(() => 'foo');
};
run(storyFn);
expect(state).toBe('foo');
});
it('performs synchronous state updates', () => {
let state;
let setState;
const storyFn = jest.fn(() => {
[state, setState] = useState('foo');
if (state === 'foo') {
setState('bar');
}
});
run(storyFn);
expect(storyFn).toHaveBeenCalledTimes(2);
expect(state).toBe('bar');
});
it('triggers only the last effect when updating state synchronously', () => {
const effects = [jest.fn(), jest.fn()];
const storyFn = jest.fn(() => {
const [effectIndex, setEffectIndex] = useState(0);
useEffect(effects[effectIndex], [effectIndex]);
if (effectIndex === 0) {
setEffectIndex(1);
}
});
run(storyFn);
expect(effects[0]).not.toHaveBeenCalled();
expect(effects[1]).toHaveBeenCalledTimes(1);
});
it('performs synchronous state updates with updater function', () => {
let state;
let setState;
const storyFn = jest.fn(() => {
[state, setState] = useState(0);
if (state < 3) {
setState((prevState) => prevState + 1);
}
});
run(storyFn);
expect(storyFn).toHaveBeenCalledTimes(4);
expect(state).toBe(3);
});
it('performs asynchronous state updates', () => {
let state;
let setState: any;
const storyFn = jest.fn(() => {
[state, setState] = useState('foo');
});
run(storyFn);
setState('bar');
expect(mockChannel.emit).toHaveBeenCalledWith(FORCE_RE_RENDER);
run(storyFn);
expect(state).toBe('bar');
});
});
describe('useReducer', () => {
it('sets initial state', () => {
let state;
const storyFn = () => {
[state] = useReducer(() => 'bar', 'foo');
};
run(storyFn);
expect(state).toBe('foo');
});
it('calculates initial state', () => {
let state;
const storyFn = () => {
[state] = useReducer(
() => 'bar',
'foo',
(arg) => arg
);
};
run(storyFn);
expect(state).toBe('foo');
});
it('performs synchronous state updates', () => {
let state;
let dispatch;
const storyFn = jest.fn(() => {
[state, dispatch] = useReducer((prevState, action) => {
switch (action) {
case 'INCREMENT':
return prevState + 1;
default:
return prevState;
}
}, 0);
if (state < 3) {
dispatch('INCREMENT');
}
});
run(storyFn);
expect(storyFn).toHaveBeenCalledTimes(4);
expect(state).toBe(3);
});
it('performs asynchronous state updates', () => {
let state: any;
let dispatch: any;
const storyFn = jest.fn(() => {
[state, dispatch] = useReducer((prevState, action) => {
switch (action) {
case 'INCREMENT':
return prevState + 1;
default:
return prevState;
}
}, 0);
});
run(storyFn);
dispatch('INCREMENT');
expect(mockChannel.emit).toHaveBeenCalledWith(FORCE_RE_RENDER);
run(storyFn);
expect(state).toBe(1);
});
});
describe('useArgs', () => {
it('will pull args from context', () => {
run(
() => {},
[
(storyFn) => {
expect(useArgs()[0]).toEqual({ a: 'b' });
return storyFn();
},
],
{ args: { a: 'b' } }
);
});
it('will emit UPDATE_STORY_ARGS when called', () => {
run(
() => {},
[
(storyFn) => {
useArgs()[1]({ a: 'b' });
expect(mockChannel.emit).toHaveBeenCalledWith(UPDATE_STORY_ARGS, {
storyId: '1',
updatedArgs: { a: 'b' },
});
return storyFn();
},
],
{ id: '1', args: {} }
);
});
it('will emit RESET_STORY_ARGS when called', () => {
run(
() => {},
[
(storyFn) => {
useArgs()[2](['a']);
expect(mockChannel.emit).toHaveBeenCalledWith(RESET_STORY_ARGS, {
storyId: '1',
argNames: ['a'],
});
useArgs()[2]();
expect(mockChannel.emit).toHaveBeenCalledWith(RESET_STORY_ARGS, {
storyId: '1',
});
return storyFn();
},
],
{ id: '1', args: {} }
);
});
});
describe('useGlobals', () => {
it('will pull globals from context', () => {
run(
() => {},
[
(storyFn) => {
expect(useGlobals()[0]).toEqual({ a: 'b' });
return storyFn();
},
],
{ globals: { a: 'b' } }
);
});
it('will emit UPDATE_GLOBALS when called', () => {
run(
() => {},
[
(storyFn) => {
useGlobals()[1]({ a: 'b' });
expect(mockChannel.emit).toHaveBeenCalledWith(UPDATE_GLOBALS, { globals: { a: 'b' } });
return storyFn();
},
],
{ globals: {} }
);
});
});
});
|
1,179 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/inferArgTypes.test.ts | import { logger } from '@storybook/client-logger';
import { expect } from '@jest/globals';
import { inferArgTypes } from './inferArgTypes';
jest.mock('@storybook/client-logger');
describe('inferArgTypes', () => {
it('infers scalar types', () => {
expect(
inferArgTypes({
initialArgs: {
a: true,
b: 'string',
c: 1,
d: () => {},
e: Symbol('foo'),
},
} as any)
).toEqual({
a: { name: 'a', type: { name: 'boolean' } },
b: { name: 'b', type: { name: 'string' } },
c: { name: 'c', type: { name: 'number' } },
d: { name: 'd', type: { name: 'function' } },
e: { name: 'e', type: { name: 'symbol' } },
});
});
it('infers array types', () => {
expect(
inferArgTypes({
initialArgs: {
a: [1, 2, 3],
b: ['a', 'b', 'c'],
c: [],
},
} as any)
).toEqual({
a: { name: 'a', type: { name: 'array', value: { name: 'number' } } },
b: { name: 'b', type: { name: 'array', value: { name: 'string' } } },
c: { name: 'c', type: { name: 'array', value: { name: 'other', value: 'unknown' } } },
});
});
it('infers object types', () => {
expect(
inferArgTypes({
initialArgs: {
a: {
x: 'string',
y: 1,
},
},
} as any)
).toEqual({
a: {
name: 'a',
type: { name: 'object', value: { x: { name: 'string' }, y: { name: 'number' } } },
},
});
});
it('infers nested types', () => {
expect(
inferArgTypes({
initialArgs: {
a: [
{
x: 'string',
},
],
},
} as any)
).toEqual({
a: {
name: 'a',
type: { name: 'array', value: { name: 'object', value: { x: { name: 'string' } } } },
},
});
});
it('avoid cycles', () => {
const cyclic: any = {};
cyclic.foo = cyclic;
(logger.warn as jest.MockedFunction<typeof logger.warn>).mockClear();
expect(
inferArgTypes({
initialArgs: {
a: cyclic,
},
} as any)
).toEqual({
a: {
name: 'a',
type: { name: 'object', value: { foo: { name: 'other', value: 'cyclic object' } } },
},
});
expect(logger.warn).toHaveBeenCalled();
});
it('ensures names', () => {
(logger.warn as jest.MockedFunction<typeof logger.warn>).mockClear();
expect(
inferArgTypes({
initialArgs: {
a: 1,
},
argTypes: {
a: {
control: {
type: 'range',
},
},
},
} as any)
).toEqual({
a: {
name: 'a',
type: { name: 'number' },
control: { type: 'range' },
},
});
});
it('ensures names even with no arg', () => {
(logger.warn as jest.MockedFunction<typeof logger.warn>).mockClear();
expect(
inferArgTypes({
argTypes: {
a: {
type: {
name: 'string',
},
},
},
} as any)
).toEqual({
a: {
name: 'a',
type: { name: 'string' },
},
});
});
});
|
1,181 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/inferControls.test.ts | import { expect } from '@jest/globals';
import { logger } from '@storybook/client-logger';
import type { StoryContextForEnhancers } from '@storybook/types';
import { argTypesEnhancers } from './inferControls';
const getStoryContext = (overrides: any = {}): StoryContextForEnhancers => ({
id: '',
title: '',
kind: '',
name: '',
story: '',
initialArgs: {},
argTypes: {
label: { control: 'text' },
labelName: { control: 'text' },
borderWidth: { control: { type: 'number', min: 0, max: 10 } },
},
...overrides,
parameters: {
__isArgsStory: true,
...overrides.parameters,
},
});
const [inferControls] = argTypesEnhancers;
describe('inferControls', () => {
describe('with custom matchers', () => {
let warnSpy: jest.SpyInstance;
beforeEach(() => {
warnSpy = jest.spyOn(logger, 'warn');
warnSpy.mockImplementation(() => {});
});
afterEach(() => {
warnSpy.mockRestore();
});
it('should return color type when using color matcher', () => {
// passing a string, should return control type color
const inferredControls = inferControls(
getStoryContext({
argTypes: {
background: {
type: {
name: 'string',
},
name: 'background',
},
},
parameters: {
controls: {
matchers: {
color: /background/,
},
},
},
})
);
expect(inferredControls.background.control.type).toEqual('color');
});
it('should return inferred type when using color matcher but arg passed is not a string', () => {
const sampleTypes = [
{
name: 'object',
value: {
rgb: {
name: 'number',
},
},
},
{ name: 'number' },
{ name: 'boolean' },
];
sampleTypes.forEach((type) => {
const inferredControls = inferControls(
getStoryContext({
argTypes: {
background: {
// passing an object which is unsupported
// should ignore color control and infer the type instead
type,
name: 'background',
},
},
parameters: {
controls: {
matchers: {
color: /background/,
},
},
},
})
);
expect(warnSpy).toHaveBeenCalled();
expect(inferredControls.background.control.type).toEqual(type.name);
});
});
});
it('should return argTypes as is when no exclude or include is passed', () => {
const controls = inferControls(getStoryContext());
expect(Object.keys(controls)).toEqual(['label', 'labelName', 'borderWidth']);
});
it('should return filtered argTypes when include is passed', () => {
const [includeString, includeArray, includeRegex] = [
inferControls(getStoryContext({ parameters: { controls: { include: 'label' } } })),
inferControls(getStoryContext({ parameters: { controls: { include: ['label'] } } })),
inferControls(getStoryContext({ parameters: { controls: { include: /label*/ } } })),
];
expect(Object.keys(includeString)).toEqual(['label', 'labelName']);
expect(Object.keys(includeArray)).toEqual(['label']);
expect(Object.keys(includeRegex)).toEqual(['label', 'labelName']);
});
it('should return filtered argTypes when exclude is passed', () => {
const [excludeString, excludeArray, excludeRegex] = [
inferControls(getStoryContext({ parameters: { controls: { exclude: 'label' } } })),
inferControls(getStoryContext({ parameters: { controls: { exclude: ['label'] } } })),
inferControls(getStoryContext({ parameters: { controls: { exclude: /label*/ } } })),
];
expect(Object.keys(excludeString)).toEqual(['borderWidth']);
expect(Object.keys(excludeArray)).toEqual(['labelName', 'borderWidth']);
expect(Object.keys(excludeRegex)).toEqual(['borderWidth']);
});
});
|
1,183 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/parameters.test.ts | import { expect } from '@jest/globals';
import { combineParameters } from './parameters';
describe('client-api.parameters', () => {
it('merges different sets of parameters by key, preferencing last', () => {
expect(combineParameters({ a: 'b', c: 'd' }, { e: 'f', a: 'g' })).toEqual({
a: 'g',
c: 'd',
e: 'f',
});
});
it('merges sub-keys', () => {
expect(combineParameters({ ns: { a: 'b', c: 'd' } }, { ns: { e: 'f', a: 'g' } })).toEqual({
ns: {
a: 'g',
c: 'd',
e: 'f',
},
});
});
it('treats array values as scalars', () => {
expect(combineParameters({ ns: { array: [1, 2, 3] } }, { ns: { array: [3, 4, 5] } })).toEqual({
ns: {
array: [3, 4, 5],
},
});
});
it('ignores undefined additions', () => {
expect(combineParameters({ a: 1 }, { a: 2 }, { a: undefined })).toEqual({ a: 2 });
});
});
|
1,186 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/storySort.test.ts | import { expect, describe, it } from '@jest/globals';
import type { StoryId, StoryIndexEntry } from '@storybook/types';
import { storySort } from './storySort';
describe('preview.storySort', () => {
const fixture: Record<StoryId, StoryIndexEntry> = Object.fromEntries(
Object.entries({
a: { title: 'a' },
á: { title: 'á' },
A: { title: 'A' },
b: { title: 'b' },
a_a: { title: 'a / a' },
a_b: { title: 'a / b' },
a_c: { title: 'a / c' },
b_a_a: { title: 'b / a / a' },
b_b: { title: 'b / b' },
c: { title: 'c' },
locale1: { title: 'Б' },
locale2: { title: 'Г' },
c__a: { title: 'c', name: 'a' },
c_b__a: { title: 'c / b', name: 'a' },
c_b__b: { title: 'c / b', name: 'b' },
c_b__c: { title: 'c / b', name: 'c' },
c__c: { title: 'c', name: 'c' },
}).map(([id, entry]) => [id, { type: 'story', name: 'name', ...entry, id, importPath: id }])
);
it('uses configure order by default', () => {
const sortFn = storySort();
expect(sortFn(fixture.a, fixture.b)).toBe(0);
expect(sortFn(fixture.b, fixture.a)).toBe(0);
expect(sortFn(fixture.a, fixture.a)).toBe(0);
});
it('can sort shallow titles alphabetically', () => {
const sortFn = storySort({ method: 'alphabetical' });
expect(sortFn(fixture.a, fixture.b)).toBeLessThan(0);
expect(sortFn(fixture.b, fixture.a)).toBeGreaterThan(0);
expect(sortFn(fixture.a, fixture.á)).toBeLessThan(0);
expect(sortFn(fixture.á, fixture.a)).toBeGreaterThan(0);
});
it('can sort deep titles alphabetically', () => {
const sortFn = storySort({ method: 'alphabetical' });
expect(sortFn(fixture.a_a, fixture.a_b)).toBeLessThan(0);
expect(sortFn(fixture.a_b, fixture.a_a)).toBeGreaterThan(0);
expect(sortFn(fixture.a_a, fixture.b)).toBeLessThan(0);
expect(sortFn(fixture.b, fixture.a_a)).toBeGreaterThan(0);
expect(sortFn(fixture.a_a, fixture.a)).toBeGreaterThan(0);
expect(sortFn(fixture.a, fixture.a_a)).toBeLessThan(0);
expect(sortFn(fixture.b_a_a, fixture.b_b)).toBeLessThan(0);
expect(sortFn(fixture.b_b, fixture.b_a_a)).toBeGreaterThan(0);
});
it('ignores case when sorting alphabetically', () => {
const sortFn = storySort({ method: 'alphabetical' });
expect(sortFn(fixture.a, fixture.A)).toBe(0);
expect(sortFn(fixture.A, fixture.a)).toBe(0);
});
it('sorts alphabetically using the given locales', () => {
const sortFn = storySort({ method: 'alphabetical', locales: 'ru-RU' });
expect(sortFn(fixture.locale1, fixture.locale2)).toBeLessThan(0);
expect(sortFn(fixture.locale2, fixture.locale1)).toBeGreaterThan(0);
});
it('sorts according to the order array', () => {
const sortFn = storySort({ order: ['b', 'c'] });
expect(sortFn(fixture.a, fixture.b)).toBeGreaterThan(0);
expect(sortFn(fixture.b, fixture.a)).toBeLessThan(0);
expect(sortFn(fixture.b_a_a, fixture.b_b)).toBe(0);
expect(sortFn(fixture.b_b, fixture.b_a_a)).toBe(0);
});
it('sorts according to the nested order array', () => {
const sortFn = storySort({ order: ['a', ['b', 'c'], 'c'] });
expect(sortFn(fixture.a_a, fixture.a_b)).toBeGreaterThan(0);
expect(sortFn(fixture.a_b, fixture.a_a)).toBeLessThan(0);
});
it('sorts alphabetically including story names', () => {
const sortFn = storySort({ method: 'alphabetical', includeNames: true });
expect(sortFn(fixture.c_b__a, fixture.c__a)).toBeGreaterThan(0);
expect(sortFn(fixture.c__a, fixture.c_b__a)).toBeLessThan(0);
expect(sortFn(fixture.c__c, fixture.c__a)).toBeGreaterThan(0);
expect(sortFn(fixture.c__a, fixture.c__c)).toBeLessThan(0);
});
it('sorts according to the order array including story names', () => {
const sortFn = storySort({
order: ['c', ['b', ['c', 'b', 'a'], 'c', 'a']],
includeNames: true,
});
expect(sortFn(fixture.c_b__a, fixture.c_b__b)).toBeGreaterThan(0);
expect(sortFn(fixture.c_b__b, fixture.c_b__c)).toBeGreaterThan(0);
expect(sortFn(fixture.c_b__a, fixture.c_b__c)).toBeGreaterThan(0);
expect(sortFn(fixture.c_b__a, fixture.c__a)).toBeLessThan(0);
expect(sortFn(fixture.c_b__a, fixture.c__c)).toBeLessThan(0);
expect(sortFn(fixture.c__a, fixture.c__c)).toBeGreaterThan(0);
});
it('sorts according to the order array with a wildcard', () => {
const sortFn = storySort({ order: ['a', '*', 'b'] });
expect(sortFn(fixture.a, fixture.b)).toBeLessThan(0);
expect(sortFn(fixture.c, fixture.b)).toBeLessThan(0);
expect(sortFn(fixture.b, fixture.c)).toBeGreaterThan(0);
expect(sortFn(fixture.b, fixture.a)).toBeGreaterThan(0);
});
it('sorts according to the nested order array with wildcard', () => {
const sortFn = storySort({ order: ['a', ['a', '*', 'b'], 'c'] });
expect(sortFn(fixture.a, fixture.c)).toBeLessThan(0);
expect(sortFn(fixture.c, fixture.a)).toBeGreaterThan(0);
expect(sortFn(fixture.a_a, fixture.a_b)).toBeLessThan(0);
expect(sortFn(fixture.a_b, fixture.a_a)).toBeGreaterThan(0);
expect(sortFn(fixture.a_a, fixture.a_c)).toBeLessThan(0);
expect(sortFn(fixture.a_c, fixture.a_a)).toBeGreaterThan(0);
expect(sortFn(fixture.a_c, fixture.a_b)).toBeLessThan(0);
expect(sortFn(fixture.a_b, fixture.a_c)).toBeGreaterThan(0);
});
it('sorts according to the nested order array with parent wildcard', () => {
const sortFn = storySort({
order: ['*', ['*', 'b', 'a']],
includeNames: true,
});
expect(sortFn(fixture.a_a, fixture.a_b)).toBeGreaterThan(0);
expect(sortFn(fixture.a_b, fixture.a_a)).toBeLessThan(0);
expect(sortFn(fixture.a_c, fixture.a_a)).toBeLessThan(0);
expect(sortFn(fixture.a_c, fixture.a_b)).toBeLessThan(0);
expect(sortFn(fixture.a_a, fixture.a_c)).toBeGreaterThan(0);
expect(sortFn(fixture.a_b, fixture.a_c)).toBeGreaterThan(0);
expect(sortFn(fixture.a_a, fixture.a_a)).toBe(0);
});
});
|
1,188 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/csf/composeConfigs.test.ts | import { expect } from '@jest/globals';
import { global } from '@storybook/global';
import { composeConfigs } from './composeConfigs';
jest.mock('@storybook/global', () => ({
global: {
FEATURES: {},
},
}));
describe('composeConfigs', () => {
it('sets default (empty) values for fields', () => {
expect(composeConfigs([])).toEqual({
parameters: {},
decorators: [],
args: {},
argsEnhancers: [],
argTypes: {},
argTypesEnhancers: [],
globals: {},
globalTypes: {},
loaders: [],
runStep: expect.any(Function),
});
});
it('composes parameters', () => {
expect(
composeConfigs([
{
parameters: { obj: { a: '1', b: '1' } },
},
{
parameters: { obj: { a: '2', c: '2' } },
},
])
).toEqual({
parameters: { obj: { a: '2', b: '1', c: '2' } },
decorators: [],
args: {},
argsEnhancers: [],
argTypes: {},
argTypesEnhancers: [],
globals: {},
globalTypes: {},
loaders: [],
runStep: expect.any(Function),
});
});
it('composes export defaults', () => {
expect(
composeConfigs([
{
default: {
parameters: { obj: { a: '1', b: '1' } },
},
},
{
default: {
parameters: { obj: { a: '2', c: '2' } },
},
},
])
).toEqual({
parameters: { obj: { a: '2', b: '1', c: '2' } },
decorators: [],
args: {},
argsEnhancers: [],
argTypes: {},
argTypesEnhancers: [],
globals: {},
globalTypes: {},
loaders: [],
runStep: expect.any(Function),
});
});
it('overrides object fields by key', () => {
expect(
composeConfigs([
{
default: {
args: { x: '1', y: '1', obj: { a: '1', b: '1' } },
argTypes: { x: '1', y: '1', obj: { a: '1', b: '1' } },
globals: { x: '1', y: '1', obj: { a: '1', b: '1' } },
globalTypes: { x: '1', y: '1', obj: { a: '1', b: '1' } },
},
},
{
default: {
args: { x: '2', z: '2', obj: { a: '2', c: '2' } },
argTypes: { x: '2', z: '2', obj: { a: '2', c: '2' } },
globals: { x: '2', z: '2', obj: { a: '2', c: '2' } },
globalTypes: { x: '2', z: '2', obj: { a: '2', c: '2' } },
},
},
])
).toEqual({
parameters: {},
decorators: [],
args: { x: '2', y: '1', z: '2', obj: { a: '2', c: '2' } },
argsEnhancers: [],
argTypes: { x: '2', y: '1', z: '2', obj: { a: '2', c: '2' } },
argTypesEnhancers: [],
globals: { x: '2', y: '1', z: '2', obj: { a: '2', c: '2' } },
globalTypes: { x: '2', y: '1', z: '2', obj: { a: '2', c: '2' } },
loaders: [],
runStep: expect.any(Function),
});
});
it('overrides object fields by key with mixed named and default exports', () => {
expect(
// configs could come from user, addons, presets, frameworks.. so they will likely be mixed in format
composeConfigs([
{
default: {
args: { x: '1', y: '1', obj: { a: '1', b: '1' } },
argTypes: { x: '1', y: '1', obj: { a: '1', b: '1' } },
globals: { x: '1', y: '1', obj: { a: '1', b: '1' } },
globalTypes: { x: '1', y: '1', obj: { a: '1', b: '1' } },
},
},
{
args: { x: '2', z: '2', obj: { a: '2', c: '2' } },
argTypes: { x: '2', z: '2', obj: { a: '2', c: '2' } },
globals: { x: '2', z: '2', obj: { a: '2', c: '2' } },
},
{
default: {
globalTypes: { x: '2', z: '2', obj: { a: '2', c: '2' } },
},
},
])
).toEqual({
parameters: {},
decorators: [],
args: { x: '2', y: '1', z: '2', obj: { a: '2', c: '2' } },
argsEnhancers: [],
argTypes: { x: '2', y: '1', z: '2', obj: { a: '2', c: '2' } },
argTypesEnhancers: [],
globals: { x: '2', y: '1', z: '2', obj: { a: '2', c: '2' } },
globalTypes: { x: '2', y: '1', z: '2', obj: { a: '2', c: '2' } },
loaders: [],
runStep: expect.any(Function),
});
});
it('concats array fields', () => {
expect(
composeConfigs([
{
argsEnhancers: ['1', '2'],
argTypesEnhancers: ['1', '2'],
loaders: ['1', '2'],
},
{
argsEnhancers: ['3', '4'],
argTypesEnhancers: ['3', '4'],
loaders: ['3', '4'],
},
])
).toEqual({
parameters: {},
decorators: [],
args: {},
argsEnhancers: ['1', '2', '3', '4'],
argTypes: {},
argTypesEnhancers: ['1', '2', '3', '4'],
globals: {},
globalTypes: {},
loaders: ['1', '2', '3', '4'],
runStep: expect.any(Function),
});
});
it('combines decorators in reverse file order', () => {
expect(
composeConfigs([
{
decorators: ['1', '2'],
},
{
decorators: ['3', '4'],
},
])
).toEqual({
parameters: {},
decorators: ['3', '4', '1', '2'],
args: {},
argsEnhancers: [],
argTypes: {},
argTypesEnhancers: [],
globals: {},
globalTypes: {},
loaders: [],
runStep: expect.any(Function),
});
});
it('concats argTypesEnhancers in two passes', () => {
expect(
composeConfigs([
{ argTypesEnhancers: [{ a: '1' }, { a: '2', secondPass: true }] },
{ argTypesEnhancers: [{ a: '3' }, { a: '4', secondPass: true }] },
])
).toEqual({
parameters: {},
decorators: [],
args: {},
argsEnhancers: [],
argTypes: {},
argTypesEnhancers: [
{ a: '1' },
{ a: '3' },
{ a: '2', secondPass: true },
{ a: '4', secondPass: true },
],
globals: {},
globalTypes: {},
loaders: [],
runStep: expect.any(Function),
});
});
it('concats chooses scalar fields', () => {
expect(
composeConfigs([
{
render: 'render-1',
renderToCanvas: 'renderToCanvas-1',
applyDecorators: 'applyDecorators-1',
},
{
render: 'render-2',
renderToCanvas: 'renderToCanvas-2',
applyDecorators: 'applyDecorators-2',
},
])
).toEqual({
parameters: {},
decorators: [],
args: {},
argsEnhancers: [],
argTypes: {},
argTypesEnhancers: [],
globals: {},
globalTypes: {},
loaders: [],
render: 'render-2',
renderToCanvas: 'renderToCanvas-2',
applyDecorators: 'applyDecorators-2',
runStep: expect.any(Function),
});
});
it('composes step runners', () => {
const fn = jest.fn();
const { runStep } = composeConfigs([
// @ts-expect-error (not defined)
{ runStep: (label, play, context) => fn(`${label}1`, play(context)) },
// @ts-expect-error (not defined)
{ runStep: (label, play, context) => fn(`${label}2`, play(context)) },
// @ts-expect-error (not defined)
{ runStep: (label, play, context) => fn(`${label}3`, play(context)) },
]);
// @ts-expect-error We don't care about the context value here
runStep('Label', () => {}, {});
expect(fn).toHaveBeenCalledTimes(3);
expect(fn).toHaveBeenNthCalledWith(1, 'Label3', expect.anything());
expect(fn).toHaveBeenNthCalledWith(2, 'Label2', expect.anything());
expect(fn).toHaveBeenNthCalledWith(3, 'Label1', expect.anything());
});
describe('FEATURES.legacyDecoratorFileOrder set to true', () => {
beforeEach(() => {
global.FEATURES!.legacyDecoratorFileOrder = true;
});
afterEach(() => {
global.FEATURES!.legacyDecoratorFileOrder = false;
});
it('should merge decorators in the order they are defined file-wise', () => {
expect(
composeConfigs([
{
decorators: ['1', '2'],
},
{
decorators: ['3', '4'],
},
])
).toMatchObject({
decorators: ['1', '2', '3', '4'],
});
});
});
});
|
1,194 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/csf/normalizeInputTypes.test.ts | import { expect } from '@jest/globals';
import { normalizeInputType, normalizeInputTypes } from './normalizeInputTypes';
describe('normalizeInputType', () => {
it('does nothing to strict types', () => {
expect(
normalizeInputType(
{
name: 'name',
type: { name: 'string' },
control: { type: 'text' },
description: 'description',
defaultValue: 'defaultValue',
},
'arg'
)
).toEqual({
name: 'name',
type: { name: 'string' },
control: { type: 'text' },
description: 'description',
defaultValue: 'defaultValue',
});
});
it('fills in unstrict types', () => {
expect(
normalizeInputType(
{
type: 'string',
control: 'text',
description: 'description',
defaultValue: 'defaultValue',
},
'arg'
)
).toEqual({
name: 'arg',
type: { name: 'string' },
control: { type: 'text' },
description: 'description',
defaultValue: 'defaultValue',
});
});
it('preserves disabled control via shortcut', () => {
expect(
normalizeInputType(
{
type: 'string',
control: false,
description: 'description',
defaultValue: 'defaultValue',
},
'arg'
)
).toEqual({
name: 'arg',
type: { name: 'string' },
control: { disable: true },
description: 'description',
defaultValue: 'defaultValue',
});
});
});
describe('normalizeInputTypes', () => {
it('maps over keys', () => {
expect(
normalizeInputTypes({
a: { type: 'string' },
b: { type: 'number' },
})
).toEqual({
a: { name: 'a', type: { name: 'string' } },
b: { name: 'b', type: { name: 'number' } },
});
});
});
|
1,197 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/csf/normalizeStory.test.ts | import { expect, describe, it } from '@jest/globals';
import type { Renderer, StoryAnnotationsOrFn } from '@storybook/types';
import { normalizeStory } from './normalizeStory';
describe('normalizeStory', () => {
describe('id generation', () => {
it('respects component id', () => {
expect(normalizeStory('name', {}, { title: 'title', id: 'component-id' }).id).toEqual(
'component-id--name'
);
});
it('respects parameters.__id', () => {
expect(
normalizeStory(
'name',
{ parameters: { __id: 'story-id' } },
{ title: 'title', id: 'component-id' }
).id
).toEqual('story-id');
});
});
describe('name', () => {
it('preferences story.name over story.storyName', () => {
expect(
normalizeStory(
'export',
{ name: 'name', storyName: 'storyName' },
{ id: 'title', title: 'title' }
).name
).toEqual('name');
expect(
normalizeStory('export', { storyName: 'storyName' }, { id: 'title', title: 'title' }).name
).toEqual('storyName');
});
it('falls back to capitalized export name', () => {
expect(normalizeStory('exportOne', {}, { id: 'title', title: 'title' }).name).toEqual(
'Export One'
);
});
});
describe('user-provided story function', () => {
it('should normalize into an object', () => {
const storyFn = () => {};
const meta = { id: 'title', title: 'title' };
expect(normalizeStory('storyExport', storyFn, meta)).toMatchInlineSnapshot(`
Object {
"argTypes": Object {},
"args": Object {},
"decorators": Array [],
"id": "title--story-export",
"loaders": Array [],
"moduleExport": [Function],
"name": "Story Export",
"parameters": Object {},
"tags": Array [],
"userStoryFn": [Function],
}
`);
});
});
describe('user-provided story object', () => {
describe('render function', () => {
it('implicit render function', () => {
const storyObj = {};
const meta = { id: 'title', title: 'title' };
const normalized = normalizeStory('storyExport', storyObj, meta);
expect(normalized.render).toBeUndefined();
});
it('user-provided story render function', () => {
const storyObj = { render: jest.fn() };
const meta = { id: 'title', title: 'title', render: jest.fn() };
const normalized = normalizeStory('storyExport', storyObj, meta);
expect(normalized.render).toBe(storyObj.render);
});
it('user-provided meta render function', () => {
const storyObj = {};
const meta = { id: 'title', title: 'title', render: jest.fn() };
const normalized = normalizeStory('storyExport', storyObj, meta);
expect(normalized.render).toBeUndefined();
});
});
describe('play function', () => {
it('no render function', () => {
const storyObj = {};
const meta = { id: 'title', title: 'title' };
const normalized = normalizeStory('storyExport', storyObj, meta);
expect(normalized.play).toBeUndefined();
});
it('user-provided story render function', () => {
const storyObj = { play: jest.fn() };
const meta = { id: 'title', title: 'title', play: jest.fn() };
const normalized = normalizeStory('storyExport', storyObj, meta);
expect(normalized.play).toBe(storyObj.play);
});
it('user-provided meta render function', () => {
const storyObj = {};
const meta = { id: 'title', title: 'title', play: jest.fn() };
const normalized = normalizeStory('storyExport', storyObj, meta);
expect(normalized.play).toBeUndefined();
});
});
describe('annotations', () => {
it('empty annotations', () => {
const storyObj = {};
const meta = { id: 'title', title: 'title' };
const normalized = normalizeStory('storyExport', storyObj, meta);
expect(normalized).toMatchInlineSnapshot(`
Object {
"argTypes": Object {},
"args": Object {},
"decorators": Array [],
"id": "title--story-export",
"loaders": Array [],
"moduleExport": Object {},
"name": "Story Export",
"parameters": Object {},
"tags": Array [],
}
`);
expect(normalized.moduleExport).toBe(storyObj);
});
it('full annotations', () => {
const storyObj: StoryAnnotationsOrFn<Renderer> = {
name: 'story name',
parameters: { storyParam: 'val' },
decorators: [() => {}],
loaders: [async () => ({})],
args: { storyArg: 'val' },
argTypes: { storyArgType: { type: 'string' } },
};
const meta = { id: 'title', title: 'title' };
const { moduleExport, ...normalized } = normalizeStory('storyExport', storyObj, meta);
expect(normalized).toMatchInlineSnapshot(`
Object {
"argTypes": Object {
"storyArgType": Object {
"name": "storyArgType",
"type": Object {
"name": "string",
},
},
},
"args": Object {
"storyArg": "val",
},
"decorators": Array [
[Function],
],
"id": "title--story-export",
"loaders": Array [
[Function],
],
"name": "story name",
"parameters": Object {
"storyParam": "val",
},
"tags": Array [],
}
`);
expect(moduleExport).toBe(storyObj);
});
it('prefers new annotations to legacy, but combines', () => {
const storyObj: StoryAnnotationsOrFn<Renderer> = {
name: 'story name',
parameters: { storyParam: 'val' },
decorators: [() => {}],
loaders: [async () => ({})],
args: { storyArg: 'val' },
argTypes: { storyArgType: { type: 'string' } },
story: {
parameters: { storyParam2: 'legacy' },
decorators: [() => {}],
loaders: [async () => ({})],
args: { storyArg2: 'legacy' },
argTypes: { storyArgType2: { type: 'string' } },
},
};
const meta = { id: 'title', title: 'title' };
const { moduleExport, ...normalized } = normalizeStory('storyExport', storyObj, meta);
expect(normalized).toMatchInlineSnapshot(`
Object {
"argTypes": Object {
"storyArgType": Object {
"name": "storyArgType",
"type": Object {
"name": "string",
},
},
"storyArgType2": Object {
"name": "storyArgType2",
"type": Object {
"name": "string",
},
},
},
"args": Object {
"storyArg": "val",
"storyArg2": "legacy",
},
"decorators": Array [
[Function],
[Function],
],
"id": "title--story-export",
"loaders": Array [
[Function],
[Function],
],
"name": "story name",
"parameters": Object {
"storyParam": "val",
"storyParam2": "legacy",
},
"tags": Array [],
}
`);
expect(moduleExport).toBe(storyObj);
});
});
});
});
|
1,199 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/csf/prepareStory.test.ts | /// <reference types="@types/jest" />;
import { global } from '@storybook/global';
import { expect } from '@jest/globals';
import type { Renderer, ArgsEnhancer, PlayFunctionContext, SBScalarType } from '@storybook/types';
import { addons, HooksContext } from '../../addons';
import { UNTARGETED } from '../args';
import { prepareStory, prepareMeta, prepareContext } from './prepareStory';
jest.mock('@storybook/global', () => ({
global: {
...(jest.requireActual('@storybook/global') as any),
},
}));
const id = 'id';
const name = 'name';
const title = 'title';
const render = (args: any) => {};
const moduleExport = {};
const stringType: SBScalarType = { name: 'string' };
const numberType: SBScalarType = { name: 'number' };
const booleanType: SBScalarType = { name: 'boolean' };
// Extra fields that must be added to the story context after enhancers
const storyContextExtras = () => ({
hooks: new HooksContext(),
viewMode: 'story' as const,
loaded: {},
abortSignal: new AbortController().signal,
canvasElement: {},
});
describe('prepareStory', () => {
describe('tags', () => {
it('story tags override component', () => {
const { tags } = prepareStory(
{ id, name, tags: ['story-1', 'story-2'], moduleExport },
{
id,
title,
tags: ['component-1', 'component-2'],
},
{ render }
);
expect(tags).toEqual(['story-1', 'story-2', 'story']);
});
it('component tags work if story are unset', () => {
const { tags } = prepareStory(
{ id, name, moduleExport },
{
id,
title,
tags: ['component-1', 'component-2'],
},
{ render }
);
expect(tags).toEqual(['component-1', 'component-2', 'story']);
});
it('sets a value even if annotations do not have tags', () => {
const { tags } = prepareStory({ id, name, moduleExport }, { id, title }, { render });
expect(tags).toEqual(['story']);
});
});
describe('parameters', () => {
it('are combined in the right order', () => {
const { parameters } = prepareStory(
{ id, name, parameters: { a: 'story', nested: { z: 'story' } }, moduleExport },
{
id,
title,
parameters: {
a: { name: 'component' },
b: { name: 'component' },
nested: { z: { name: 'component' }, y: { name: 'component' } },
},
},
{
render,
parameters: {
a: { name: 'global' },
b: { name: 'global' },
c: { name: 'global' },
nested: { z: { name: 'global' }, x: { name: 'global' } },
},
}
);
expect(parameters).toEqual({
__isArgsStory: true,
a: 'story',
b: { name: 'component' },
c: { name: 'global' },
nested: { z: 'story', y: { name: 'component' }, x: { name: 'global' } },
});
});
it('sets a value even if annotations do not have parameters', () => {
const { parameters } = prepareStory({ id, name, moduleExport }, { id, title }, { render });
expect(parameters).toEqual({ __isArgsStory: true });
});
it('does not set `__isArgsStory` if `passArgsFirst` is disabled', () => {
const { parameters } = prepareStory(
{ id, name, parameters: { passArgsFirst: false }, moduleExport },
{ id, title },
{ render }
);
expect(parameters).toEqual({ passArgsFirst: false, __isArgsStory: false });
});
it('does not set `__isArgsStory` if `render` does not take args', () => {
const { parameters } = prepareStory(
{ id, name, moduleExport },
{ id, title },
{ render: () => {} }
);
expect(parameters).toEqual({ __isArgsStory: false });
});
});
describe('args/initialArgs', () => {
it('are combined in the right order', () => {
const { initialArgs } = prepareStory(
{ id, name, args: { a: 'story', nested: { z: 'story' } }, moduleExport },
{
id,
title,
args: {
a: 'component',
b: 'component',
nested: { z: 'component', y: 'component' },
},
},
{
render,
args: {
a: 'global',
b: 'global',
c: 'global',
nested: { z: 'global', x: 'global' },
},
}
);
expect(initialArgs).toEqual({
a: 'story',
b: 'component',
c: 'global',
nested: { z: 'story' },
});
});
it('can be overriden by `undefined`', () => {
const { initialArgs } = prepareStory(
{ id, name, args: { a: undefined }, moduleExport },
{ id, title, args: { a: 'component' } },
{ render }
);
expect(initialArgs).toEqual({ a: undefined });
});
it('sets a value even if annotations do not have args', () => {
const { initialArgs } = prepareStory({ id, name, moduleExport }, { id, title }, { render });
expect(initialArgs).toEqual({});
});
describe('argsEnhancers', () => {
it('are applied in the right order', () => {
const run: number[] = [];
const enhancerOne: ArgsEnhancer<Renderer> = () => {
run.push(1);
return {};
};
const enhancerTwo: ArgsEnhancer<Renderer> = () => {
run.push(2);
return {};
};
prepareStory(
{ id, name, moduleExport },
{ id, title },
{ render, argsEnhancers: [enhancerOne, enhancerTwo] }
);
expect(run).toEqual([1, 2]);
});
it('allow you to add args', () => {
const enhancer = jest.fn(() => ({ c: 'd' }));
const { initialArgs } = prepareStory(
{ id, name, args: { a: 'b' }, moduleExport },
{ id, title },
{ render, argsEnhancers: [enhancer] }
);
expect(enhancer).toHaveBeenCalledWith(expect.objectContaining({ initialArgs: { a: 'b' } }));
expect(initialArgs).toEqual({ a: 'b', c: 'd' });
});
it('passes result of earlier enhancers into subsequent ones, and composes their output', () => {
const enhancerOne = jest.fn(() => ({ b: 'B' }));
const enhancerTwo = jest.fn(({ initialArgs }) =>
Object.entries(initialArgs).reduce(
(acc, [key, val]) => ({ ...acc, [key]: `enhanced ${val}` }),
{}
)
);
const enhancerThree = jest.fn(() => ({ c: 'C' }));
const { initialArgs } = prepareStory(
{ id, name, args: { a: 'A' }, moduleExport },
{ id, title },
{ render, argsEnhancers: [enhancerOne, enhancerTwo, enhancerThree] }
);
expect(enhancerOne).toHaveBeenCalledWith(
expect.objectContaining({ initialArgs: { a: 'A' } })
);
expect(enhancerTwo).toHaveBeenCalledWith(
expect.objectContaining({ initialArgs: { a: 'A', b: 'B' } })
);
expect(enhancerThree).toHaveBeenCalledWith(
expect.objectContaining({ initialArgs: { a: 'enhanced A', b: 'enhanced B' } })
);
expect(initialArgs).toEqual({
a: 'enhanced A',
b: 'enhanced B',
c: 'C',
});
});
});
});
describe('argTypes', () => {
it('are combined in the right order', () => {
const { argTypes } = prepareStory(
{
id,
name,
argTypes: {
a: { name: 'a-story', type: booleanType },
nested: { name: 'nested', type: booleanType, a: 'story' },
},
moduleExport,
},
{
id,
title,
argTypes: {
a: { name: 'a-component', type: stringType },
b: { name: 'b-component', type: stringType },
nested: { name: 'nested', type: booleanType, a: 'component', b: 'component' },
},
},
{
render,
argTypes: {
a: { name: 'a-global', type: numberType },
b: { name: 'b-global', type: numberType },
c: { name: 'c-global', type: numberType },
nested: { name: 'nested', type: booleanType, a: 'global', b: 'global', c: 'global' },
},
}
);
expect(argTypes).toEqual({
a: { name: 'a-story', type: booleanType },
b: { name: 'b-component', type: stringType },
c: { name: 'c-global', type: numberType },
nested: { name: 'nested', type: booleanType, a: 'story', b: 'component', c: 'global' },
});
});
describe('argTypesEnhancers', () => {
it('allows you to alter argTypes when stories are added', () => {
const enhancer = jest.fn((context) => ({ ...context.argTypes, c: { name: 'd' } }));
const { argTypes } = prepareStory(
{ id, name, argTypes: { a: { name: 'b' } }, moduleExport },
{ id, title },
{ render, argTypesEnhancers: [enhancer] }
);
expect(enhancer).toHaveBeenCalledWith(
expect.objectContaining({ argTypes: { a: { name: 'b' } } })
);
expect(argTypes).toEqual({ a: { name: 'b' }, c: { name: 'd' } });
});
it('does not merge argType enhancer results', () => {
const enhancer = jest.fn(() => ({ c: { name: 'd' } }));
const { argTypes } = prepareStory(
{ id, name, argTypes: { a: { name: 'b' } }, moduleExport },
{ id, title },
{ render, argTypesEnhancers: [enhancer] }
);
expect(enhancer).toHaveBeenCalledWith(
expect.objectContaining({ argTypes: { a: { name: 'b' } } })
);
expect(argTypes).toEqual({ c: { name: 'd' } });
});
it('recursively passes argTypes to successive enhancers', () => {
const firstEnhancer = jest.fn((context) => ({ ...context.argTypes, c: { name: 'd' } }));
const secondEnhancer = jest.fn((context) => ({ ...context.argTypes, e: { name: 'f' } }));
const { argTypes } = prepareStory(
{ id, name, argTypes: { a: { name: 'b' } }, moduleExport },
{ id, title },
{ render, argTypesEnhancers: [firstEnhancer, secondEnhancer] }
);
expect(firstEnhancer).toHaveBeenCalledWith(
expect.objectContaining({ argTypes: { a: { name: 'b' } } })
);
expect(secondEnhancer).toHaveBeenCalledWith(
expect.objectContaining({ argTypes: { a: { name: 'b' }, c: { name: 'd' } } })
);
expect(argTypes).toEqual({ a: { name: 'b' }, c: { name: 'd' }, e: { name: 'f' } });
});
});
});
describe('applyLoaders', () => {
it('awaits the result of a loader', async () => {
const loader = jest.fn(async () => new Promise((r) => setTimeout(() => r({ foo: 7 }), 100)));
const { applyLoaders } = prepareStory(
{ id, name, loaders: [loader as any], moduleExport },
{ id, title },
{ render }
);
const storyContext = { context: 'value' } as any;
const loadedContext = await applyLoaders({ ...storyContext });
expect(loader).toHaveBeenCalledWith({ ...storyContext, loaded: {} });
expect(loadedContext).toEqual({
context: 'value',
loaded: { foo: 7 },
});
});
it('loaders are composed in the right order', async () => {
const globalLoader = async () => ({ foo: 1, bar: 1, baz: 1 });
const componentLoader = async () => ({ foo: 3, bar: 3 });
const storyLoader = async () => ({ foo: 5 });
const { applyLoaders } = prepareStory(
{ id, name, loaders: [storyLoader], moduleExport },
{ id, title, loaders: [componentLoader] },
{ render, loaders: [globalLoader] }
);
const storyContext = { context: 'value' } as any;
const loadedContext = await applyLoaders(storyContext);
expect(loadedContext).toEqual({
context: 'value',
loaded: { foo: 5, bar: 3, baz: 1 },
});
});
it('later loaders override earlier loaders', async () => {
const loaders: any[] = [
async () => new Promise((r) => setTimeout(() => r({ foo: 7 }), 100)),
async () => new Promise((r) => setTimeout(() => r({ foo: 3 }), 50)),
];
const { applyLoaders } = prepareStory(
{ id, name, loaders, moduleExport },
{ id, title },
{ render }
);
const storyContext = { context: 'value' } as any;
const loadedContext = await applyLoaders(storyContext);
expect(loadedContext).toEqual({
context: 'value',
loaded: { foo: 3 },
});
});
});
describe('undecoratedStoryFn', () => {
it('args are mapped by argTypes[x].mapping', () => {
const renderMock = jest.fn();
const story = prepareStory(
{
id,
name,
argTypes: {
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped' } },
two: { name: 'two', type: { name: 'string' }, mapping: { 1: 'no match' } },
},
args: { one: 1, two: 2, three: 3 },
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = prepareContext({ args: story.initialArgs, globals: {}, ...story });
story.undecoratedStoryFn({ ...context, ...storyContextExtras() });
expect(renderMock).toHaveBeenCalledWith(
{ one: 'mapped', two: 2, three: 3 },
expect.objectContaining({ args: { one: 'mapped', two: 2, three: 3 } })
);
});
it('passes args as the first argument to the story if `parameters.passArgsFirst` is true', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{ id, name, args: { a: 1 }, parameters: { passArgsFirst: true }, moduleExport },
{ id, title },
{ render: renderMock }
);
firstStory.undecoratedStoryFn({ args: firstStory.initialArgs, ...firstStory } as any);
expect(renderMock).toHaveBeenCalledWith(
{ a: 1 },
expect.objectContaining({ args: { a: 1 } })
);
const secondStory = prepareStory(
{ id, name, args: { a: 1 }, parameters: { passArgsFirst: false }, moduleExport },
{ id, title },
{ render: renderMock }
);
secondStory.undecoratedStoryFn({ args: secondStory.initialArgs, ...secondStory } as any);
expect(renderMock).toHaveBeenCalledWith(expect.objectContaining({ args: { a: 1 } }));
});
});
describe('storyFn', () => {
it('produces a story with inherited decorators applied', () => {
const renderMock = jest.fn();
const globalDecorator = jest.fn((s) => s());
const componentDecorator = jest.fn((s) => s());
const storyDecorator = jest.fn((s) => s());
const story = prepareStory(
{
id,
name,
decorators: [storyDecorator],
moduleExport,
},
{ id, title, decorators: [componentDecorator] },
{ render: renderMock, decorators: [globalDecorator] }
);
addons.setChannel({ on: jest.fn(), removeListener: jest.fn() } as any);
const hooks = new HooksContext();
story.unboundStoryFn({ args: story.initialArgs, hooks, ...story } as any);
expect(globalDecorator).toHaveBeenCalled();
expect(componentDecorator).toHaveBeenCalled();
expect(storyDecorator).toHaveBeenCalled();
expect(renderMock).toHaveBeenCalled();
hooks.clean();
});
it('prepared context is applied to decorators', () => {
const renderMock = jest.fn();
let ctx1;
let ctx2;
let ctx3;
const globalDecorator = jest.fn((fn, ctx) => {
ctx1 = ctx;
return fn();
});
const componentDecorator = jest.fn((fn, ctx) => {
ctx2 = ctx;
return fn();
});
const storyDecorator = jest.fn((fn, ctx) => {
ctx3 = ctx;
return fn();
});
const story = prepareStory(
{
id,
name,
argTypes: {
one: { name: 'one', type: { name: 'string' }, mapping: { 1: 'mapped-1' } },
},
args: { one: 1 },
decorators: [storyDecorator],
moduleExport,
},
{ id, title, decorators: [componentDecorator] },
{ render: renderMock, decorators: [globalDecorator] }
);
const hooks = new HooksContext();
const context = prepareContext({ args: story.initialArgs, globals: {}, ...story });
story.unboundStoryFn({ ...context, ...storyContextExtras(), hooks });
expect(ctx1).toMatchObject({ unmappedArgs: { one: 1 }, args: { one: 'mapped-1' } });
expect(ctx2).toMatchObject({ unmappedArgs: { one: 1 }, args: { one: 'mapped-1' } });
expect(ctx3).toMatchObject({ unmappedArgs: { one: 1 }, args: { one: 'mapped-1' } });
hooks.clean();
});
});
describe('mapping', () => {
it('maps labels to values in prepareContext', () => {
const story = prepareStory(
{
id,
name,
argTypes: {
one: { name: 'one', mapping: { 1: 'mapped-1' } },
},
moduleExport,
},
{ id, title },
{ render: jest.fn() }
);
const context = prepareContext({ args: { one: 1 }, globals: {}, ...story });
expect(context).toMatchObject({
args: { one: 'mapped-1' },
});
});
it('maps arrays of labels to values in prepareContext', () => {
const story = prepareStory(
{
id,
name,
argTypes: {
one: { name: 'one', mapping: { 1: 'mapped-1' } },
},
moduleExport,
},
{ id, title },
{ render: jest.fn() }
);
const context = prepareContext({
args: { one: [1, 1] },
globals: {},
...story,
});
expect(context).toMatchObject({
args: { one: ['mapped-1', 'mapped-1'] },
});
});
});
describe('with `FEATURES.argTypeTargetsV7`', () => {
beforeEach(() => {
global.FEATURES = { argTypeTargetsV7: true };
});
it('filters out targeted args', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{
id,
name,
args: { a: 1, b: 2 },
argTypes: { b: { name: 'b', target: 'foo' } },
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = prepareContext({ args: firstStory.initialArgs, globals: {}, ...firstStory });
firstStory.unboundStoryFn({ ...context, ...storyContextExtras() });
expect(renderMock).toHaveBeenCalledWith(
{ a: 1 },
expect.objectContaining({ args: { a: 1 }, allArgs: { a: 1, b: 2 } })
);
});
it('filters out conditional args', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{
id,
name,
args: { a: 1, b: 2 },
argTypes: { b: { name: 'b', if: { arg: 'a', truthy: false } } },
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = prepareContext({ args: firstStory.initialArgs, globals: {}, ...firstStory });
firstStory.unboundStoryFn({ ...context, ...storyContextExtras() });
expect(renderMock).toHaveBeenCalledWith(
{ a: 1 },
expect.objectContaining({ args: { a: 1 }, allArgs: { a: 1, b: 2 } })
);
});
it('adds argsByTarget to context', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{
id,
name,
args: { a: 1, b: 2 },
argTypes: { b: { name: 'b', target: 'foo' } },
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = prepareContext({ args: firstStory.initialArgs, globals: {}, ...firstStory });
firstStory.unboundStoryFn({ ...context, ...storyContextExtras() });
expect(renderMock).toHaveBeenCalledWith(
{ a: 1 },
expect.objectContaining({ argsByTarget: { [UNTARGETED]: { a: 1 }, foo: { b: 2 } } })
);
});
it('always sets args, even when all are targetted', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{
id,
name,
args: { b: 2 },
argTypes: { b: { name: 'b', target: 'foo' } },
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = prepareContext({ args: firstStory.initialArgs, globals: {}, ...firstStory });
firstStory.unboundStoryFn({ ...context, ...storyContextExtras() });
expect(renderMock).toHaveBeenCalledWith(
{},
expect.objectContaining({ argsByTarget: { foo: { b: 2 } } })
);
});
it('always sets args, even when none are set for the story', () => {
const renderMock = jest.fn();
const firstStory = prepareStory(
{
id,
name,
moduleExport,
},
{ id, title },
{ render: renderMock }
);
const context = prepareContext({ args: firstStory.initialArgs, globals: {}, ...firstStory });
firstStory.unboundStoryFn({ ...context, ...storyContextExtras() });
expect(renderMock).toHaveBeenCalledWith({}, expect.objectContaining({ argsByTarget: {} }));
});
});
});
describe('playFunction', () => {
it('awaits play if defined', async () => {
const inner = jest.fn();
const play = jest.fn(async () => {
await new Promise((r) => setTimeout(r, 0)); // Ensure this puts an async boundary in
inner();
});
const { playFunction } = prepareStory(
{ id, name, play, moduleExport },
{ id, title },
{ render }
);
await playFunction!({} as PlayFunctionContext);
expect(play).toHaveBeenCalled();
expect(inner).toHaveBeenCalled();
});
it('provides step via runStep', async () => {
const stepPlay = jest.fn((context) => {
expect(context).not.toBeUndefined();
expect(context.step).toEqual(expect.any(Function));
});
const play = jest.fn(async ({ step }) => {
await step('label', stepPlay);
});
const runStep = jest.fn((label, p, c) => p(c));
const { playFunction } = prepareStory(
{ id, name, play, moduleExport },
{ id, title },
{ render, runStep }
);
await playFunction!({} as PlayFunctionContext);
expect(play).toHaveBeenCalled();
expect(stepPlay).toHaveBeenCalled();
expect(runStep).toBeCalledWith('label', stepPlay, expect.any(Object));
});
});
describe('moduleExport', () => {
it('are carried through from the story annotations', () => {
const storyObj = {};
const story = prepareStory({ id, name, moduleExport: storyObj }, { id, title }, { render });
expect(story.moduleExport).toBe(storyObj);
});
});
describe('prepareMeta', () => {
it('returns the same as prepareStory', () => {
const meta = {
id,
title,
moduleExport,
tags: ['some-tag'],
parameters: {
a: { name: 'component' },
b: { name: 'component' },
nested: { z: { name: 'component' }, y: { name: 'component' } },
},
args: {
a: 'component',
b: 'component',
nested: { z: 'component', y: 'component' },
},
argTypes: {
a: { name: 'a-story', type: booleanType },
nested: { name: 'nested', type: booleanType, a: 'story' },
},
};
const preparedStory = prepareStory({ id, name, moduleExport }, meta, { render });
const preparedMeta = prepareMeta(meta, { render }, {});
// omitting the properties from preparedStory that are not in preparedMeta
const {
name: storyName,
story,
applyLoaders,
originalStoryFn,
unboundStoryFn,
undecoratedStoryFn,
playFunction,
// eslint-disable-next-line @typescript-eslint/naming-convention
parameters: { __isArgsStory, ...parameters },
...expectedPreparedMeta
} = preparedStory;
expect(preparedMeta).toMatchObject({ ...expectedPreparedMeta, parameters });
expect(Object.keys(preparedMeta)).toHaveLength(Object.keys(expectedPreparedMeta).length + 1);
});
});
|
1,201 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/csf/processCSFFile.test.ts | import { expect } from '@jest/globals';
import { processCSFFile } from './processCSFFile';
it('returns a CSFFile object with meta and stories', () => {
const { meta, stories } = processCSFFile(
{
default: { title: 'Component' },
storyOne: { args: { a: 1 } },
storyTwo: { args: { a: 2 } },
},
'./path/to/component.js',
'Component'
);
expect(meta).toEqual({
id: 'component',
title: 'Component',
parameters: { fileName: './path/to/component.js' },
});
expect(stories).toEqual({
'component--story-one': expect.objectContaining({
id: 'component--story-one',
name: 'Story One',
args: { a: 1 },
}),
'component--story-two': expect.objectContaining({
id: 'component--story-two',
name: 'Story Two',
args: { a: 2 },
}),
});
});
it('automatically sets title if undefined', () => {
const { meta } = processCSFFile(
{
default: {},
storyOne: {},
},
'./path/to/component.js',
'Prefix/to/file'
);
expect(meta).toEqual({
id: 'prefix-to-file',
title: 'Prefix/to/file',
parameters: { fileName: './path/to/component.js' },
});
});
it('ignores __namedExportsOrder', () => {
const { stories } = processCSFFile(
{
default: { title: 'Component' },
x: () => 0,
y: () => 0,
z: () => 0,
w: () => 0,
__namedExportsOrder: ['w', 'x', 'z', 'y'],
},
'./path/to/component.js',
'Component'
);
expect(Object.keys(stories)).toEqual([
'component--x',
'component--y',
'component--z',
'component--w',
]);
});
it('filters exports using includeStories array', () => {
const { stories } = processCSFFile(
{
default: { title: 'Component', includeStories: ['x', 'z'] },
x: () => 0,
y: () => 0,
z: () => 0,
w: () => 0,
},
'./path/to/component.js',
'Component'
);
expect(Object.keys(stories)).toEqual(['component--x', 'component--z']);
});
it('filters exports using includeStories regex', () => {
const { stories } = processCSFFile(
{
default: { title: 'Component', includeStories: /^(x|z)$/ },
x: () => 0,
y: () => 0,
z: () => 0,
w: () => 0,
},
'./path/to/component.js',
'Component'
);
expect(Object.keys(stories)).toEqual(['component--x', 'component--z']);
});
it('filters exports using excludeStories array', () => {
const { stories } = processCSFFile(
{
default: { title: 'Component', excludeStories: ['x', 'z'] },
x: () => 0,
y: () => 0,
z: () => 0,
w: () => 0,
},
'./path/to/component.js',
'Component'
);
expect(Object.keys(stories)).toEqual(['component--y', 'component--w']);
});
it('filters exports using excludeStories regex', () => {
const { stories } = processCSFFile(
{
default: { title: 'Component', excludeStories: /^(x|z)$/ },
x: () => 0,
y: () => 0,
z: () => 0,
w: () => 0,
},
'./path/to/component.js',
'Component'
);
expect(Object.keys(stories)).toEqual(['component--y', 'component--w']);
});
describe('moduleExports', () => {
it('are carried through', () => {
const moduleExports = {
default: { title: 'Component' },
storyOne: { args: { a: 1 } },
storyTwo: { args: { a: 2 } },
};
const csfFile = processCSFFile(moduleExports, './path/to/component.js', 'Component');
expect(csfFile.moduleExports).toBe(moduleExports);
});
});
|
1,203 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/csf/stepRunners.test.ts | import type { PlayFunctionContext, StepRunner } from '@storybook/types';
import { composeStepRunners } from './stepRunners';
describe('stepRunners', () => {
it('composes each step runner', async () => {
const order: string[] = [];
const firstStepRunner: StepRunner = async (label, play, ctx) => {
order.push(`first-${label}-start`);
await play(ctx);
order.push(`first-${label}-end`);
};
const secondStepRunner: StepRunner = async (label, play, ctx) => {
order.push(`second-${label}-start`);
await play(ctx);
order.push(`second-${label}-end`);
};
const composed = composeStepRunners([firstStepRunner, secondStepRunner]);
const playFnA = jest.fn();
const playContextA = {} as PlayFunctionContext;
await composed('a', playFnA, playContextA);
const playFnB = jest.fn();
const playContextB = {} as PlayFunctionContext;
await composed('b', playFnB, playContextB);
expect(playFnA).toHaveBeenCalledTimes(1);
expect(playFnA).toHaveBeenCalledWith(playContextA);
expect(playFnB).toHaveBeenCalledTimes(1);
expect(playFnB).toHaveBeenCalledWith(playContextB);
expect(order).toEqual([
'first-a-start',
'second-a-start',
'second-a-end',
'first-a-end',
'first-b-start',
'second-b-start',
'second-b-end',
'first-b-end',
]);
});
it('creates a sensible default if no step runner is provided', async () => {
const composed = composeStepRunners([]);
const playFnA = jest.fn();
const playContextA = {} as PlayFunctionContext;
await composed('a', playFnA, playContextA);
const playFnB = jest.fn();
const playContextB = {} as PlayFunctionContext;
await composed('b', playFnB, playContextB);
expect(playFnA).toHaveBeenCalledTimes(1);
expect(playFnA).toHaveBeenCalledWith(playContextA);
expect(playFnB).toHaveBeenCalledTimes(1);
expect(playFnB).toHaveBeenCalledWith(playContextB);
});
});
|
1,205 | 0 | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/csf | petrpan-code/storybookjs/storybook/code/lib/preview-api/src/modules/store/csf/testing-utils/index.test.ts | import { composeStory, composeStories } from './index';
// Most integration tests for this functionality are located under renderers/react
describe('composeStory', () => {
const meta = {
title: 'Button',
parameters: {
firstAddon: true,
},
args: {
label: 'Hello World',
primary: true,
},
};
test('should return story with composed args and parameters', () => {
const Story = () => {};
Story.args = { primary: true };
Story.parameters = {
parameters: {
secondAddon: true,
},
};
const composedStory = composeStory(Story, meta);
expect(composedStory.args).toEqual({ ...Story.args, ...meta.args });
expect(composedStory.parameters).toEqual(
expect.objectContaining({ ...Story.parameters, ...meta.parameters })
);
});
test('should throw an error if Story is undefined', () => {
expect(() => {
// @ts-expect-error (invalid input)
composeStory(undefined, meta);
}).toThrow();
});
});
describe('composeStories', () => {
test('should call composeStoryFn with stories', () => {
const composeConfigFn = jest.fn((v) => v);
const module = {
default: {
title: 'Button',
},
StoryOne: () => {},
StoryTwo: () => {},
};
const globalConfig = {};
composeStories(module, globalConfig, composeConfigFn);
expect(composeConfigFn).toHaveBeenCalledWith(
module.StoryOne,
module.default,
globalConfig,
'StoryOne'
);
expect(composeConfigFn).toHaveBeenCalledWith(
module.StoryTwo,
module.default,
globalConfig,
'StoryTwo'
);
});
test('should not call composeStoryFn for non-story exports', () => {
const composeConfigFn = jest.fn((v) => v);
const module = {
default: {
title: 'Button',
excludeStories: /Data/,
},
mockData: {},
};
composeStories(module, {}, composeConfigFn);
expect(composeConfigFn).not.toHaveBeenCalled();
});
});
|
1,258 | 0 | petrpan-code/storybookjs/storybook/code/lib/router | petrpan-code/storybookjs/storybook/code/lib/router/src/utils.test.ts | import { buildArgsParam, deepDiff, DEEPLY_EQUAL, getMatch, parsePath } from './utils';
jest.mock('@storybook/client-logger', () => ({
once: { warn: jest.fn() },
}));
describe('getMatch', () => {
it('gets startsWithTarget match', () => {
const output = getMatch('/foo/bar', '/foo', true);
expect(output).toEqual({
path: '/foo/bar',
});
});
it('gets currentIsTarget match', () => {
const output = getMatch('/foo', '/foo', false);
expect(output).toEqual({
path: '/foo',
});
});
it('gets matchTarget match', () => {
const output = getMatch('/foo', '/f.+', false);
expect(output).toEqual({
path: '/foo',
});
});
it('returns null match', () => {
const output = getMatch('/foo/bar', '/foo/baz', true);
expect(output).toBe(null);
});
it('returns null match if "startsWith" part is in the middle', () => {
const output = getMatch('/foo/bar', '/bar', true);
expect(output).toBe(null);
});
});
describe('parsePath', () => {
it('should work without path', () => {
const output = parsePath(undefined);
expect(output).toEqual({
viewMode: undefined,
storyId: undefined,
refId: undefined,
});
});
it('should parse /foo/bar correctly', () => {
const output = parsePath('/foo/bar');
expect(output).toMatchObject({
viewMode: 'foo',
storyId: 'bar',
});
});
it('should parse /foo/bar/x correctly', () => {
const output = parsePath('/foo/bar/x');
expect(output).toMatchObject({
viewMode: 'foo',
storyId: 'bar',
});
});
it('should parse /viewMode/refId_story--id correctly', () => {
const output = parsePath('/viewMode/refId_story--id');
expect(output).toMatchObject({
viewMode: 'viewmode',
storyId: 'story--id',
refId: 'refid',
});
});
});
describe('deepDiff', () => {
it('returns DEEPLY_EQUAL when the values are deeply equal', () => {
expect(deepDiff({ foo: [{ bar: 1 }] }, { foo: [{ bar: 1 }] })).toBe(DEEPLY_EQUAL);
});
it('returns the update when the types are different', () => {
expect(deepDiff(true, 1)).toBe(1);
});
it('returns a sparse array when updating an array', () => {
// eslint-disable-next-line no-sparse-arrays
expect(deepDiff([1, 2], [1, 3])).toStrictEqual([, 3]);
});
it('returns undefined for removed array values', () => {
// eslint-disable-next-line no-sparse-arrays
expect(deepDiff([1, 2], [1])).toStrictEqual([, undefined]);
});
it('returns a longer array when adding to an array', () => {
// eslint-disable-next-line no-sparse-arrays
expect(deepDiff([1, 2], [1, 2, 3])).toStrictEqual([, , 3]);
});
it('returns a partial when updating an object', () => {
expect(deepDiff({ foo: 1, bar: 2 }, { foo: 1, bar: 3 })).toStrictEqual({ bar: 3 });
});
it('returns undefined for omitted object properties', () => {
expect(deepDiff({ foo: 1, bar: 2 }, { foo: 1 })).toStrictEqual({ bar: undefined });
});
it('traverses into objects', () => {
expect(deepDiff({ foo: { bar: [1, 2], baz: [3, 4] } }, { foo: { bar: [3] } })).toStrictEqual({
foo: { bar: [3, undefined], baz: undefined },
});
});
});
describe('buildArgsParam', () => {
it('builds a simple key-value pair', () => {
const param = buildArgsParam({}, { key: 'val' });
expect(param).toEqual('key:val');
});
it('builds multiple values', () => {
const param = buildArgsParam({}, { one: '1', two: '2', three: '3' });
expect(param).toEqual('one:1;two:2;three:3');
});
it('builds booleans', () => {
const param = buildArgsParam({}, { yes: true, no: false });
expect(param).toEqual('yes:!true;no:!false');
});
it('builds arrays', () => {
const param = buildArgsParam({}, { arr: ['1', '2', '3'] });
expect(param).toEqual('arr[0]:1;arr[1]:2;arr[2]:3');
});
it('builds sparse arrays', () => {
// eslint-disable-next-line no-sparse-arrays
const param = buildArgsParam({}, { arr: ['1', , '3'] });
expect(param).toEqual('arr[0]:1;arr[2]:3');
});
it('builds simple objects', () => {
const param = buildArgsParam({}, { obj: { one: '1', two: '2' } });
expect(param).toEqual('obj.one:1;obj.two:2');
});
it('builds nested objects', () => {
const param = buildArgsParam({}, { obj: { foo: { one: '1', two: '2' }, bar: { one: '1' } } });
expect(param).toEqual('obj.foo.one:1;obj.foo.two:2;obj.bar.one:1');
});
it('builds arrays in objects', () => {
// eslint-disable-next-line no-sparse-arrays
const param = buildArgsParam({}, { obj: { foo: ['1', , '3'] } });
expect(param).toEqual('obj.foo[0]:1;obj.foo[2]:3');
});
it('builds single object in array', () => {
const param = buildArgsParam({}, { arr: [{ one: '1', two: '2' }] });
expect(param).toEqual('arr[0].one:1;arr[0].two:2');
});
it('builds multiple objects in array', () => {
const param = buildArgsParam({}, { arr: [{ one: '1' }, { two: '2' }] });
expect(param).toEqual('arr[0].one:1;arr[1].two:2');
});
it('builds nested object in array', () => {
const param = buildArgsParam({}, { arr: [{ foo: { bar: 'val' } }] });
expect(param).toEqual('arr[0].foo.bar:val');
});
it('encodes space as +', () => {
const param = buildArgsParam({}, { key: 'foo bar baz' });
expect(param).toEqual('key:foo+bar+baz');
});
it('encodes null values as !null', () => {
const param = buildArgsParam({}, { key: null });
expect(param).toEqual('key:!null');
});
it('encodes nested null values as !null', () => {
const param = buildArgsParam({}, { foo: { bar: [{ key: null }], baz: null } });
expect(param).toEqual('foo.bar[0].key:!null;foo.baz:!null');
});
it('encodes hex color values as !hex(value)', () => {
const param = buildArgsParam({}, { key: '#ff4785' });
expect(param).toEqual('key:!hex(ff4785)');
});
it('encodes rgba color values by prefixing and compacting', () => {
const param = buildArgsParam({}, { rgb: 'rgb(255, 71, 133)', rgba: 'rgba(255, 71, 133, 0.5)' });
expect(param).toEqual('rgb:!rgb(255,71,133);rgba:!rgba(255,71,133,0.5)');
});
it('encodes hsla color values by prefixing and compacting', () => {
const param = buildArgsParam({}, { hsl: 'hsl(45, 99%, 70%)', hsla: 'hsla(45, 99%, 70%, 0.5)' });
expect(param).toEqual('hsl:!hsl(45,99,70);hsla:!hsla(45,99,70,0.5)');
});
it('encodes Date objects as !date(ISO string)', () => {
const param = buildArgsParam({}, { key: new Date('2001-02-03T04:05:06.789Z') });
expect(param).toEqual('key:!date(2001-02-03T04:05:06.789Z)');
});
describe('with initial state', () => {
it('omits unchanged values', () => {
const param = buildArgsParam({ one: 1 }, { one: 1, two: 2 });
expect(param).toEqual('two:2');
});
it('omits unchanged object properties', () => {
const param = buildArgsParam({ obj: { one: 1 } }, { obj: { one: 1, two: 2 } });
expect(param).toEqual('obj.two:2');
});
it('sets !undefined for removed array values', () => {
const param = buildArgsParam({ arr: [1] }, { arr: [] });
expect(param).toEqual('arr[0]:!undefined');
});
it('sets !undefined for removed object properties', () => {
const param = buildArgsParam({ obj: { one: 1 } }, { obj: {} });
expect(param).toEqual('obj.one:!undefined');
});
it('omits unchanged array values (yielding sparse arrays)', () => {
const param = buildArgsParam({ arr: [1, 2, 3] }, { arr: [1, 3, 4] });
expect(param).toEqual('arr[1]:3;arr[2]:4');
});
it('omits nested unchanged object properties and array values', () => {
const param = buildArgsParam(
{ obj: { nested: [{ one: 1 }, { two: 2 }] } },
{ obj: { nested: [{ one: 1 }, { two: 2, three: 3 }] } }
);
expect(param).toEqual('obj.nested[1].three:3');
});
});
});
|
1,290 | 0 | petrpan-code/storybookjs/storybook/code/lib/telemetry | petrpan-code/storybookjs/storybook/code/lib/telemetry/src/anonymous-id.test.ts | import { normalizeGitUrl } from './anonymous-id';
describe('normalizeGitUrl', () => {
it('trims off https://', () => {
expect(normalizeGitUrl('https://github.com/storybookjs/storybook.git')).toEqual(
'github.com/storybookjs/storybook.git'
);
});
it('trims off http://', () => {
expect(normalizeGitUrl('http://github.com/storybookjs/storybook.git')).toEqual(
'github.com/storybookjs/storybook.git'
);
});
it('trims off git+https://', () => {
expect(normalizeGitUrl('git+https://github.com/storybookjs/storybook.git')).toEqual(
'github.com/storybookjs/storybook.git'
);
});
it('trims off https://username@', () => {
expect(normalizeGitUrl('https://username@github.com/storybookjs/storybook.git')).toEqual(
'github.com/storybookjs/storybook.git'
);
});
it('trims off http://username@', () => {
expect(normalizeGitUrl('http://username@github.com/storybookjs/storybook.git')).toEqual(
'github.com/storybookjs/storybook.git'
);
});
it('trims off https://username:password@', () => {
expect(
normalizeGitUrl('https://username:password@github.com/storybookjs/storybook.git')
).toEqual('github.com/storybookjs/storybook.git');
});
it('trims off http://username:password@', () => {
expect(
normalizeGitUrl('http://username:password@github.com/storybookjs/storybook.git')
).toEqual('github.com/storybookjs/storybook.git');
});
it('trims off git://', () => {
expect(normalizeGitUrl('git://github.com/storybookjs/storybook.git')).toEqual(
'github.com/storybookjs/storybook.git'
);
});
it('trims off git@', () => {
expect(normalizeGitUrl('git@github.com:storybookjs/storybook.git')).toEqual(
'github.com/storybookjs/storybook.git'
);
});
it('trims off git+ssh://git@', () => {
expect(normalizeGitUrl('git+ssh://git@github.com:storybookjs/storybook.git')).toEqual(
'github.com/storybookjs/storybook.git'
);
});
it('trims off ssh://git@', () => {
expect(normalizeGitUrl('ssh://git@github.com:storybookjs/storybook.git')).toEqual(
'github.com/storybookjs/storybook.git'
);
});
it('trims off #hash', () => {
expect(normalizeGitUrl('https://github.com/storybookjs/storybook.git#next')).toEqual(
'github.com/storybookjs/storybook.git'
);
});
it('trims off extra whitespace', () => {
expect(normalizeGitUrl('https://github.com/storybookjs/storybook.git#next\n')).toEqual(
'github.com/storybookjs/storybook.git'
);
expect(normalizeGitUrl('https://github.com/storybookjs/storybook.git\n')).toEqual(
'github.com/storybookjs/storybook.git'
);
});
});
|
1,292 | 0 | petrpan-code/storybookjs/storybook/code/lib/telemetry | petrpan-code/storybookjs/storybook/code/lib/telemetry/src/event-cache.test.ts | import { getPrecedingUpgrade } from './event-cache';
expect.addSnapshotSerializer({
print: (val: any) => JSON.stringify(val, null, 2),
test: (val) => typeof val !== 'string',
});
describe('event-cache', () => {
const init = { body: { eventType: 'init', eventId: 'init' }, timestamp: 1 };
const upgrade = { body: { eventType: 'upgrade', eventId: 'upgrade' }, timestamp: 2 };
const dev = { body: { eventType: 'dev', eventId: 'dev' }, timestamp: 3 };
const build = { body: { eventType: 'build', eventId: 'build' }, timestamp: 3 };
const error = { body: { eventType: 'build', eventId: 'error' }, timestamp: 4 };
const versionUpdate = {
body: { eventType: 'version-update', eventId: 'version-update' },
timestamp: 5,
};
describe('data handling', () => {
it('errors', async () => {
const preceding = await getPrecedingUpgrade({
init: { timestamp: 1, body: { ...init.body, error: {} } },
});
expect(preceding).toMatchInlineSnapshot(`
{
"timestamp": 1,
"eventType": "init",
"eventId": "init"
}
`);
});
it('session IDs', async () => {
const preceding = await getPrecedingUpgrade({
init: { timestamp: 1, body: { ...init.body, sessionId: 100 } },
});
expect(preceding).toMatchInlineSnapshot(`
{
"timestamp": 1,
"eventType": "init",
"eventId": "init",
"sessionId": 100
}
`);
});
it('extra fields', async () => {
const preceding = await getPrecedingUpgrade({
init: { timestamp: 1, body: { ...init.body, foobar: 'baz' } },
});
expect(preceding).toMatchInlineSnapshot(`
{
"timestamp": 1,
"eventType": "init",
"eventId": "init"
}
`);
});
});
describe('no intervening dev events', () => {
it('no upgrade events', async () => {
const preceding = await getPrecedingUpgrade({});
expect(preceding).toBeUndefined();
});
it('init', async () => {
const preceding = await getPrecedingUpgrade({ init });
expect(preceding).toMatchInlineSnapshot(`
{
"timestamp": 1,
"eventType": "init",
"eventId": "init"
}
`);
});
it('upgrade', async () => {
const preceding = await getPrecedingUpgrade({ upgrade });
expect(preceding).toMatchInlineSnapshot(`
{
"timestamp": 2,
"eventType": "upgrade",
"eventId": "upgrade"
}
`);
});
it('both init and upgrade', async () => {
const preceding = await getPrecedingUpgrade({ init, upgrade });
expect(preceding).toMatchInlineSnapshot(`
{
"timestamp": 2,
"eventType": "upgrade",
"eventId": "upgrade"
}
`);
});
});
describe('intervening dev events', () => {
it('no upgrade events', async () => {
const preceding = await getPrecedingUpgrade({ dev });
expect(preceding).toBeUndefined();
});
it('init', async () => {
const preceding = await getPrecedingUpgrade({ init, dev });
expect(preceding).toBeUndefined();
});
it('upgrade', async () => {
const preceding = await getPrecedingUpgrade({ upgrade, dev });
expect(preceding).toBeUndefined();
});
it('init followed by upgrade', async () => {
const preceding = await getPrecedingUpgrade({ init, upgrade, dev });
expect(preceding).toBeUndefined();
});
it('both init and upgrade with intervening dev', async () => {
const secondUpgrade = {
body: { eventType: 'upgrade', eventId: 'secondUpgrade' },
timestamp: 4,
};
const preceding = await getPrecedingUpgrade({ init, dev, upgrade: secondUpgrade });
expect(preceding).toMatchInlineSnapshot(`
{
"timestamp": 4,
"eventType": "upgrade",
"eventId": "secondUpgrade"
}
`);
});
it('both init and upgrade with non-intervening dev', async () => {
const earlyDev = {
body: { eventType: 'dev', eventId: 'earlyDev' },
timestamp: -1,
};
const preceding = await getPrecedingUpgrade({ dev: earlyDev, init, upgrade });
expect(preceding).toMatchInlineSnapshot(`
{
"timestamp": 2,
"eventType": "upgrade",
"eventId": "upgrade"
}
`);
});
});
describe('intervening other events', () => {
it('build', async () => {
const preceding = await getPrecedingUpgrade({ upgrade, build });
expect(preceding).toBeUndefined();
});
it('error', async () => {
const preceding = await getPrecedingUpgrade({ upgrade, error });
expect(preceding).toBeUndefined();
});
it('version-update', async () => {
const preceding = await getPrecedingUpgrade({ upgrade, 'version-update': versionUpdate });
expect(preceding).toMatchInlineSnapshot(`
{
"timestamp": 2,
"eventType": "upgrade",
"eventId": "upgrade"
}
`);
});
});
});
|
1,294 | 0 | petrpan-code/storybookjs/storybook/code/lib/telemetry | petrpan-code/storybookjs/storybook/code/lib/telemetry/src/get-chromatic-version.test.ts | import { getChromaticVersionSpecifier } from './get-chromatic-version';
it('works for dependencies', () => {
expect(getChromaticVersionSpecifier({ dependencies: { chromatic: '^6.11.4' } })).toBe('^6.11.4');
});
it('works for scripts', () => {
expect(getChromaticVersionSpecifier({ scripts: { chromatic: 'npx chromatic -t abc123' } })).toBe(
'latest'
);
});
it('fails otherwise', () => {
expect(getChromaticVersionSpecifier({})).toBeUndefined();
});
|
1,296 | 0 | petrpan-code/storybookjs/storybook/code/lib/telemetry | petrpan-code/storybookjs/storybook/code/lib/telemetry/src/get-framework-info.test.ts | import type { StorybookConfig } from '@storybook/types';
import path from 'path';
import { getFrameworkInfo } from './get-framework-info';
import { getActualPackageJson } from './package-json';
jest.mock('./package-json', () => ({
getActualPackageJson: jest.fn(),
}));
describe('getFrameworkInfo', () => {
it('should return an empty object if mainConfig.framework is undefined', async () => {
const result = await getFrameworkInfo({} as StorybookConfig);
expect(result).toEqual({});
});
it('should return an empty object if mainConfig.framework name is undefined', async () => {
const result = await getFrameworkInfo({ framework: {} } as StorybookConfig);
expect(result).toEqual({});
});
it('should call getActualPackageJson with the correct package name', async () => {
const packageName = '@storybook/react';
const framework = { name: packageName };
await getFrameworkInfo({ framework } as StorybookConfig);
expect(getActualPackageJson).toHaveBeenCalledWith(packageName);
});
it('should resolve the framework package json correctly and strip project paths in the metadata', async () => {
const packageName = `${process.cwd()}/@storybook/react`.split('/').join(path.sep);
const framework = { name: packageName };
const frameworkPackageJson = {
name: packageName,
dependencies: {
'@storybook/react': '7.0.0',
'@storybook/builder-vite': '7.0.0',
},
};
(getActualPackageJson as jest.Mock).mockResolvedValueOnce(frameworkPackageJson);
const result = await getFrameworkInfo({ framework } as StorybookConfig);
expect(getActualPackageJson).toHaveBeenCalledWith(packageName);
expect(result).toEqual({
framework: {
name: '$SNIP/@storybook/react'.split('/').join(path.sep),
options: undefined,
},
builder: '@storybook/builder-vite',
renderer: '@storybook/react',
});
});
});
|
1,298 | 0 | petrpan-code/storybookjs/storybook/code/lib/telemetry | petrpan-code/storybookjs/storybook/code/lib/telemetry/src/get-monorepo-type.test.ts | /* eslint-disable no-underscore-dangle */
import path from 'path';
import { getMonorepoType, monorepoConfigs } from './get-monorepo-type';
// eslint-disable-next-line global-require, jest/no-mocks-import
jest.mock('fs-extra', () => require('../../../__mocks__/fs-extra'));
jest.mock('@storybook/core-common', () => {
const coreCommon = jest.requireActual('@storybook/core-common');
return {
...coreCommon,
getProjectRoot: () => 'root',
};
});
const checkMonorepoType = ({ monorepoConfigFile, isYarnWorkspace = false }: any) => {
const mockFiles = {
[path.join('root', 'package.json')]: isYarnWorkspace ? '{ "workspaces": [] }' : '{}',
};
if (monorepoConfigFile) {
mockFiles[path.join('root', monorepoConfigFile)] = '{}';
}
// eslint-disable-next-line global-require
require('fs-extra').__setMockFiles(mockFiles);
return getMonorepoType();
};
describe('getMonorepoType', () => {
describe('Monorepos from json files', () => {
it.each(Object.entries(monorepoConfigs))(
'should detect %p from %s file',
(monorepoName, monorepoConfigFile) => {
expect(checkMonorepoType({ monorepoConfigFile })).toEqual(monorepoName);
}
);
});
describe('Yarn|NPM workspaces', () => {
it('should detect Workspaces from package.json', () => {
expect(checkMonorepoType({ monorepoConfigFile: undefined, isYarnWorkspace: true })).toEqual(
'Workspaces'
);
});
});
describe('Non-monorepos', () => {
it('should return undefined', () => {
expect(checkMonorepoType({ monorepoConfigFile: undefined, isYarnWorkspace: false })).toEqual(
undefined
);
});
});
});
|
1,304 | 0 | petrpan-code/storybookjs/storybook/code/lib/telemetry | petrpan-code/storybookjs/storybook/code/lib/telemetry/src/sanitize.test.ts | /* eslint-disable local-rules/no-uncategorized-errors */
import { sanitizeError, cleanPaths } from './sanitize';
describe(`Errors Helpers`, () => {
describe(`sanitizeError`, () => {
it(`Sanitizes ansi codes in error`, () => {
const errorMessage = `\u001B[4mStorybook\u001B[0m`;
let e: any;
try {
throw new Error(errorMessage);
} catch (error) {
e = error;
}
const sanitizedError = sanitizeError(e);
expect(sanitizedError.message).toEqual('Storybook');
expect(sanitizedError.stack).toContain('Error: Storybook');
});
it(`Sanitizes current path from error stacktraces`, () => {
const errorMessage = `this is a test`;
let e: any;
try {
throw new Error(errorMessage);
} catch (error) {
e = error;
}
expect(e).toBeDefined();
expect(e.message).toEqual(errorMessage);
expect(e.stack).toEqual(expect.stringContaining(process.cwd()));
const sanitizedError = sanitizeError(e);
expect(sanitizedError.message).toEqual(expect.stringContaining(errorMessage));
expect(sanitizedError.message).toEqual(
expect.not.stringContaining(process.cwd().replace(/\\/g, `\\\\`))
);
});
it(`Sanitizes a section of the current path from error stacktrace`, () => {
const errorMessage = `this is a test`;
const e = {
message: errorMessage,
stack: `
Error: this is an error
at Object.<anonymous> (/Users/username/Code/storybook-app/storybook-config.js:1:32)
at Object.<anonymous> (/Users/username/Code/storybook-app/node_module/storybook-telemetry/blah.js:1:69)
at Object.<anonymous> (/Users/username/Code/storybook-app/node_module/fake-path/index.js:1:41)
at Object.<anonymous> (/Users/username/.fake-path/index.js:1:69)
at Module._compile (internal/modules/cjs/loader.js:736:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:747:10)
at Module.load (internal/modules/cjs/loader.js:628:32)
at tryModuleLoad (internal/modules/cjs/loader.js:568:12)
at Function.Module._load (internal/modules/cjs/loader.js:560:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
at executeUserCode (internal/bootstrap/node.js:526:15)
at startMainThreadExecution (internal/bootstrap/node.js:439:3)
`,
};
expect(e).toBeDefined();
expect(e.message).toEqual(errorMessage);
expect(e.stack).toBeDefined();
const mockCwd = jest
.spyOn(process, `cwd`)
.mockImplementation(() => `/Users/username/Code/storybook-app`);
expect(e.stack).toEqual(expect.stringContaining(`username`));
const sanitizedError = sanitizeError(e as Error, `/`);
expect(sanitizedError.message.includes(errorMessage)).toBe(true);
expect(sanitizedError.stack).toEqual(expect.not.stringContaining(`username`));
const result = sanitizedError.stack.match(/\$SNIP/g) as Array<string>;
expect(result.length).toBe(4);
mockCwd.mockRestore();
});
});
describe(`cleanPaths`, () => {
it.each([`storybook-config.js`, `src/pages/index.js`])(
`should clean path on unix: %s`,
(filePath) => {
const cwdMockPath = `/Users/username/storybook-app`;
const mockCwd = jest.spyOn(process, `cwd`).mockImplementation(() => cwdMockPath);
const errorMessage = `Path 1 /Users/Username/storybook-app/${filePath} Path 2 /Users/username/storybook-app/${filePath}`;
expect(cleanPaths(errorMessage, `/`)).toBe(
`Path 1 $SNIP/${filePath} Path 2 $SNIP/${filePath}`
);
mockCwd.mockRestore();
}
);
it.each([`storybook-config.js`, `src\\pages\\index.js`])(
`should clean path on windows: %s`,
(filePath) => {
const cwdMockPath = `C:\\Users\\username\\storybook-app`;
const mockCwd = jest.spyOn(process, `cwd`).mockImplementationOnce(() => cwdMockPath);
const errorMessage = `Path 1 C:\\Users\\username\\storybook-app\\${filePath} Path 2 c:\\Users\\username\\storybook-app\\${filePath}`;
expect(cleanPaths(errorMessage, `\\`)).toBe(
`Path 1 $SNIP\\${filePath} Path 2 $SNIP\\${filePath}`
);
mockCwd.mockRestore();
}
);
});
});
|
1,306 | 0 | petrpan-code/storybookjs/storybook/code/lib/telemetry | petrpan-code/storybookjs/storybook/code/lib/telemetry/src/session-id.test.ts | import { nanoid } from 'nanoid';
import { cache } from '@storybook/core-common';
import { resetSessionIdForTest, getSessionId, SESSION_TIMEOUT } from './session-id';
jest.mock('@storybook/core-common', () => {
const actual = jest.requireActual('@storybook/core-common');
return {
...actual,
cache: {
get: jest.fn(),
set: jest.fn(),
},
};
});
jest.mock('nanoid');
const spy = (x: any) => x as jest.SpyInstance;
describe('getSessionId', () => {
beforeEach(() => {
jest.clearAllMocks();
resetSessionIdForTest();
});
test('returns existing sessionId when cached in memory and does not fetch from disk', async () => {
const existingSessionId = 'memory-session-id';
resetSessionIdForTest(existingSessionId);
const sessionId = await getSessionId();
expect(cache.get).not.toHaveBeenCalled();
expect(cache.set).toHaveBeenCalledTimes(1);
expect(cache.set).toHaveBeenCalledWith(
'session',
expect.objectContaining({ id: existingSessionId })
);
expect(sessionId).toBe(existingSessionId);
});
test('returns existing sessionId when cached on disk and not expired', async () => {
const existingSessionId = 'existing-session-id';
const existingSession = {
id: existingSessionId,
lastUsed: Date.now() - SESSION_TIMEOUT + 1000,
};
spy(cache.get).mockResolvedValueOnce(existingSession);
const sessionId = await getSessionId();
expect(cache.get).toHaveBeenCalledTimes(1);
expect(cache.get).toHaveBeenCalledWith('session');
expect(cache.set).toHaveBeenCalledTimes(1);
expect(cache.set).toHaveBeenCalledWith(
'session',
expect.objectContaining({ id: existingSessionId })
);
expect(sessionId).toBe(existingSessionId);
});
test('generates new sessionId when none exists', async () => {
const newSessionId = 'new-session-id';
(nanoid as any as jest.SpyInstance).mockReturnValueOnce(newSessionId);
spy(cache.get).mockResolvedValueOnce(undefined);
const sessionId = await getSessionId();
expect(cache.get).toHaveBeenCalledTimes(1);
expect(cache.get).toHaveBeenCalledWith('session');
expect(nanoid).toHaveBeenCalledTimes(1);
expect(cache.set).toHaveBeenCalledTimes(1);
expect(cache.set).toHaveBeenCalledWith(
'session',
expect.objectContaining({ id: newSessionId })
);
expect(sessionId).toBe(newSessionId);
});
test('generates new sessionId when existing one is expired', async () => {
const expiredSessionId = 'expired-session-id';
const expiredSession = { id: expiredSessionId, lastUsed: Date.now() - SESSION_TIMEOUT - 1000 };
const newSessionId = 'new-session-id';
spy(nanoid).mockReturnValueOnce(newSessionId);
spy(cache.get).mockResolvedValueOnce(expiredSession);
const sessionId = await getSessionId();
expect(cache.get).toHaveBeenCalledTimes(1);
expect(cache.get).toHaveBeenCalledWith('session');
expect(nanoid).toHaveBeenCalledTimes(1);
expect(cache.set).toHaveBeenCalledTimes(1);
expect(cache.set).toHaveBeenCalledWith(
'session',
expect.objectContaining({ id: newSessionId })
);
expect(sessionId).toBe(newSessionId);
});
});
|
1,308 | 0 | petrpan-code/storybookjs/storybook/code/lib/telemetry | petrpan-code/storybookjs/storybook/code/lib/telemetry/src/storybook-metadata.test.ts | import type { PackageJson, StorybookConfig } from '@storybook/types';
import path from 'path';
import { computeStorybookMetadata, metaFrameworks, sanitizeAddonName } from './storybook-metadata';
const packageJsonMock: PackageJson = {
name: 'some-user-project',
version: 'x.x.x',
};
const mainJsMock: StorybookConfig = {
stories: [],
};
jest.mock('./package-json', () => {
const getActualPackageVersion = jest.fn((name) =>
Promise.resolve({
name,
version: 'x.x.x',
})
);
const getActualPackageVersions = jest.fn((packages) =>
Promise.all(Object.keys(packages).map(getActualPackageVersion))
);
const getActualPackageJson = jest.fn((name) => ({
dependencies: {
'@storybook/react': 'x.x.x',
'@storybook/builder-vite': 'x.x.x',
},
}));
return {
getActualPackageVersions,
getActualPackageVersion,
getActualPackageJson,
};
});
jest.mock('./get-monorepo-type', () => ({
getMonorepoType: () => 'Nx',
}));
jest.mock('detect-package-manager', () => ({
detect: () => 'Yarn',
getNpmVersion: () => '3.1.1',
}));
const originalSep = path.sep;
describe('storybook-metadata', () => {
let cwdSpy: jest.SpyInstance;
beforeEach(() => {
// @ts-expect-error the property is read only but we can change it for testing purposes
path.sep = originalSep;
});
afterEach(() => {
cwdSpy?.mockRestore();
// @ts-expect-error the property is read only but we can change it for testing purposes
path.sep = originalSep;
});
describe('sanitizeAddonName', () => {
test('special addon names', () => {
const addonNames = [
'@storybook/preset-create-react-app',
'storybook-addon-deprecated/register',
'storybook-addon-ends-with-js/register.js',
'@storybook/addon-knobs/preset',
'@storybook/addon-ends-with-js/preset.js',
'@storybook/addon-postcss/dist/index.js',
'../local-addon/register.js',
'../../',
].map(sanitizeAddonName);
expect(addonNames).toEqual([
'@storybook/preset-create-react-app',
'storybook-addon-deprecated',
'storybook-addon-ends-with-js',
'@storybook/addon-knobs',
'@storybook/addon-ends-with-js',
'@storybook/addon-postcss',
'../local-addon',
'../../',
]);
});
test('Windows paths', () => {
// @ts-expect-error the property is read only but we can change it for testing purposes
path.sep = '\\';
const cwdMockPath = `C:\\Users\\username\\storybook-app`;
cwdSpy = jest.spyOn(process, `cwd`).mockReturnValueOnce(cwdMockPath);
expect(sanitizeAddonName(`${cwdMockPath}\\local-addon\\themes.js`)).toEqual(
'$SNIP\\local-addon\\themes'
);
});
test('Linux paths', () => {
// @ts-expect-error the property is read only but we can change it for testing purposes
path.sep = '/';
const cwdMockPath = `/Users/username/storybook-app`;
cwdSpy = jest.spyOn(process, `cwd`).mockReturnValue(cwdMockPath);
expect(sanitizeAddonName(`${cwdMockPath}/local-addon/themes.js`)).toEqual(
'$SNIP/local-addon/themes'
);
});
});
describe('computeStorybookMetadata', () => {
describe('pnp paths', () => {
test('should parse pnp paths for known frameworks', async () => {
const unixResult = await computeStorybookMetadata({
packageJson: packageJsonMock,
mainConfig: {
...mainJsMock,
framework: {
name: '/Users/foo/storybook/.yarn/__virtual__/@storybook-react-vite-virtual-769c990b9/0/cache/@storybook-react-vite-npm-7.1.0-alpha.38-512b-a23.zip/node_modules/@storybook/react-vite',
options: {
fastRefresh: false,
},
},
},
});
expect(unixResult.framework).toEqual({
name: '@storybook/react-vite',
options: { fastRefresh: false },
});
const windowsResult = await computeStorybookMetadata({
packageJson: packageJsonMock,
mainConfig: {
...mainJsMock,
framework: {
name: 'C:\\Users\\foo\\storybook\\.yarn\\__virtual__\\@storybook-react-vite-virtual-769c990b9\\0\\cache\\@storybook-react-vite-npm-7.1.0-alpha.38-512b-a23.zip\\node_modules\\@storybook\\react-vite',
options: {
fastRefresh: false,
},
},
},
});
expect(windowsResult.framework).toEqual({
name: '@storybook/react-vite',
options: { fastRefresh: false },
});
});
test('should parse pnp paths for unknown frameworks', async () => {
const unixResult = await computeStorybookMetadata({
packageJson: packageJsonMock,
mainConfig: {
...mainJsMock,
framework: {
name: '/Users/foo/my-project/.yarn/__virtual__/@storybook-react-vite-virtual-769c990b9/0/cache/@storybook-react-rust-npm-7.1.0-alpha.38-512b-a23.zip/node_modules/storybook-react-rust',
},
},
});
expect(unixResult.framework).toEqual({
name: 'storybook-react-rust',
});
const windowsResult = await computeStorybookMetadata({
packageJson: packageJsonMock,
mainConfig: {
...mainJsMock,
framework: {
name: 'C:\\Users\\foo\\my-project\\.yarn\\__virtual__\\@storybook-react-vite-virtual-769c990b9\\0\\cache\\@storybook-react-rust-npm-7.1.0-alpha.38-512b-a23.zip\\node_modules\\storybook-react-rust',
},
},
});
expect(windowsResult.framework).toEqual({
name: 'storybook-react-rust',
});
});
test('should sanitize pnp paths for local frameworks', async () => {
// @ts-expect-error the property is read only but we can change it for testing purposes
path.sep = '/';
cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue('/Users/foo/my-projects');
const unixResult = await computeStorybookMetadata({
packageJson: packageJsonMock,
mainConfig: {
...mainJsMock,
framework: {
name: '/Users/foo/my-projects/.storybook/some-local-framework',
},
},
});
expect(unixResult.framework).toEqual({
name: '$SNIP/.storybook/some-local-framework',
});
// @ts-expect-error the property is read only but we can change it for testing purposes
path.sep = '\\';
cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue('C:\\Users\\foo\\my-project');
const windowsResult = await computeStorybookMetadata({
packageJson: packageJsonMock,
mainConfig: {
...mainJsMock,
framework: {
name: 'C:\\Users\\foo\\my-project\\.storybook\\some-local-framework',
},
},
});
expect(windowsResult.framework).toEqual({
name: '$SNIP\\.storybook\\some-local-framework',
});
});
});
test('should return frameworkOptions from mainjs', async () => {
const reactResult = await computeStorybookMetadata({
packageJson: packageJsonMock,
mainConfig: {
...mainJsMock,
framework: {
name: '@storybook/react-vite',
options: {
fastRefresh: false,
},
},
},
});
expect(reactResult.framework).toEqual({
name: '@storybook/react-vite',
options: { fastRefresh: false },
});
const angularResult = await computeStorybookMetadata({
packageJson: packageJsonMock,
mainConfig: {
...mainJsMock,
framework: {
name: '@storybook/angular',
options: {
enableIvy: true,
enableNgcc: true,
},
},
},
});
expect(angularResult.framework).toEqual({
name: '@storybook/angular',
options: { enableIvy: true, enableNgcc: true },
});
});
test('should separate storybook packages and addons', async () => {
const result = await computeStorybookMetadata({
packageJson: {
...packageJsonMock,
devDependencies: {
'@storybook/react': 'x.y.z',
'@storybook/addon-essentials': 'x.x.x',
'@storybook/addon-knobs': 'x.x.y',
'storybook-addon-deprecated': 'x.x.z',
},
} as PackageJson,
mainConfig: {
...mainJsMock,
addons: [
'@storybook/addon-essentials',
'storybook-addon-deprecated/register',
'@storybook/addon-knobs/preset',
],
},
});
expect(result.addons).toMatchInlineSnapshot(`
Object {
"@storybook/addon-essentials": Object {
"options": undefined,
"version": "x.x.x",
},
"@storybook/addon-knobs": Object {
"options": undefined,
"version": "x.x.x",
},
"storybook-addon-deprecated": Object {
"options": undefined,
"version": "x.x.x",
},
}
`);
expect(result.storybookPackages).toMatchInlineSnapshot(`
Object {
"@storybook/react": Object {
"version": "x.x.x",
},
}
`);
});
test('should return user specified features', async () => {
const features = {
storyStoreV7: true,
};
const result = await computeStorybookMetadata({
packageJson: packageJsonMock,
mainConfig: {
...mainJsMock,
features,
},
});
expect(result.features).toEqual(features);
});
test('should infer builder and renderer from framework package.json', async () => {
expect(
await computeStorybookMetadata({
packageJson: packageJsonMock,
mainConfig: {
...mainJsMock,
framework: '@storybook/react-vite',
},
})
).toMatchObject({
framework: { name: '@storybook/react-vite' },
renderer: '@storybook/react',
builder: '@storybook/builder-vite',
});
});
test('should return the number of refs', async () => {
const res = await computeStorybookMetadata({
packageJson: packageJsonMock,
mainConfig: {
...mainJsMock,
refs: {
a: { title: '', url: '' },
b: { title: '', url: '' },
},
},
});
expect(res.refCount).toEqual(2);
});
test('only reports addon options for addon-essentials', async () => {
const res = await computeStorybookMetadata({
packageJson: packageJsonMock,
mainConfig: {
...mainJsMock,
addons: [
{ name: '@storybook/addon-essentials', options: { controls: false } },
{ name: 'addon-foo', options: { foo: 'bar' } },
],
},
});
expect(res.addons).toMatchInlineSnapshot(`
Object {
"@storybook/addon-essentials": Object {
"options": Object {
"controls": false,
},
"version": "x.x.x",
},
"addon-foo": Object {
"options": undefined,
"version": "x.x.x",
},
}
`);
});
test.each(Object.entries(metaFrameworks))(
'should detect the supported metaframework: %s',
async (metaFramework, name) => {
const res = await computeStorybookMetadata({
packageJson: {
...packageJsonMock,
dependencies: {
[metaFramework]: 'x.x.x',
},
} as PackageJson,
mainConfig: mainJsMock,
});
expect(res.metaFramework).toEqual({
name,
packageName: metaFramework,
version: 'x.x.x',
});
}
);
});
});
|
1,310 | 0 | petrpan-code/storybookjs/storybook/code/lib/telemetry | petrpan-code/storybookjs/storybook/code/lib/telemetry/src/telemetry.test.ts | /// <reference types="@types/jest" />;
import fetch from 'node-fetch';
import { sendTelemetry } from './telemetry';
jest.mock('node-fetch');
jest.mock('./event-cache', () => {
return { set: jest.fn() };
});
jest.mock('./session-id', () => {
return {
getSessionId: async () => {
return 'session-id';
},
};
});
const fetchMock = fetch as jest.Mock;
beforeEach(() => {
fetchMock.mockResolvedValue({ status: 200 });
});
it('makes a fetch request with name and data', async () => {
fetchMock.mockClear();
await sendTelemetry({ eventType: 'dev', payload: { foo: 'bar' } });
expect(fetch).toHaveBeenCalledTimes(1);
const body = JSON.parse(fetchMock.mock.calls[0][1].body);
expect(body).toMatchObject({
eventType: 'dev',
payload: { foo: 'bar' },
});
});
it('retries if fetch fails with a 503', async () => {
fetchMock.mockClear().mockResolvedValueOnce({ status: 503 });
await sendTelemetry(
{
eventType: 'dev',
payload: { foo: 'bar' },
},
{ retryDelay: 0 }
);
expect(fetch).toHaveBeenCalledTimes(2);
});
it('gives up if fetch repeatedly fails', async () => {
fetchMock.mockClear().mockResolvedValue({ status: 503 });
await sendTelemetry(
{
eventType: 'dev',
payload: { foo: 'bar' },
},
{ retryDelay: 0 }
);
expect(fetch).toHaveBeenCalledTimes(4);
});
it('await all pending telemetry when passing in immediate = true', async () => {
let numberOfResolvedTasks = 0;
fetchMock.mockImplementation(async () => {
// wait 10ms so that the "fetch" is still running while
// getSessionId resolves immediately below. tricky!
await new Promise((resolve) => {
setTimeout(resolve, 10);
});
numberOfResolvedTasks += 1;
return { status: 200 };
});
// when we call sendTelemetry with immediate = true
// all pending tasks will be awaited
// to test this we add a few telemetry tasks that will be in the 'queue'
// we do NOT await these tasks!
sendTelemetry({
eventType: 'init',
payload: { foo: 'bar' },
});
sendTelemetry({
eventType: 'dev',
payload: { foo: 'bar' },
});
// wait for getSessionId to finish, but not for fetches
await new Promise((resolve) => {
setTimeout(resolve, 0);
});
expect(fetch).toHaveBeenCalledTimes(2);
expect(numberOfResolvedTasks).toBe(0);
// here we await
await sendTelemetry(
{
eventType: 'error',
payload: { foo: 'bar' },
},
{ retryDelay: 0, immediate: true }
);
expect(fetch).toHaveBeenCalledTimes(3);
expect(numberOfResolvedTasks).toBe(3);
});
|
1,317 | 0 | petrpan-code/storybookjs/storybook/code/lib | petrpan-code/storybookjs/storybook/code/lib/test/tsconfig.json | {
"extends": "../../tsconfig.json",
"include": ["src/**/*"]
}
|
1,398 | 0 | petrpan-code/storybookjs/storybook/code/presets/react-webpack | petrpan-code/storybookjs/storybook/code/presets/react-webpack/src/cra-config.test.ts | import fs from 'fs';
import path from 'path';
import { getReactScriptsPath } from './cra-config';
jest.mock('fs', () => ({
realpathSync: jest.fn(() => '/test-project'),
readFileSync: jest.fn(),
existsSync: jest.fn(() => true),
}));
const SCRIPT_PATH = path.join('.bin', 'react-scripts');
describe('cra-config', () => {
describe('when used with the default react-scripts package', () => {
beforeEach(() => {
(fs.realpathSync as unknown as jest.Mock).mockImplementationOnce((filePath) =>
filePath.replace(SCRIPT_PATH, `react-scripts/${SCRIPT_PATH}`)
);
});
it('should locate the react-scripts package', () => {
expect(getReactScriptsPath({ noCache: true })).toEqual(
path.join(path.sep, 'test-project', 'node_modules', 'react-scripts')
);
});
});
describe('when used with a custom react-scripts package', () => {
beforeEach(() => {
(fs.realpathSync as unknown as jest.Mock).mockImplementationOnce((filePath) =>
filePath.replace(SCRIPT_PATH, `custom-react-scripts/${SCRIPT_PATH}`)
);
});
it('should locate the react-scripts package', () => {
expect(getReactScriptsPath({ noCache: true })).toEqual(
path.join(path.sep, 'test-project', 'node_modules', 'custom-react-scripts')
);
});
});
describe('when used with a custom react-scripts package without symlinks in .bin folder', () => {
beforeEach(() => {
// In case of .bin/react-scripts is not symlink (like it happens on Windows),
// realpathSync() method does not translate the path.
(fs.realpathSync as unknown as jest.Mock).mockImplementationOnce((filePath) => filePath);
(fs.readFileSync as unknown as jest.Mock).mockImplementationOnce(
() => `#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case \`uname\` in
*CYGWIN*) basedir=\`cygpath -w "$basedir"\`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../custom-react-scripts/bin/react-scripts.js" "$@"
ret=$?
else
node "$basedir/../custom-react-scripts/bin/react-scripts.js" "$@"
ret=$?
fi
exit $ret`
);
});
it('should locate the react-scripts package', () => {
expect(getReactScriptsPath({ noCache: true })).toEqual(
path.join(path.sep, 'test-project', 'node_modules', 'custom-react-scripts')
);
});
});
});
|
1,401 | 0 | petrpan-code/storybookjs/storybook/code/presets/react-webpack | petrpan-code/storybookjs/storybook/code/presets/react-webpack/src/framework-preset-react-docs.test.ts | import ReactDocgenTypescriptPlugin from '@storybook/react-docgen-typescript-plugin';
import type { TypescriptOptions } from '@storybook/core-webpack';
import type { Configuration } from 'webpack';
import * as preset from './framework-preset-react-docs';
jest.mock('./requirer', () => ({
requirer: (resolver: any, path: string) => path,
}));
describe('framework-preset-react-docgen', () => {
const presetsListWithDocs = [{ name: '@storybook/addon-docs', options: {}, preset: null }];
// mock requirer
describe('react-docgen', () => {
it('should return the webpack config with the extra webpack loader', async () => {
const webpackConfig: Configuration = {};
const config = await preset.webpackFinal?.(webpackConfig, {
presets: {
apply: async () =>
({
check: false,
reactDocgen: 'react-docgen',
} as Partial<TypescriptOptions>),
},
presetsList: presetsListWithDocs,
} as any);
expect(config).toEqual({
module: {
rules: [
{
exclude: /node_modules\/.*/,
loader: '@storybook/preset-react-webpack/dist/loaders/react-docgen-loader',
test: /\.(cjs|mjs|tsx?|jsx?)$/,
},
],
},
});
});
});
describe('react-docgen-typescript', () => {
it('should return the webpack config with the extra plugin', async () => {
const webpackConfig = {
plugins: [],
};
const config = await preset.webpackFinal?.(webpackConfig, {
presets: {
// @ts-expect-error (not strict)
apply: async () =>
({
check: false,
reactDocgen: 'react-docgen-typescript',
} as Partial<TypescriptOptions>),
},
presetsList: presetsListWithDocs,
});
expect(config).toEqual({
module: {
rules: [
{
exclude: /node_modules\/.*/,
loader: '@storybook/preset-react-webpack/dist/loaders/react-docgen-loader',
test: /\.(cjs|mjs|jsx?)$/,
},
],
},
plugins: [expect.any(ReactDocgenTypescriptPlugin)],
});
});
});
describe('no docgen', () => {
it('should not add any extra plugins', async () => {
const webpackConfig = {
plugins: [],
};
const outputWebpackconfig = await preset.webpackFinal?.(webpackConfig, {
presets: {
// @ts-expect-error (Converted from ts-ignore)
apply: async () =>
({
check: false,
reactDocgen: false,
} as Partial<TypescriptOptions>),
},
presetsList: presetsListWithDocs,
});
expect(outputWebpackconfig).toEqual({ plugins: [] });
});
});
describe('no docs or controls addon used', () => {
it('should not add any extra plugins', async () => {
const webpackConfig = {
plugins: [],
};
const outputWebpackconfig = await preset.webpackFinal?.(webpackConfig, {
presets: {
// @ts-expect-error (Converted from ts-ignore)
apply: async () =>
({
check: false,
reactDocgen: 'react-docgen-typescript',
} as Partial<TypescriptOptions>),
},
presetsList: [],
});
expect(outputWebpackconfig).toEqual({
plugins: [],
});
});
});
});
|
1,403 | 0 | petrpan-code/storybookjs/storybook/code/presets/react-webpack | petrpan-code/storybookjs/storybook/code/presets/react-webpack/src/framework-preset-react.test.ts | import type { Configuration } from 'webpack';
import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin';
import type { Options } from '@storybook/core-webpack';
import * as preset from './framework-preset-react';
const mockApply = jest.fn();
jest.mock('@pmmmwh/react-refresh-webpack-plugin', () => {
return jest.fn().mockImplementation(() => {
return { apply: mockApply };
});
});
describe('framework-preset-react', () => {
const reactRefreshPath = require.resolve('react-refresh/babel');
const webpackConfigMock: Configuration = {
plugins: [],
module: {
rules: [],
},
};
const babelConfigMock = {};
const storybookOptions: Partial<Options> = {
configType: 'DEVELOPMENT',
presets: {
// @ts-expect-error (Converted from ts-ignore)
apply: async () => ({
name: '@storybook/react',
options: {
fastRefresh: true,
},
}),
},
presetsList: [],
};
const storybookOptionsDisabledRefresh: Partial<Options> = {
configType: 'DEVELOPMENT',
presets: {
// @ts-expect-error (Converted from ts-ignore)
apply: async () => ({
name: '@storybook/react',
options: {
fastRefresh: false,
},
}),
},
};
describe('babel', () => {
it('should return a config with fast refresh plugin when fast refresh is enabled', async () => {
const config = await preset.babel?.(babelConfigMock, storybookOptions as Options);
expect(config?.plugins).toEqual([[reactRefreshPath, {}, 'storybook-react-refresh']]);
});
it('should return unchanged config without fast refresh plugin when fast refresh is disabled', async () => {
const config = await preset.babel?.(
babelConfigMock,
storybookOptionsDisabledRefresh as Options
);
expect(config).toEqual(babelConfigMock);
});
it('should return unchanged config without fast refresh plugin when mode is not development', async () => {
const config = await preset.babel?.(babelConfigMock, {
...storybookOptions,
configType: 'PRODUCTION',
} as Options);
expect(config).toEqual(babelConfigMock);
});
});
describe('webpackFinal', () => {
it('should return a config with fast refresh plugin when fast refresh is enabled', async () => {
const config = await preset.webpackFinal?.(webpackConfigMock, storybookOptions as Options);
expect(config?.plugins).toEqual([new ReactRefreshWebpackPlugin()]);
});
it('should return unchanged config without fast refresh plugin when fast refresh is disabled', async () => {
const config = await preset.webpackFinal?.(
webpackConfigMock,
storybookOptionsDisabledRefresh as Options
);
expect(config).toEqual(webpackConfigMock);
});
it('should return unchanged config without fast refresh plugin when mode is not development', async () => {
const config = await preset.webpackFinal?.(webpackConfigMock, {
...storybookOptions,
configType: 'PRODUCTION',
} as Options);
expect(config).toEqual(webpackConfigMock);
});
});
});
|
1,421 | 0 | petrpan-code/storybookjs/storybook/code/presets/server-webpack/src/lib | petrpan-code/storybookjs/storybook/code/presets/server-webpack/src/lib/compiler/json-to-csf-compiler.test.ts | import 'jest-specific-snapshot';
import path from 'path';
import fs from 'fs-extra';
import YAML from 'yaml';
import { compileCsfModule } from '.';
async function generate(filePath: string) {
const content = await fs.readFile(filePath, 'utf8');
const parsed = filePath.endsWith('.json') ? JSON.parse(content) : YAML.parse(content);
return compileCsfModule(parsed);
}
['json', 'ya?ml'].forEach((fileType) => {
const inputRegExp = new RegExp(`.${fileType}$`);
describe(`${fileType}-to-csf-compiler`, () => {
const transformFixturesDir = path.join(__dirname, '__testfixtures__');
fs.readdirSync(transformFixturesDir)
.filter((fileName: string) => inputRegExp.test(fileName))
.forEach((fixtureFile: string) => {
it(`${fixtureFile}`, async () => {
const inputPath = path.join(transformFixturesDir, fixtureFile);
const code = await generate(inputPath);
expect(code).toMatchSpecificSnapshot(inputPath.replace(inputRegExp, '.snapshot'));
});
});
});
});
|
1,499 | 0 | petrpan-code/storybookjs/storybook/code/renderers/html/src | petrpan-code/storybookjs/storybook/code/renderers/html/src/docs/sourceDecorator.test.ts | import { SNIPPET_RENDERED } from '@storybook/docs-tools';
import { addons, useEffect } from '@storybook/preview-api';
import { sourceDecorator } from './sourceDecorator';
import type { StoryContext } from '../types';
jest.mock('@storybook/preview-api');
const mockedAddons = addons as jest.Mocked<typeof addons>;
const mockedUseEffect = useEffect as jest.Mocked<typeof useEffect>;
expect.addSnapshotSerializer({
print: (val: any) => val,
test: (val) => typeof val === 'string',
});
const tick = () => new Promise((r) => setTimeout(r, 0));
const makeContext = (name: string, parameters: any, args: any, extra?: object): StoryContext =>
// @ts-expect-error haven't added unmapped args to StoryContext yet
({
id: `html-test--${name}`,
kind: 'js-text',
name,
parameters,
componentId: '',
title: '',
story: '',
unmappedArgs: args,
args,
argTypes: {},
globals: {},
initialArgs: {},
...extra,
} as StoryContext);
describe('sourceDecorator', () => {
let mockChannel: { on: jest.Mock; emit?: jest.Mock };
beforeEach(() => {
mockedAddons.getChannel.mockReset();
// @ts-expect-error (Converted from ts-ignore)
mockedUseEffect.mockImplementation((cb) => setTimeout(() => cb(), 0));
mockChannel = { on: jest.fn(), emit: jest.fn() };
mockedAddons.getChannel.mockReturnValue(mockChannel as any);
});
it('should render dynamically for args stories', async () => {
const storyFn = (args: any) => `<div>args story</div>`;
const context = makeContext('args', { __isArgsStory: true }, {});
sourceDecorator(storyFn, context);
await tick();
expect(mockChannel.emit).toHaveBeenCalledWith(SNIPPET_RENDERED, {
id: 'html-test--args',
args: {},
source: '<div>args story</div>',
});
});
it('should skip dynamic rendering for no-args stories', async () => {
const storyFn = () => `<div>classic story</div>`;
const context = makeContext('classic', {}, {});
sourceDecorator(storyFn, context);
await tick();
expect(mockChannel.emit).not.toHaveBeenCalled();
});
it('should use the originalStoryFn if excludeDecorators is set', async () => {
const storyFn = (args: any) => `<div>args story</div>`;
const decoratedStoryFn = (args: any) => `
<div style="padding: 25px; border: 3px solid red;">${storyFn(args)}</div>
`;
const context = makeContext(
'args',
{
__isArgsStory: true,
docs: {
source: {
excludeDecorators: true,
},
},
},
{},
{ originalStoryFn: storyFn }
);
sourceDecorator(decoratedStoryFn, context);
await tick();
expect(mockChannel.emit).toHaveBeenCalledWith(SNIPPET_RENDERED, {
id: 'html-test--args',
args: {},
source: '<div>args story</div>',
});
});
});
|
1,568 | 0 | petrpan-code/storybookjs/storybook/code/renderers/react | petrpan-code/storybookjs/storybook/code/renderers/react/src/public-api.test.ts | import * as api from '.';
describe('preview', () => {
afterEach(() => {
jest.resetModules();
});
const isFunction = (value: unknown) => typeof value === 'function';
it('should return the client api in a browser environment', () => {
expect(Object.keys(api).length).toBeGreaterThan(0);
expect(Object.values(api).every(isFunction)).toEqual(true);
});
it('should return the client api in a node.js environment', () => {
expect(Object.keys(api).length).toBeGreaterThan(0);
expect(Object.values(api).every(isFunction)).toEqual(true);
});
});
|
1,570 | 0 | petrpan-code/storybookjs/storybook/code/renderers/react | petrpan-code/storybookjs/storybook/code/renderers/react/src/public-types.test.tsx | import { describe, test } from '@jest/globals';
import { satisfies } from '@storybook/core-common';
import type { Args, StoryAnnotations, StrictArgs } from '@storybook/types';
import { expectTypeOf } from 'expect-type';
import type { KeyboardEventHandler, ReactNode } from 'react';
import React from 'react';
import type { SetOptional } from 'type-fest';
import type { Mock } from '@storybook/test';
import { fn } from '@storybook/test';
import type { Decorator, Meta, StoryObj } from './public-types';
import type { ReactRenderer } from './types';
type ReactStory<TArgs, TRequiredArgs> = StoryAnnotations<ReactRenderer, TArgs, TRequiredArgs>;
type ButtonProps = { label: string; disabled: boolean };
const Button: (props: ButtonProps) => JSX.Element = () => <></>;
describe('Args can be provided in multiple ways', () => {
test('✅ All required args may be provided in meta', () => {
const meta = satisfies<Meta<typeof Button>>()({
component: Button,
args: { label: 'good', disabled: false },
});
type Story = StoryObj<typeof meta>;
const Basic: Story = {};
expectTypeOf(Basic).toEqualTypeOf<
ReactStory<ButtonProps, SetOptional<ButtonProps, 'label' | 'disabled'>>
>();
});
test('✅ Required args may be provided partial in meta and the story', () => {
const meta = satisfies<Meta<typeof Button>>()({
component: Button,
args: { label: 'good' },
});
const Basic: StoryObj<typeof meta> = {
args: { disabled: false },
};
type Expected = ReactStory<ButtonProps, SetOptional<ButtonProps, 'label'>>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
test('❌ The combined shape of meta args and story args must match the required args.', () => {
{
const meta = satisfies<Meta<typeof Button>>()({ component: Button });
const Basic: StoryObj<typeof meta> = {
// @ts-expect-error disabled not provided ❌
args: { label: 'good' },
};
type Expected = ReactStory<ButtonProps, ButtonProps>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
}
{
const meta = satisfies<Meta<typeof Button>>()({
component: Button,
args: { label: 'good' },
});
// @ts-expect-error disabled not provided ❌
const Basic: StoryObj<typeof meta> = {};
type Expected = ReactStory<ButtonProps, SetOptional<ButtonProps, 'label'>>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
}
{
const meta = satisfies<Meta<ButtonProps>>()({ component: Button });
const Basic: StoryObj<typeof meta> = {
// @ts-expect-error disabled not provided ❌
args: { label: 'good' },
};
type Expected = ReactStory<ButtonProps, ButtonProps>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
}
});
test('Component can be used as generic parameter for StoryObj', () => {
type Expected = ReactStory<ButtonProps, Partial<ButtonProps>>;
expectTypeOf<StoryObj<typeof Button>>().toEqualTypeOf<Expected>();
});
});
test('✅ All void functions are optional', () => {
interface CmpProps {
label: string;
disabled: boolean;
onClick(): void;
onKeyDown: KeyboardEventHandler;
onLoading: (s: string) => JSX.Element;
submitAction(): void;
}
const Cmp: (props: CmpProps) => JSX.Element = () => <></>;
const meta = satisfies<Meta<CmpProps>>()({
component: Cmp,
args: { label: 'good' },
});
const Basic: StoryObj<typeof meta> = {
args: { disabled: false, onLoading: () => <div>Loading...</div> },
};
type Expected = ReactStory<
CmpProps,
SetOptional<CmpProps, 'label' | 'onClick' | 'onKeyDown' | 'submitAction'>
>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
type ThemeData = 'light' | 'dark';
declare const Theme: (props: { theme: ThemeData; children?: ReactNode }) => JSX.Element;
describe('Story args can be inferred', () => {
test('Correct args are inferred when type is widened for render function', () => {
type Props = ButtonProps & { theme: ThemeData };
const meta = satisfies<Meta<Props>>()({
component: Button,
args: { disabled: false },
render: (args, { component }) => {
// component is not null as it is provided in meta
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const Component = component!;
return (
<Theme theme={args.theme}>
<Component {...args} />
</Theme>
);
},
});
const Basic: StoryObj<typeof meta> = { args: { theme: 'light', label: 'good' } };
type Expected = ReactStory<Props, SetOptional<Props, 'disabled'>>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
const withDecorator: Decorator<{ decoratorArg: number }> = (Story, { args }) => (
<>
Decorator: {args.decoratorArg}
<Story args={{ decoratorArg: 0 }} />
</>
);
test('Correct args are inferred when type is widened for decorators', () => {
type Props = ButtonProps & { decoratorArg: number };
const meta = satisfies<Meta<Props>>()({
component: Button,
args: { disabled: false },
decorators: [withDecorator],
});
const Basic: StoryObj<typeof meta> = { args: { decoratorArg: 0, label: 'good' } };
type Expected = ReactStory<Props, SetOptional<Props, 'disabled'>>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
test('Correct args are inferred when type is widened for multiple decorators', () => {
type Props = ButtonProps & { decoratorArg: number; decoratorArg2: string };
const secondDecorator: Decorator<{ decoratorArg2: string }> = (Story, { args }) => (
<>
Decorator: {args.decoratorArg2}
<Story />
</>
);
// decorator is not using args
const thirdDecorator: Decorator<Args> = (Story) => (
<>
<Story />
</>
);
// decorator is not using args
const fourthDecorator: Decorator<StrictArgs> = (Story) => (
<>
<Story />
</>
);
const meta = satisfies<Meta<Props>>()({
component: Button,
args: { disabled: false },
decorators: [withDecorator, secondDecorator, thirdDecorator, fourthDecorator],
});
const Basic: StoryObj<typeof meta> = {
args: { decoratorArg: 0, decoratorArg2: '', label: 'good' },
};
type Expected = ReactStory<Props, SetOptional<Props, 'disabled'>>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
});
test('StoryObj<typeof meta> is allowed when meta is upcasted to Meta<Props>', () => {
expectTypeOf<StoryObj<Meta<ButtonProps>>>().toEqualTypeOf<
ReactStory<
ButtonProps & { children?: ReactNode },
Partial<ButtonProps & { children?: ReactNode }>
>
>();
});
test('StoryObj<typeof meta> is allowed when meta is upcasted to Meta<typeof Cmp>', () => {
expectTypeOf<StoryObj<Meta<typeof Button>>>().toEqualTypeOf<
ReactStory<
ButtonProps & { children?: ReactNode },
Partial<ButtonProps & { children?: ReactNode }>
>
>();
});
test('StoryObj<typeof meta> is allowed when all arguments are optional', () => {
expectTypeOf<StoryObj<Meta<{ label?: string }>>>().toEqualTypeOf<
ReactStory<{ label?: string; children?: ReactNode }, { label?: string; children?: ReactNode }>
>();
});
test('Meta can be used without generic', () => {
expectTypeOf({ component: Button }).toMatchTypeOf<Meta>();
});
test('Props can be defined as interfaces, issue #21768', () => {
interface Props {
label: string;
}
const Component = ({ label }: Props) => <>{label}</>;
const withDecorator: Decorator = (Story) => (
<>
<Story />
</>
);
const meta = {
component: Component,
args: {
label: 'label',
},
decorators: [withDecorator],
} satisfies Meta<Props>;
const Basic: StoryObj<typeof meta> = {};
type Expected = ReactStory<Props, SetOptional<Props, 'label'>>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
test('Components without Props can be used, issue #21768', () => {
const Component = () => <>Foo</>;
const withDecorator: Decorator = (Story) => (
<>
<Story />
</>
);
const meta = {
component: Component,
decorators: [withDecorator],
} satisfies Meta<typeof Component>;
const Basic: StoryObj<typeof meta> = {};
type Expected = ReactStory<{}, {}>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
test('Meta is broken when using discriminating types, issue #23629', () => {
type TestButtonProps = {
text: string;
} & (
| {
id?: string;
onClick?: (e: unknown, id: string | undefined) => void;
}
| {
id: string;
onClick: (e: unknown, id: string) => void;
}
);
const TestButton: React.FC<TestButtonProps> = ({ text }) => {
return <p>{text}</p>;
};
expectTypeOf({
title: 'Components/Button',
component: TestButton,
args: {
text: 'Button',
},
}).toMatchTypeOf<Meta<TestButtonProps>>();
});
test('Infer mock function given to args in meta.', () => {
type Props = { label: string; onClick: () => void; onRender: () => JSX.Element };
const TestButton = (props: Props) => <></>;
const meta = {
component: TestButton,
args: { label: 'label', onClick: fn(), onRender: () => <>some jsx</> },
} satisfies Meta<typeof TestButton>;
type Story = StoryObj<typeof meta>;
const Basic: Story = {
play: async ({ args }) => {
expectTypeOf(args.onClick).toEqualTypeOf<Mock<[], void>>();
expectTypeOf(args.onRender).toEqualTypeOf<() => JSX.Element>();
},
};
type Expected = StoryAnnotations<
ReactRenderer,
Props & { onClick: Mock<[], void> },
Partial<Props>
>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
|
1,580 | 0 | petrpan-code/storybookjs/storybook/code/renderers/react/src | petrpan-code/storybookjs/storybook/code/renderers/react/src/__test__/composeStories.test.tsx | /// <reference types="@types/jest" />;
import React from 'react';
import { render, screen } from '@testing-library/react';
import type { Meta } from '@storybook/react';
import { expectTypeOf } from 'expect-type';
import { setProjectAnnotations, composeStories, composeStory } from '..';
import type { Button } from './Button';
import * as stories from './Button.stories';
// example with composeStories, returns an object with all stories composed with args/decorators
const { CSF3Primary } = composeStories(stories);
// example with composeStory, returns a single story composed with args/decorators
const Secondary = composeStory(stories.CSF2Secondary, stories.default);
test('renders primary button', () => {
render(<CSF3Primary>Hello world</CSF3Primary>);
const buttonElement = screen.getByText(/Hello world/i);
expect(buttonElement).not.toBeNull();
});
test('reuses args from composed story', () => {
render(<Secondary />);
const buttonElement = screen.getByRole('button');
expect(buttonElement.textContent).toEqual(Secondary.args.children);
});
test('onclick handler is called', async () => {
const onClickSpy = jest.fn();
render(<Secondary onClick={onClickSpy} />);
const buttonElement = screen.getByRole('button');
buttonElement.click();
expect(onClickSpy).toHaveBeenCalled();
});
test('reuses args from composeStories', () => {
const { getByText } = render(<CSF3Primary />);
const buttonElement = getByText(/foo/i);
expect(buttonElement).not.toBeNull();
});
describe('projectAnnotations', () => {
test('renders with default projectAnnotations', () => {
const WithEnglishText = composeStory(stories.CSF2StoryWithLocale, stories.default);
const { getByText } = render(<WithEnglishText />);
const buttonElement = getByText('Hello!');
expect(buttonElement).not.toBeNull();
});
test('renders with custom projectAnnotations via composeStory params', () => {
const WithPortugueseText = composeStory(stories.CSF2StoryWithLocale, stories.default, {
globalTypes: { locale: { defaultValue: 'pt' } } as any,
});
const { getByText } = render(<WithPortugueseText />);
const buttonElement = getByText('Olá!');
expect(buttonElement).not.toBeNull();
});
test('renders with custom projectAnnotations via setProjectAnnotations', () => {
setProjectAnnotations([{ parameters: { injected: true } }]);
const Story = composeStory(stories.CSF2StoryWithLocale, stories.default);
expect(Story.parameters?.injected).toBe(true);
});
});
describe('CSF3', () => {
test('renders with inferred globalRender', () => {
const Primary = composeStory(stories.CSF3Button, stories.default);
render(<Primary>Hello world</Primary>);
const buttonElement = screen.getByText(/Hello world/i);
expect(buttonElement).not.toBeNull();
});
test('renders with custom render function', () => {
const Primary = composeStory(stories.CSF3ButtonWithRender, stories.default);
render(<Primary />);
expect(screen.getByTestId('custom-render')).not.toBeNull();
});
test('renders with play function', async () => {
const CSF3InputFieldFilled = composeStory(stories.CSF3InputFieldFilled, stories.default);
const { container } = render(<CSF3InputFieldFilled />);
await CSF3InputFieldFilled.play({ canvasElement: container });
const input = screen.getByTestId('input') as HTMLInputElement;
expect(input.value).toEqual('Hello world!');
});
});
describe('ComposeStories types', () => {
test('Should support typescript operators', () => {
type ComposeStoriesParam = Parameters<typeof composeStories>[0];
expectTypeOf({
...stories,
default: stories.default as Meta<typeof Button>,
}).toMatchTypeOf<ComposeStoriesParam>();
expectTypeOf({
...stories,
default: stories.default satisfies Meta<typeof Button>,
}).toMatchTypeOf<ComposeStoriesParam>();
});
});
|
1,581 | 0 | petrpan-code/storybookjs/storybook/code/renderers/react/src | petrpan-code/storybookjs/storybook/code/renderers/react/src/__test__/internals.test.tsx | /// <reference types="@types/jest" />;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import React from 'react';
import { addons } from '@storybook/preview-api';
import { render, screen } from '@testing-library/react';
import { composeStories, composeStory } from '..';
import * as stories from './Button.stories';
const { CSF2StoryWithParamsAndDecorator } = composeStories(stories);
test('returns composed args including default values from argtypes', () => {
expect(CSF2StoryWithParamsAndDecorator.args).toEqual({
...stories.CSF2StoryWithParamsAndDecorator.args,
});
});
test('returns composed parameters from story', () => {
expect(CSF2StoryWithParamsAndDecorator.parameters).toEqual(
expect.objectContaining({
...stories.CSF2StoryWithParamsAndDecorator.parameters,
})
);
});
describe('Id of the story', () => {
test('is exposed correctly when composeStories is used', () => {
expect(CSF2StoryWithParamsAndDecorator.id).toBe(
'example-button--csf-2-story-with-params-and-decorator'
);
});
test('is exposed correctly when composeStory is used and exportsName is passed', () => {
const exportName = Object.entries(stories).filter(
([_, story]) => story === stories.CSF3Primary
)[0][0];
const Primary = composeStory(stories.CSF3Primary, stories.default, {}, exportName);
expect(Primary.id).toBe('example-button--csf-3-primary');
});
test("is not unique when composeStory is used and exportsName isn't passed", () => {
const Primary = composeStory(stories.CSF3Primary, stories.default);
expect(Primary.id).toContain('unknown');
});
});
// common in addons that need to communicate between manager and preview
test('should pass with decorators that need addons channel', () => {
const PrimaryWithChannels = composeStory(stories.CSF3Primary, stories.default, {
decorators: [
(StoryFn: any) => {
addons.getChannel();
return <StoryFn />;
},
],
});
render(<PrimaryWithChannels>Hello world</PrimaryWithChannels>);
const buttonElement = screen.getByText(/Hello world/i);
expect(buttonElement).not.toBeNull();
});
describe('Unsupported formats', () => {
test('should throw error if story is undefined', () => {
const UnsupportedStory = () => <div>hello world</div>;
UnsupportedStory.story = { parameters: {} };
const UnsupportedStoryModule: any = {
default: {},
UnsupportedStory: undefined,
};
expect(() => {
composeStories(UnsupportedStoryModule);
}).toThrow();
});
});
describe('non-story exports', () => {
test('should filter non-story exports with excludeStories', () => {
const StoryModuleWithNonStoryExports = {
default: {
title: 'Some/Component',
excludeStories: /.*Data/,
},
LegitimateStory: () => <div>hello world</div>,
mockData: {},
};
const result = composeStories(StoryModuleWithNonStoryExports);
expect(Object.keys(result)).not.toContain('mockData');
});
test('should filter non-story exports with includeStories', () => {
const StoryModuleWithNonStoryExports = {
default: {
title: 'Some/Component',
includeStories: /.*Story/,
},
LegitimateStory: () => <div>hello world</div>,
mockData: {},
};
const result = composeStories(StoryModuleWithNonStoryExports);
expect(Object.keys(result)).not.toContain('mockData');
});
});
// Batch snapshot testing
const testCases = Object.values(composeStories(stories)).map((Story) => [
// The ! is necessary in Typescript only, as the property is part of a partial type
Story.storyName!,
Story,
]);
test.each(testCases)('Renders %s story', async (_storyName, Story) => {
const tree = await render(<Story />);
expect(tree.baseElement).toMatchSnapshot();
});
|
1,582 | 0 | petrpan-code/storybookjs/storybook/code/renderers/react/src/__test__ | petrpan-code/storybookjs/storybook/code/renderers/react/src/__test__/__snapshots__/internals.test.tsx.snap | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Renders CSF2Secondary story 1`] = `
<body>
<div>
<button
class="storybook-button storybook-button--medium storybook-button--secondary"
type="button"
>
Children coming from story args!
</button>
</div>
</body>
`;
exports[`Renders CSF2StoryWithLocale story 1`] = `
<body>
<div>
<button
class="storybook-button storybook-button--medium storybook-button--secondary"
type="button"
>
Hello!
</button>
</div>
</body>
`;
exports[`Renders CSF2StoryWithParamsAndDecorator story 1`] = `
<body>
<div>
<button
class="storybook-button storybook-button--medium storybook-button--secondary"
type="button"
>
foo
</button>
</div>
</body>
`;
exports[`Renders CSF3Button story 1`] = `
<body>
<div>
<button
class="storybook-button storybook-button--medium storybook-button--secondary"
type="button"
>
foo
</button>
</div>
</body>
`;
exports[`Renders CSF3ButtonWithRender story 1`] = `
<body>
<div>
<div>
<p
data-testid="custom-render"
>
I am a custom render function
</p>
<button
class="storybook-button storybook-button--medium storybook-button--secondary"
type="button"
>
foo
</button>
</div>
</div>
</body>
`;
exports[`Renders CSF3InputFieldFilled story 1`] = `
<body>
<div>
<input
data-testid="input"
/>
</div>
</body>
`;
exports[`Renders CSF3Primary story 1`] = `
<body>
<div>
<button
class="storybook-button storybook-button--large storybook-button--primary"
type="button"
>
foo
</button>
</div>
</body>
`;
|
1,584 | 0 | petrpan-code/storybookjs/storybook/code/renderers/react/src | petrpan-code/storybookjs/storybook/code/renderers/react/src/docs/extractArgTypes.test.ts | import 'jest-specific-snapshot';
import path from 'path';
import fs from 'fs';
// @ts-expect-error (seems broken/missing)
import requireFromString from 'require-from-string';
import { transformFileSync, transformSync } from '@babel/core';
import { inferControls } from '@storybook/preview-api';
import type { Renderer } from '@storybook/types';
import { normalizeNewlines } from '@storybook/docs-tools';
import type { StoryContext } from '../types';
import { extractProps } from './extractProps';
import { extractArgTypes } from './extractArgTypes';
// File hierarchy:
// __testfixtures__ / some-test-case / input.*
const inputRegExp = /^input\..*$/;
const transformToModule = (inputCode: string) => {
const options = {
presets: [
[
'@babel/preset-env',
{
targets: {
esmodules: true,
},
},
],
],
};
const { code } = transformSync(inputCode, options) || {};
return normalizeNewlines(code || '');
};
const annotateWithDocgen = (inputPath: string) => {
const options = {
presets: ['@babel/typescript', '@babel/react'],
plugins: ['babel-plugin-react-docgen', '@babel/plugin-transform-class-properties'],
babelrc: false,
};
const { code } = transformFileSync(inputPath, options) || {};
return normalizeNewlines(code || '');
};
// We need to skip a set of test cases that use ESM code, as the `requireFromString`
// code below does not support it. These stories will be tested via Chromatic in the
// sandboxes. Hopefully we can figure out a better testing strategy in the future.
const skippedTests = [
'js-class-component',
'js-function-component',
'js-function-component-inline-defaults',
'js-function-component-inline-defaults-no-propTypes',
'ts-function-component',
'ts-function-component-inline-defaults',
'js-proptypes',
];
describe('react component properties', () => {
// Fixture files are in template/stories
const fixturesDir = path.resolve(__dirname, '../../template/stories/docgen-components');
fs.readdirSync(fixturesDir, { withFileTypes: true }).forEach((testEntry) => {
if (testEntry.isDirectory()) {
const testDir = path.join(fixturesDir, testEntry.name);
const testFile = fs.readdirSync(testDir).find((fileName) => inputRegExp.test(fileName));
if (testFile) {
if (skippedTests.includes(testEntry.name)) {
it.skip(`${testEntry.name}`, () => {});
} else {
it(`${testEntry.name}`, () => {
const inputPath = path.join(testDir, testFile);
// snapshot the output of babel-plugin-react-docgen
const docgenPretty = annotateWithDocgen(inputPath);
expect(docgenPretty).toMatchSpecificSnapshot(path.join(testDir, 'docgen.snapshot'));
// transform into an uglier format that's works with require-from-string
const docgenModule = transformToModule(docgenPretty);
// snapshot the output of component-properties/react
const { component } = requireFromString(docgenModule, inputPath);
const properties = extractProps(component);
expect(properties).toMatchSpecificSnapshot(path.join(testDir, 'properties.snapshot'));
// snapshot the output of `extractArgTypes`
const argTypes = extractArgTypes(component);
const parameters = { __isArgsStory: true };
const rows = inferControls({
argTypes,
parameters,
} as unknown as StoryContext<Renderer>);
expect(rows).toMatchSpecificSnapshot(path.join(testDir, 'argTypes.snapshot'));
});
}
}
}
});
});
|
1,587 | 0 | petrpan-code/storybookjs/storybook/code/renderers/react/src | petrpan-code/storybookjs/storybook/code/renderers/react/src/docs/jsxDecorator.test.tsx | /* eslint-disable jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events */
import type { FC, PropsWithChildren } from 'react';
import React, { createElement, Profiler } from 'react';
import PropTypes from 'prop-types';
import { addons, useEffect } from '@storybook/preview-api';
import { SNIPPET_RENDERED } from '@storybook/docs-tools';
import { renderJsx, jsxDecorator } from './jsxDecorator';
jest.mock('@storybook/preview-api');
const mockedAddons = addons as jest.Mocked<typeof addons>;
const mockedUseEffect = useEffect as jest.Mocked<typeof useEffect>;
expect.addSnapshotSerializer({
print: (val: any) => val,
test: (val) => typeof val === 'string',
});
describe('renderJsx', () => {
it('basic', () => {
expect(renderJsx(<div>hello</div>, {})).toMatchInlineSnapshot(`
<div>
hello
</div>
`);
});
it('functions', () => {
// eslint-disable-next-line no-console
const onClick = () => console.log('onClick');
expect(renderJsx(<div onClick={onClick}>hello</div>, {})).toMatchInlineSnapshot(`
<div onClick={() => {}}>
hello
</div>
`);
});
it('undefined values', () => {
expect(renderJsx(<div className={undefined}>hello</div>, {})).toMatchInlineSnapshot(`
<div>
hello
</div>
`);
});
it('null values', () => {
expect(renderJsx(<div>hello</div>, {})).toMatchInlineSnapshot(`
<div>
hello
</div>
`);
});
it('large objects', () => {
const obj = Array.from({ length: 20 }).reduce((acc, _, i) => {
// @ts-expect-error (Converted from ts-ignore)
acc[`key_${i}`] = `val_${i}`;
return acc;
}, {});
expect(renderJsx(<div data-val={obj} />, {})).toMatchInlineSnapshot(`
<div
data-val={{
key_0: 'val_0',
key_1: 'val_1',
key_10: 'val_10',
key_11: 'val_11',
key_12: 'val_12',
key_13: 'val_13',
key_14: 'val_14',
key_15: 'val_15',
key_16: 'val_16',
key_17: 'val_17',
key_18: 'val_18',
key_19: 'val_19',
key_2: 'val_2',
key_3: 'val_3',
key_4: 'val_4',
key_5: 'val_5',
key_6: 'val_6',
key_7: 'val_7',
key_8: 'val_8',
key_9: 'val_9'
}}
/>
`);
});
it('long arrays', () => {
const arr = Array.from({ length: 20 }, (_, i) => `item ${i}`);
expect(renderJsx(<div data-val={arr} />, {})).toMatchInlineSnapshot(`
<div
data-val={[
'item 0',
'item 1',
'item 2',
'item 3',
'item 4',
'item 5',
'item 6',
'item 7',
'item 8',
'item 9',
'item 10',
'item 11',
'item 12',
'item 13',
'item 14',
'item 15',
'item 16',
'item 17',
'item 18',
'item 19'
]}
/>
`);
});
it('forwardRef component', () => {
const MyExoticComponent = React.forwardRef<PropsWithChildren<{}>>(function MyExoticComponent(
props,
_ref
) {
return <div>{props.children}</div>;
});
expect(renderJsx(createElement(MyExoticComponent, {}, 'I am forwardRef!'), {}))
.toMatchInlineSnapshot(`
<MyExoticComponent>
I am forwardRef!
</MyExoticComponent>
`);
});
it('memo component', () => {
const MyMemoComponent: FC = React.memo(function MyMemoComponent(props) {
return <div>{props.children}</div>;
});
expect(renderJsx(createElement(MyMemoComponent, {}, 'I am memo!'), {})).toMatchInlineSnapshot(`
<MyMemoComponent>
I am memo!
</MyMemoComponent>
`);
});
it('Profiler', () => {
function ProfilerComponent(props: any) {
return (
<Profiler id="profiler-test" onRender={() => {}}>
<div>{props.children}</div>
</Profiler>
);
}
expect(renderJsx(createElement(ProfilerComponent, {}, 'I am Profiler'), {}))
.toMatchInlineSnapshot(`
<ProfilerComponent>
I am Profiler
</ProfilerComponent>
`);
});
it('should not add default props to string if the prop value has not changed', () => {
const Container = ({ className, children }: { className: string; children: string }) => {
return <div className={className}>{children}</div>;
};
Container.propTypes = {
children: PropTypes.string.isRequired,
className: PropTypes.string,
};
Container.defaultProps = {
className: 'super-container',
};
expect(renderJsx(<Container>yo dude</Container>, {})).toMatchInlineSnapshot(`
<Container className="super-container">
yo dude
</Container>
`);
});
});
// @ts-expect-error (Converted from ts-ignore)
const makeContext = (name: string, parameters: any, args: any, extra?: object): StoryContext => ({
id: `jsx-test--${name}`,
kind: 'js-text',
name,
parameters,
unmappedArgs: args,
args,
...extra,
});
describe('jsxDecorator', () => {
let mockChannel: { on: jest.Mock; emit?: jest.Mock };
beforeEach(() => {
mockedAddons.getChannel.mockReset();
// @ts-expect-error (Converted from ts-ignore)
mockedUseEffect.mockImplementation((cb) => setTimeout(() => cb(), 0));
mockChannel = { on: jest.fn(), emit: jest.fn() };
mockedAddons.getChannel.mockReturnValue(mockChannel as any);
});
it('should render dynamically for args stories', async () => {
const storyFn = (args: any) => <div>args story</div>;
const context = makeContext('args', { __isArgsStory: true }, {});
jsxDecorator(storyFn, context);
await new Promise((r) => setTimeout(r, 0));
expect(mockChannel.emit).toHaveBeenCalledWith(SNIPPET_RENDERED, {
id: 'jsx-test--args',
args: {},
source: '<div>\n args story\n</div>',
});
});
it('should not render decorators when provided excludeDecorators parameter', async () => {
const storyFn = (args: any) => <div>args story</div>;
const decoratedStoryFn = (args: any) => (
<div style={{ padding: 25, border: '3px solid red' }}>{storyFn(args)}</div>
);
const context = makeContext(
'args',
{
__isArgsStory: true,
docs: {
source: {
excludeDecorators: true,
},
},
},
{},
{ originalStoryFn: storyFn }
);
jsxDecorator(decoratedStoryFn, context);
await new Promise((r) => setTimeout(r, 0));
expect(mockChannel.emit).toHaveBeenCalledWith(SNIPPET_RENDERED, {
id: 'jsx-test--args',
args: {},
source: '<div>\n args story\n</div>',
});
});
it('should skip dynamic rendering for no-args stories', async () => {
const storyFn = () => <div>classic story</div>;
const context = makeContext('classic', {}, {});
jsxDecorator(storyFn, context);
await new Promise((r) => setTimeout(r, 0));
expect(mockChannel.emit).not.toHaveBeenCalled();
});
it('renders MDX properly', async () => {
// FIXME: generate this from actual MDX
const mdxElement: ReturnType<typeof createElement> = {
// @ts-expect-error (Converted from ts-ignore)
type: { displayName: 'MDXCreateElement' },
props: {
mdxType: 'div',
originalType: 'div',
className: 'foo',
},
};
jsxDecorator(() => mdxElement, makeContext('mdx-args', { __isArgsStory: true }, {}));
await new Promise((r) => setTimeout(r, 0));
expect(mockChannel.emit).toHaveBeenCalledWith(SNIPPET_RENDERED, {
id: 'jsx-test--mdx-args',
args: {},
source: '<div className="foo" />',
});
});
it('handles stories that trigger Suspense', async () => {
// if a story function uses a hook or other library that triggers suspense, it will throw a Promise until it is resolved
// and then it will return the story content after the promise is resolved
const storyFn = jest.fn();
storyFn
.mockImplementationOnce(() => {
// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw Promise.resolve();
})
.mockImplementation(() => {
return <div>resolved args story</div>;
});
const jsx = '';
const context = makeContext('args', { __isArgsStory: true, jsx }, {});
expect(() => {
jsxDecorator(storyFn, context);
}).toThrow(Promise);
jsxDecorator(storyFn, context);
await new Promise((r) => setTimeout(r, 0));
expect(mockChannel.emit).toHaveBeenCalledTimes(2);
expect(mockChannel.emit).nthCalledWith(1, SNIPPET_RENDERED, {
id: 'jsx-test--args',
args: {},
source: '',
});
expect(mockChannel.emit).nthCalledWith(2, SNIPPET_RENDERED, {
id: 'jsx-test--args',
args: {},
source: '<div>\n resolved args story\n</div>',
});
});
});
|
1,600 | 0 | petrpan-code/storybookjs/storybook/code/renderers/react/src/docs/lib | petrpan-code/storybookjs/storybook/code/renderers/react/src/docs/lib/inspection/acornParser.test.ts | import { parse } from './acornParser';
import type {
InspectionElement,
InspectionObject,
InspectionArray,
InspectionIdentifier,
InspectionLiteral,
InspectionFunction,
InspectionUnknown,
} from './types';
import { InspectionType } from './types';
describe('parse', () => {
describe('expression', () => {
it('support HTML element', () => {
const result = parse('<div>Hello!</div>');
const inferredType = result.inferredType as InspectionElement;
expect(inferredType.type).toBe(InspectionType.ELEMENT);
expect(inferredType.identifier).toBe('div');
expect(result.ast).toBeDefined();
});
it('support React declaration', () => {
const result = parse('<FunctionalComponent />');
const inferredType = result.inferredType as InspectionElement;
expect(inferredType.type).toBe(InspectionType.ELEMENT);
expect(inferredType.identifier).toBe('FunctionalComponent');
expect(result.ast).toBeDefined();
});
it('support anonymous functional React component', () => {
const result = parse('() => { return <div>Hey!</div>; }');
const inferredType = result.inferredType as InspectionElement;
expect(inferredType.type).toBe(InspectionType.ELEMENT);
expect(inferredType.identifier).toBeUndefined();
expect(result.ast).toBeDefined();
});
it('support named functional React component', () => {
const result = parse('function NamedFunctionalComponent() { return <div>Hey!</div>; }');
const inferredType = result.inferredType as InspectionElement;
expect(inferredType.type).toBe(InspectionType.ELEMENT);
expect(inferredType.identifier).toBe('NamedFunctionalComponent');
expect(result.ast).toBeDefined();
});
it('support class React component', () => {
const result = parse(`
class ClassComponent extends React.PureComponent {
render() {
return <div>Hey!</div>;
}
}`);
const inferredType = result.inferredType as InspectionElement;
expect(inferredType.type).toBe(InspectionType.ELEMENT);
expect(inferredType.identifier).toBe('ClassComponent');
expect(result.ast).toBeDefined();
});
it('support PropTypes.shape', () => {
const result = parse('PropTypes.shape({ foo: PropTypes.string })');
const inferredType = result.inferredType as InspectionObject;
expect(inferredType.type).toBe(InspectionType.OBJECT);
expect(inferredType.depth).toBe(1);
expect(result.ast).toBeDefined();
});
it('support deep PropTypes.shape', () => {
const result = parse('PropTypes.shape({ foo: PropTypes.shape({ bar: PropTypes.string }) })');
const inferredType = result.inferredType as InspectionObject;
expect(inferredType.type).toBe(InspectionType.OBJECT);
expect(inferredType.depth).toBe(2);
expect(result.ast).toBeDefined();
});
it('support shape', () => {
const result = parse('shape({ foo: string })');
const inferredType = result.inferredType as InspectionObject;
expect(inferredType.type).toBe(InspectionType.OBJECT);
expect(inferredType.depth).toBe(1);
expect(result.ast).toBeDefined();
});
it('support deep shape', () => {
const result = parse('shape({ foo: shape({ bar: string }) })');
const inferredType = result.inferredType as InspectionObject;
expect(inferredType.type).toBe(InspectionType.OBJECT);
expect(inferredType.depth).toBe(2);
expect(result.ast).toBeDefined();
});
it('support single prop object literal', () => {
const result = parse('{ foo: PropTypes.string }');
const inferredType = result.inferredType as InspectionObject;
expect(inferredType.type).toBe(InspectionType.OBJECT);
expect(inferredType.depth).toBe(1);
expect(result.ast).toBeDefined();
});
it('support multi prop object literal', () => {
const result = parse(`
{
foo: PropTypes.string,
bar: PropTypes.string
}`);
const inferredType = result.inferredType as InspectionObject;
expect(inferredType.type).toBe(InspectionType.OBJECT);
expect(inferredType.depth).toBe(1);
expect(result.ast).toBeDefined();
});
it('support deep object literal', () => {
const result = parse(`
{
foo: {
hey: PropTypes.string
},
bar: PropTypes.string,
hey: {
ho: PropTypes.string
}
}`);
const inferredType = result.inferredType as InspectionObject;
expect(inferredType.type).toBe(InspectionType.OBJECT);
expect(inferredType.depth).toBe(2);
expect(result.ast).toBeDefined();
});
it('support required prop', () => {
const result = parse('{ foo: PropTypes.string.isRequired }');
const inferredType = result.inferredType as InspectionObject;
expect(inferredType.type).toBe(InspectionType.OBJECT);
expect(inferredType.depth).toBe(1);
expect(result.ast).toBeDefined();
});
it('support array', () => {
const result = parse("['bottom-left', 'bottom-center', 'bottom-right']");
const inferredType = result.inferredType as InspectionArray;
expect(inferredType.type).toBe(InspectionType.ARRAY);
expect(inferredType.depth).toBe(1);
expect(result.ast).toBeDefined();
});
it('support deep array', () => {
const result = parse("['bottom-left', { foo: string }, [['hey', 'ho']]]");
const inferredType = result.inferredType as InspectionArray;
expect(inferredType.type).toBe(InspectionType.ARRAY);
expect(inferredType.depth).toBe(3);
expect(result.ast).toBeDefined();
});
it('support object identifier', () => {
const result = parse('NAMED_OBJECT');
const inferredType = result.inferredType as InspectionIdentifier;
expect(inferredType.type).toBe(InspectionType.IDENTIFIER);
expect(inferredType.identifier).toBe('NAMED_OBJECT');
expect(result.ast).toBeDefined();
});
it('support anonymous function', () => {
const result = parse('() => {}');
const inferredType = result.inferredType as InspectionFunction;
expect(inferredType.type).toBe(InspectionType.FUNCTION);
expect(inferredType.identifier).toBeUndefined();
expect(inferredType.hasParams).toBeFalsy();
expect(inferredType.params.length).toBe(0);
expect(result.ast).toBeDefined();
});
it('support anonymous function with arguments', () => {
const result = parse('(a, b) => {}');
const inferredType = result.inferredType as InspectionFunction;
expect(inferredType.type).toBe(InspectionType.FUNCTION);
expect(inferredType.identifier).toBeUndefined();
expect(inferredType.hasParams).toBeTruthy();
expect(inferredType.params.length).toBe(2);
expect(result.ast).toBeDefined();
});
it('support named function', () => {
const result = parse('function concat() {}');
const inferredType = result.inferredType as InspectionFunction;
expect(inferredType.type).toBe(InspectionType.FUNCTION);
expect(inferredType.identifier).toBe('concat');
expect(inferredType.hasParams).toBeFalsy();
expect(inferredType.params.length).toBe(0);
expect(result.ast).toBeDefined();
});
it('support named function with arguments', () => {
const result = parse('function concat(a, b) {}');
const inferredType = result.inferredType as InspectionFunction;
expect(inferredType.type).toBe(InspectionType.FUNCTION);
expect(inferredType.identifier).toBe('concat');
expect(inferredType.hasParams).toBeTruthy();
expect(inferredType.params.length).toBe(2);
expect(result.ast).toBeDefined();
});
it('support class', () => {
const result = parse('class Foo {}');
const inferredType = result.inferredType as InspectionFunction;
expect(inferredType.type).toBe(InspectionType.CLASS);
expect(inferredType.identifier).toBe('Foo');
expect(result.ast).toBeDefined();
});
[
{ name: 'string', value: "'string value'" },
{ name: 'numeric', value: '1' },
{ name: 'boolean (true)', value: 'true' },
{ name: 'boolean (false)', value: 'false' },
{ name: 'null', value: 'null' },
].forEach((x) => {
it(`support ${x.name}`, () => {
const result = parse(x.value);
const inferredType = result.inferredType as InspectionLiteral;
expect(inferredType.type).toBe(InspectionType.LITERAL);
expect(result.ast).toBeDefined();
});
});
it("returns Unknown when it's not supported", () => {
const result = parse("Symbol('foo')");
const inferredType = result.inferredType as InspectionUnknown;
expect(inferredType.type).toBe(InspectionType.UNKNOWN);
expect(result.ast).toBeDefined();
});
});
});
|
1,606 | 0 | petrpan-code/storybookjs/storybook/code/renderers/react/src/docs | petrpan-code/storybookjs/storybook/code/renderers/react/src/docs/propTypes/generateFuncSignature.test.ts | import { parseJsDoc } from '@storybook/docs-tools';
import { generateFuncSignature, generateShortFuncSignature } from './generateFuncSignature';
describe('generateFuncSignature', () => {
it('should return an empty string when there is no @params and @returns tags', () => {
// @ts-expect-error (invalid input)
const result = generateFuncSignature(null, null);
expect(result).toBe('');
});
it('should return a signature with a single arg when there is a @param tag with a name', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@param event').extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('(event)');
});
it('should return a signature with a single arg when there is a @param tag with a name and a type', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@param {SyntheticEvent} event').extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('(event: SyntheticEvent)');
});
it('should return a signature with a single arg when there is a @param tag with a name, a type and a desc', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc(
'@param {SyntheticEvent} event - React event'
).extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('(event: SyntheticEvent)');
});
it('should support @param of record type', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@param {{a: number}} event').extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('(event: ({a: number}))');
});
it('should support @param of union type', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@param {(number|boolean)} event').extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('(event: (number|boolean))');
});
it('should support @param of array type', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@param {number[]} event').extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('(event: number[])');
});
it('should support @param with a nullable type', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@param {?number} event').extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('(event: number)');
});
it('should support @param with a non nullable type', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@param {!number} event').extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('(event: number)');
});
it('should support optional @param with []', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@param {number} [event]').extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('(event: number)');
});
it('should support optional @param with =', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@param {number=} event').extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('(event: number)');
});
it('should support @param of type any', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@param {*} event').extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('(event: any)');
});
it('should support multiple @param tags', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc(
'@param {SyntheticEvent} event\n@param {string} customData'
).extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('(event: SyntheticEvent, customData: string)');
});
it('should return a signature with a return type when there is a @returns with a type', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@returns {string}').extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('() => string');
});
it('should support @returns of record type', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@returns {{a: number, b: string}}').extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('() => ({a: number, b: string})');
});
it('should support @returns of array type', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@returns {integer[]}').extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('() => integer[]');
});
it('should support @returns of union type', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@returns {(number|boolean)}').extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('() => (number|boolean)');
});
it('should support @returns type any', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@returns {*}').extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('() => any');
});
it('should support @returns of type void', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@returns {void}').extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('() => void');
});
it('should return a full signature when there is a single @param tag and a @returns', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc(
'@param {SyntheticEvent} event - React event.\n@returns {string}'
).extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('(event: SyntheticEvent) => string');
});
it('should return a full signature when there is a multiple @param tags and a @returns', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc(
'@param {SyntheticEvent} event - React event.\n@param {string} data\n@returns {string}'
).extractedTags;
const result = generateFuncSignature(params, returns);
expect(result).toBe('(event: SyntheticEvent, data: string) => string');
});
});
describe('generateShortFuncSignature', () => {
it('should return an empty string when there is no @params and @returns tags', () => {
// @ts-expect-error (invalid input)
const result = generateShortFuncSignature(null, null);
expect(result).toBe('');
});
it('should return ( ... ) when there is @params', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@param event').extractedTags;
const result = generateShortFuncSignature(params, returns);
expect(result).toBe('( ... )');
});
it('should return ( ... ) => returnsType when there is @params and a @returns', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@param event\n@returns {string}').extractedTags;
const result = generateShortFuncSignature(params, returns);
expect(result).toBe('( ... ) => string');
});
it('should return () => returnsType when there is only a @returns', () => {
// @ts-expect-error (unsafe)
const { params, returns } = parseJsDoc('@returns {string}').extractedTags;
const result = generateShortFuncSignature(params, returns);
expect(result).toBe('() => string');
});
});
|
1,608 | 0 | petrpan-code/storybookjs/storybook/code/renderers/react/src/docs | petrpan-code/storybookjs/storybook/code/renderers/react/src/docs/propTypes/handleProp.test.tsx | /* eslint-disable no-underscore-dangle */
import PropTypes from 'prop-types';
import React from 'react';
import {
type PropDef,
extractComponentProps,
type DocgenInfo,
type DocgenPropDefaultValue,
} from '@storybook/docs-tools';
import { enhancePropTypesProp, enhancePropTypesProps } from './handleProp';
type Component = any;
const DOCGEN_SECTION = 'props';
function ReactComponent() {
return <div>React Component!</div>;
}
function createDocgenSection(docgenInfo: DocgenInfo): Record<string, any> {
return {
[DOCGEN_SECTION]: {
...docgenInfo,
},
};
}
function createDocgenProp({
name,
type,
...others
}: Partial<DocgenInfo> & { name: string }): Record<string, any> {
return {
[name]: {
type,
required: false,
...others,
},
};
}
// eslint-disable-next-line react/forbid-foreign-prop-types
function createComponent({ propTypes = {}, defaultProps = {}, docgenInfo = {} }): Component {
const component = () => {
return <div>Hey!</div>;
};
component.propTypes = propTypes;
component.defaultProps = defaultProps;
// @ts-expect-error (Converted from ts-ignore)
component.__docgenInfo = createDocgenSection(docgenInfo);
return component;
}
function createDefaultValue(defaultValue: string): DocgenPropDefaultValue {
return { value: defaultValue };
}
function extractPropDef(component: Component, rawDefaultProp?: any): PropDef {
return enhancePropTypesProp(extractComponentProps(component, DOCGEN_SECTION)[0], rawDefaultProp);
}
describe('enhancePropTypesProp', () => {
describe('type', () => {
function createTestComponent(docgenInfo: Partial<DocgenInfo>): Component {
return createComponent({
docgenInfo: {
...createDocgenProp({ name: 'prop', ...docgenInfo }),
},
});
}
describe('custom', () => {
describe('when raw value is available', () => {
it('should support literal', () => {
const component = createTestComponent({
type: {
name: 'custom',
raw: 'MY_LITERAL',
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('MY_LITERAL');
expect(type.detail).toBeUndefined();
});
it('should support short object', () => {
const component = createTestComponent({
type: {
name: 'custom',
raw: '{\n text: PropTypes.string.isRequired,\n}',
},
});
const { type } = extractPropDef(component);
const expectedSummary = '{ text: string }';
expect(type.summary.replace(/\s/g, '')).toBe(expectedSummary.replace(/\s/g, ''));
expect(type.detail).toBeUndefined();
});
it('should support long object', () => {
const component = createTestComponent({
type: {
name: 'custom',
raw: '{\n text: PropTypes.string.isRequired,\n value1: PropTypes.string.isRequired,\n value2: PropTypes.string.isRequired,\n value3: PropTypes.string.isRequired,\n value4: PropTypes.string.isRequired,\n}',
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('object');
const expectedDetail = `{
text: string,
value1: string,
value2: string,
value3: string,
value4: string
}`;
expect(type.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should not have a deep object as summary', () => {
const component = createTestComponent({
type: {
name: 'custom',
raw: '{\n foo: { bar: PropTypes.string.isRequired,\n }}',
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('object');
});
it('should use identifier of a React element when available', () => {
const component = createTestComponent({
type: {
name: 'custom',
raw: 'function InlinedFunctionalComponent() {\n return <div>Inlined FunctionalComponent!</div>;\n}',
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('InlinedFunctionalComponent');
const expectedDetail = `function InlinedFunctionalComponent() {
return <div>Inlined FunctionalComponent!</div>;
}`;
expect(type.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should not use identifier of a HTML element', () => {
const component = createTestComponent({
type: {
name: 'custom',
raw: '<div>Hello world from Montreal, Quebec, Canada!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</div>',
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('element');
const expectedDetail =
'<div>Hello world from Montreal, Quebec, Canada!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</div>';
expect(type.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should support element without identifier', () => {
const component = createTestComponent({
type: {
name: 'custom',
raw: '() => {\n return <div>Inlined FunctionalComponent!</div>;\n}',
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('element');
const expectedDetail = `() => {
return <div>Inlined FunctionalComponent!</div>;
}`;
expect(type.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
describe('when it is not a known type', () => {
it('should return "custom" when its a long type', () => {
const component = createTestComponent({
type: {
name: 'custom',
raw: 'Symbol("A very very very very very very lonnnngggggggggggggggggggggggggggggggggggg symbol")',
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('custom');
expect(type.detail).toBe(
'Symbol("A very very very very very very lonnnngggggggggggggggggggggggggggggggggggg symbol")'
);
});
it('should return "custom" when its a short type', () => {
const component = createTestComponent({
type: {
name: 'custom',
raw: 'Symbol("Hey!")',
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('Symbol("Hey!")');
expect(type.detail).toBeUndefined();
});
});
});
it("should return 'custom' when there is no raw value", () => {
const component = createTestComponent({
type: {
name: 'custom',
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('custom');
});
});
[
'any',
'bool',
'string',
'number',
'symbol',
'object',
'element',
'elementType',
'node',
].forEach((x) => {
it(`should return '${x}' when type is ${x}`, () => {
const component = createTestComponent({
type: {
name: x,
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe(x);
});
});
it('should support short shape', () => {
const component = createTestComponent({
type: {
name: 'shape',
value: {
foo: {
name: 'string',
required: false,
},
},
},
});
const { type } = extractPropDef(component);
const expectedSummary = '{ foo: string }';
expect(type.summary.replace(/\s/g, '')).toBe(expectedSummary.replace(/\s/g, ''));
expect(type.detail).toBeUndefined();
});
it('should support long shape', () => {
const component = createTestComponent({
type: {
name: 'shape',
value: {
foo: {
name: 'string',
required: false,
},
bar: {
name: 'string',
required: false,
},
another: {
name: 'string',
required: false,
},
another2: {
name: 'string',
required: false,
},
another3: {
name: 'string',
required: false,
},
another4: {
name: 'string',
required: false,
},
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('object');
const expectedDetail = `{
foo: string,
bar: string,
another: string,
another2: string,
another3: string,
another4: string
}`;
expect(type.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should not have a deep shape as summary', () => {
const component = createTestComponent({
type: {
name: 'shape',
value: {
bar: {
name: 'shape',
value: {
hey: {
name: 'string',
required: false,
},
},
required: false,
},
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('object');
});
it('should support enum of string', () => {
const component = createTestComponent({
type: {
name: 'enum',
value: [
{
value: "'News'",
computed: false,
},
{
value: "'Photos'",
computed: false,
},
],
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe("'News' | 'Photos'");
});
it('should support enum of object', () => {
const component = createTestComponent({
type: {
name: 'enum',
value: [
{
value:
'{\n text: PropTypes.string.isRequired,\n value: PropTypes.string.isRequired,\n}',
computed: true,
},
{
value:
'{\n foo: PropTypes.string,\n bar: PropTypes.string,\n hey: PropTypes.string,\n ho: PropTypes.string,\n}',
computed: true,
},
],
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('object | object');
const expectedDetail = `{
text: string,
value: string
} | {
foo: string,
bar: string,
hey: string,
ho: string
}`;
expect(type.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should support short object in enum summary', () => {
const component = createTestComponent({
type: {
name: 'enum',
value: [
{
value: '{\n text: PropTypes.string.isRequired,\n}',
computed: true,
},
{
value: '{\n foo: PropTypes.string,\n}',
computed: true,
},
],
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('{ text: string } | { foo: string }');
});
it('should not have a deep object in an enum summary', () => {
const component = createTestComponent({
type: {
name: 'enum',
value: [
{
value: '{\n text: { foo: PropTypes.string.isRequired,\n }\n}',
computed: true,
},
{
value: '{\n foo: PropTypes.string,\n}',
computed: true,
},
],
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('object | object');
});
it('should support enum of element', () => {
const component = createTestComponent({
type: {
name: 'enum',
value: [
{
value: '() => {\n return <div>FunctionalComponent!</div>;\n}',
computed: true,
},
{
value:
'class ClassComponent extends React.PureComponent {\n render() {\n return <div>ClassComponent!</div>;\n }\n}',
computed: true,
},
],
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('element | ClassComponent');
const expectedDetail = `() => {
return <div>FunctionalComponent!</div>;
} | class ClassComponent extends React.PureComponent {
render() {
return <div>ClassComponent!</div>;
}
}`;
expect(type.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
describe('func', () => {
it('should return "func" when the prop dont have a description', () => {
const component = createTestComponent({
type: {
name: 'func',
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('func');
});
it('should return "func" when the prop have a description without JSDoc tags', () => {
const component = createTestComponent({
type: {
name: 'func',
},
description: 'Hey! Hey!',
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('func');
});
it('should return a func signature when there is JSDoc tags.', () => {
const component = createTestComponent({
type: {
name: 'func',
},
description: '@param event\n@param data\n@returns {string}',
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('(event, data) => string');
});
});
it('should return the instance type when type is instanceOf', () => {
const component = createTestComponent({
type: {
name: 'instanceOf',
value: 'Set',
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('Set');
});
describe('objectOf', () => {
it('should support objectOf primitive', () => {
const component = createTestComponent({
type: {
name: 'objectOf',
value: {
name: 'number',
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('objectOf(number)');
expect(type.detail).toBeUndefined();
});
it('should support objectOf of identifier', () => {
const component = createTestComponent({
type: {
name: 'objectOf',
value: {
name: 'custom',
raw: 'NAMED_OBJECT',
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('objectOf(NAMED_OBJECT)');
expect(type.detail).toBeUndefined();
});
it('should support objectOf short object', () => {
const component = createTestComponent({
type: {
name: 'objectOf',
value: {
name: 'custom',
raw: '{\n foo: PropTypes.string,\n}',
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('objectOf({ foo: string })');
expect(type.detail).toBeUndefined();
});
it('should support objectOf long object', () => {
const component = createTestComponent({
type: {
name: 'objectOf',
value: {
name: 'custom',
raw: '{\n foo: PropTypes.string,\n bar: PropTypes.string,\n another: PropTypes.string,\n anotherAnother: PropTypes.string,\n}',
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('objectOf(object)');
const expectedDetail = `objectOf({
foo: string,
bar: string,
another: string,
anotherAnother: string
})`;
expect(type.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should not have deep object in summary', () => {
const component = createTestComponent({
type: {
name: 'objectOf',
value: {
name: 'custom',
raw: '{\n foo: { bar: PropTypes.string,\n }\n}',
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('objectOf(object)');
});
it('should support objectOf short shape', () => {
const component = createTestComponent({
type: {
name: 'objectOf',
value: {
name: 'shape',
value: {
foo: {
name: 'string',
required: false,
},
},
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('objectOf({ foo: string })');
expect(type.detail).toBeUndefined();
});
it('should support objectOf long shape', () => {
const component = createTestComponent({
type: {
name: 'objectOf',
value: {
name: 'shape',
value: {
foo: {
name: 'string',
required: false,
},
bar: {
name: 'string',
required: false,
},
another: {
name: 'string',
required: false,
},
anotherAnother: {
name: 'string',
required: false,
},
},
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('objectOf(object)');
const expectedDetail = `objectOf({
foo: string,
bar: string,
another: string,
anotherAnother: string
})`;
expect(type.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should not have a deep shape in summary', () => {
const component = createTestComponent({
type: {
name: 'objectOf',
value: {
name: 'shape',
value: {
bar: {
name: 'shape',
value: {
hey: {
name: 'string',
required: false,
},
},
required: false,
},
},
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('objectOf(object)');
});
});
it('should support union', () => {
const component = createTestComponent({
type: {
name: 'union',
value: [
{
name: 'string',
},
{
name: 'instanceOf',
value: 'Set',
},
],
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('string | Set');
expect(type.detail).toBeUndefined();
});
describe('array', () => {
it('should support array of primitive', () => {
const component = createTestComponent({
type: {
name: 'arrayOf',
value: {
name: 'number',
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('number[]');
expect(type.detail).toBeUndefined();
});
it('should support array of identifier', () => {
const component = createTestComponent({
type: {
name: 'arrayOf',
value: {
name: 'custom',
raw: 'NAMED_OBJECT',
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('NAMED_OBJECT[]');
expect(type.detail).toBeUndefined();
});
it('should support array of short object', () => {
const component = createTestComponent({
type: {
name: 'arrayOf',
value: {
name: 'custom',
raw: '{\n foo: PropTypes.string,\n}',
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('[{ foo: string }]');
expect(type.detail).toBeUndefined();
});
it('should support array of long object', () => {
const component = createTestComponent({
type: {
name: 'arrayOf',
value: {
name: 'custom',
raw: '{\n text: PropTypes.string.isRequired,\n value: PropTypes.string.isRequired,\n another: PropTypes.string.isRequired,\n another2: PropTypes.string.isRequired,\n another3: PropTypes.string.isRequired,\n another4: PropTypes.string.isRequired,\n}',
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('object[]');
const expectedDetail = `[{
text: string,
value: string,
another: string,
another2: string,
another3: string,
another4: string
}]`;
expect(type.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should not have deep object in summary', () => {
const component = createTestComponent({
type: {
name: 'arrayOf',
value: {
name: 'custom',
raw: '{\n foo: { bar: PropTypes.string, }\n}',
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('object[]');
});
it('should support array of short shape', () => {
const component = createTestComponent({
type: {
name: 'arrayOf',
value: {
name: 'shape',
value: {
foo: {
name: 'string',
required: false,
},
},
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('[{ foo: string }]');
expect(type.detail).toBeUndefined();
});
it('should support array of long shape', () => {
const component = createTestComponent({
type: {
name: 'arrayOf',
value: {
name: 'shape',
value: {
foo: {
name: 'string',
required: false,
},
bar: {
name: 'string',
required: false,
},
another: {
name: 'string',
required: false,
},
another2: {
name: 'string',
required: false,
},
another3: {
name: 'string',
required: false,
},
another4: {
name: 'string',
required: false,
},
},
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('object[]');
const expectedDetail = `[{
foo: string,
bar: string,
another: string,
another2: string,
another3: string,
another4: string
}]`;
expect(type.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should not have deep shape in summary', () => {
const component = createTestComponent({
type: {
name: 'arrayOf',
value: {
name: 'shape',
value: {
bar: {
name: 'shape',
value: {
hey: {
name: 'string',
required: false,
},
},
required: false,
},
},
},
},
});
const { type } = extractPropDef(component);
expect(type.summary).toBe('object[]');
});
});
});
describe('defaultValue', () => {
function createTestComponent(
defaultValue: DocgenPropDefaultValue,
typeName = 'anything-is-fine'
): Component {
return createComponent({
docgenInfo: {
...createDocgenProp({
name: 'prop',
type: { name: typeName },
defaultValue,
}),
},
});
}
it('should support short object', () => {
const component = createTestComponent(createDefaultValue("{ foo: 'foo', bar: 'bar' }"));
const { defaultValue } = extractPropDef(component);
const expectedSummary = "{ foo: 'foo', bar: 'bar' }";
expect(defaultValue?.summary.replace(/\s/g, '')).toBe(expectedSummary.replace(/\s/g, ''));
expect(defaultValue?.detail).toBeUndefined();
});
it('should support long object', () => {
const component = createTestComponent(
createDefaultValue("{ foo: 'foo', bar: 'bar', another: 'another' }")
);
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('object');
const expectedDetail = `{
foo: 'foo',
bar: 'bar',
another: 'another'
}`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should not have deep object in summary', () => {
const component = createTestComponent(
createDefaultValue("{ foo: 'foo', bar: { hey: 'ho' } }")
);
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('object');
});
it('should support short function', () => {
const component = createTestComponent(createDefaultValue('() => {}'));
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('() => {}');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support long function', () => {
const component = createTestComponent(
createDefaultValue(
'(foo, bar) => {\n const concat = foo + bar;\n const append = concat + " hey!";\n \n return append;\n}'
)
);
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('func');
const expectedDetail = `(foo, bar) => {
const concat = foo + bar;
const append = concat + ' hey!';
return append
}`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should use the name of function when available and indicate that args are present', () => {
const component = createTestComponent(
createDefaultValue('function concat(a, b) {\n return a + b;\n}')
);
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('concat( ... )');
const expectedDetail = `function concat(a, b) {
return a + b
}`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should use the name of function when available', () => {
const component = createTestComponent(
createDefaultValue('function hello() {\n return "hello";\n}')
);
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('hello()');
const expectedDetail = `function hello() {
return 'hello'
}`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should support short element', () => {
const component = createTestComponent(createDefaultValue('<div>Hey!</div>'));
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('<div>Hey!</div>');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support long element', () => {
const component = createTestComponent(
createDefaultValue(
'<div>Hey! Hey! Hey!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</div>'
)
);
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('element');
expect(defaultValue?.detail).toBe(
'<div>Hey! Hey! Hey!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</div>'
);
});
it('should support element with props', () => {
const component = createTestComponent(createDefaultValue('<Component className="toto" />'));
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('<Component />');
expect(defaultValue?.detail).toBe('<Component className="toto" />');
});
it("should use the name of the React component when it's available", () => {
const component = createTestComponent(
createDefaultValue(
'function InlinedFunctionalComponent() {\n return <div>Inlined FunctionalComponent!</div>;\n}'
)
);
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('<InlinedFunctionalComponent />');
const expectedDetail = `function InlinedFunctionalComponent() {
return <div>Inlined FunctionalComponent!</div>;
}`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should not use the name of an HTML element', () => {
const component = createTestComponent(createDefaultValue('<div>Hey!</div>'));
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).not.toBe('<div />');
});
it('should support short array', () => {
const component = createTestComponent(createDefaultValue('[1]'));
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('[1]');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support long array', () => {
const component = createTestComponent(
createDefaultValue(
'[\n {\n thing: {\n id: 2,\n func: () => {},\n arr: [],\n },\n },\n]'
)
);
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('array');
const expectedDetail = `[{
thing: {
id: 2,
func: () => {
},
arr: []
}
}]`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should not have deep array in summary', () => {
const component = createTestComponent(createDefaultValue('[[[1]]]'));
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('array');
});
describe('fromRawDefaultProp', () => {
[
{ type: 'number', defaultProp: 1 },
{ type: 'boolean', defaultProp: true },
{ type: 'symbol', defaultProp: Symbol('hey!') },
].forEach((x) => {
it(`should support ${x.type}`, () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null);
const { defaultValue } = extractPropDef(component, x.defaultProp);
expect(defaultValue?.summary).toBe(x.defaultProp.toString());
expect(defaultValue?.detail).toBeUndefined();
});
});
it('should support strings', () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null);
const { defaultValue } = extractPropDef(component, 'foo');
expect(defaultValue?.summary).toBe('"foo"');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support array of primitives', () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null);
const { defaultValue } = extractPropDef(component, [1, 2, 3]);
expect(defaultValue?.summary).toBe('[1, 2, 3]');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support array of short object', () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null);
const { defaultValue } = extractPropDef(component, [{ foo: 'bar' }]);
expect(defaultValue?.summary).toBe("[{ 'foo': 'bar' }]");
expect(defaultValue?.detail).toBeUndefined();
});
it('should support array of long object', () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null);
const { defaultValue } = extractPropDef(component, [{ foo: 'bar', bar: 'foo', hey: 'ho' }]);
expect(defaultValue?.summary).toBe('array');
const expectedDetail = `[{
'foo': 'bar',
'bar': 'foo',
'hey': 'ho'
}]`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should support short object', () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null);
const { defaultValue } = extractPropDef(component, { foo: 'bar' });
expect(defaultValue?.summary).toBe("{ 'foo': 'bar' }");
expect(defaultValue?.detail).toBeUndefined();
});
it('should support long object', () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null);
const { defaultValue } = extractPropDef(component, { foo: 'bar', bar: 'foo', hey: 'ho' });
expect(defaultValue?.summary).toBe('object');
const expectedDetail = `{
'foo': 'bar',
'bar': 'foo',
'hey': 'ho'
}`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should support anonymous function', () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null);
const { defaultValue } = extractPropDef(component, () => 'hey!');
expect(defaultValue?.summary).toBe('func');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support named function', () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null);
const { defaultValue } = extractPropDef(component, function hello() {
return 'world!';
});
expect(defaultValue?.summary).toBe('hello()');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support named function with params', () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null);
const { defaultValue } = extractPropDef(component, function add(a: number, b: number) {
return a + b;
});
expect(defaultValue?.summary).toBe('add( ... )');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support React element', () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null);
const defaultProp = <ReactComponent />;
// Simulate babel-plugin-add-react-displayname.
defaultProp.type.displayName = 'ReactComponent';
const { defaultValue } = extractPropDef(component, defaultProp);
expect(defaultValue?.summary).toBe('<ReactComponent />');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support React element with props', () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null);
// @ts-expect-error (Converted from ts-ignore)
const defaultProp = <ReactComponent className="toto" />;
// Simulate babel-plugin-add-react-displayname.
defaultProp.type.displayName = 'ReactComponent';
const { defaultValue } = extractPropDef(component, defaultProp);
expect(defaultValue?.summary).toBe('<ReactComponent />');
expect(defaultValue?.detail).toBe('<ReactComponent className="toto" />');
});
it('should support short HTML element', () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null);
const { defaultValue } = extractPropDef(component, <div>HTML element</div>);
expect(defaultValue?.summary).toBe('<div>HTML element</div>');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support long HTML element', () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null);
const { defaultValue } = extractPropDef(
component,
<div>HTML element!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</div>
);
expect(defaultValue?.summary).toBe('element');
const expectedDetail = `<div>
HTML element!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
</div>`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
['element', 'elementType'].forEach((x) => {
it(`should support inlined React class component for ${x}`, () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null, x);
const { defaultValue } = extractPropDef(
component,
class InlinedClassComponent extends React.PureComponent {
render() {
return <div>Inlined ClassComponent!</div>;
}
}
);
expect(defaultValue?.summary).toBe('<InlinedClassComponent />');
expect(defaultValue?.detail).toBeUndefined();
});
it(`should support inlined anonymous React functional component for ${x}`, () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null, x);
const { defaultValue } = extractPropDef(component, () => {
return <div>Inlined FunctionalComponent!</div>;
});
expect(defaultValue?.summary).toBe('element');
expect(defaultValue?.detail).toBeUndefined();
});
it(`should support inlined anonymous React functional component with props for ${x}`, () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null, x);
const { defaultValue } = extractPropDef(component, ({ foo }: { foo: string }) => {
return <div>{foo}</div>;
});
expect(defaultValue?.summary).toBe('element');
expect(defaultValue?.detail).toBeUndefined();
});
it(`should support inlined named React functional component for ${x}`, () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null, x);
const { defaultValue } = extractPropDef(component, function InlinedFunctionalComponent() {
return <div>Inlined FunctionalComponent!</div>;
});
expect(defaultValue?.summary).toBe('<InlinedFunctionalComponent />');
expect(defaultValue?.detail).toBeUndefined();
});
it(`should support inlined named React functional component with props for ${x}`, () => {
// @ts-expect-error (invalid input)
const component = createTestComponent(null, x);
const { defaultValue } = extractPropDef(
component,
function InlinedFunctionalComponent({ foo }: { foo: string }) {
return <div>{foo}</div>;
}
);
expect(defaultValue?.summary).toBe('<InlinedFunctionalComponent />');
expect(defaultValue?.detail).toBeUndefined();
});
});
});
});
});
describe('enhancePropTypesProps', () => {
it('should keep the original definition order', () => {
const component = createComponent({
propTypes: {
foo: PropTypes.string,
middleWithDefaultValue: PropTypes.string,
bar: PropTypes.string,
endWithDefaultValue: PropTypes.string,
},
docgenInfo: {
...createDocgenProp({
name: 'middleWithDefaultValue',
type: { name: 'string' },
defaultValue: { value: 'Middle!' },
}),
...createDocgenProp({
name: 'endWithDefaultValue',
type: { name: 'string' },
defaultValue: { value: 'End!' },
}),
...createDocgenProp({
name: 'foo',
type: { name: 'string' },
}),
...createDocgenProp({
name: 'bar',
type: { name: 'string' },
}),
},
});
const props = enhancePropTypesProps(
extractComponentProps(component, DOCGEN_SECTION),
component
);
expect(props.length).toBe(4);
expect(props[0].name).toBe('foo');
expect(props[1].name).toBe('middleWithDefaultValue');
expect(props[2].name).toBe('bar');
expect(props[3].name).toBe('endWithDefaultValue');
});
it('should not include @ignore props', () => {
const component = createComponent({
propTypes: {
foo: PropTypes.string,
bar: PropTypes.string,
},
docgenInfo: {
...createDocgenProp({
name: 'foo',
type: { name: 'string' },
}),
...createDocgenProp({
name: 'bar',
type: { name: 'string' },
description: '@ignore',
}),
},
});
const props = enhancePropTypesProps(
extractComponentProps(component, DOCGEN_SECTION),
component
);
expect(props.length).toBe(1);
expect(props[0].name).toBe('foo');
});
});
|
1,612 | 0 | petrpan-code/storybookjs/storybook/code/renderers/react/src/docs | petrpan-code/storybookjs/storybook/code/renderers/react/src/docs/typeScript/handleProp.test.tsx | /* eslint-disable no-underscore-dangle */
import React from 'react';
import {
type PropDef,
extractComponentProps,
type DocgenInfo,
type DocgenPropDefaultValue,
} from '@storybook/docs-tools';
import { enhanceTypeScriptProp } from './handleProp';
type Component = any;
const DOCGEN_SECTION = 'props';
function ReactComponent() {
return <div>React Component!</div>;
}
function createDocgenSection(docgenInfo: DocgenInfo): Record<string, any> {
return {
[DOCGEN_SECTION]: {
...docgenInfo,
},
};
}
function createDocgenProp({
name,
tsType,
...others
}: Partial<DocgenInfo> & { name: string }): Record<string, any> {
return {
[name]: {
tsType,
required: false,
...others,
},
};
}
// eslint-disable-next-line react/forbid-foreign-prop-types
function createComponent({ propTypes = {}, defaultProps = {}, docgenInfo = {} }): Component {
const component = () => {
return <div>Hey!</div>;
};
component.propTypes = propTypes;
component.defaultProps = defaultProps;
// @ts-expect-error (Converted from ts-ignore)
component.__docgenInfo = createDocgenSection(docgenInfo);
return component;
}
function createDefaultValue(defaultValue: string): DocgenPropDefaultValue {
return { value: defaultValue };
}
function extractPropDef(component: Component, rawDefaultProp?: any): PropDef {
return enhanceTypeScriptProp(extractComponentProps(component, DOCGEN_SECTION)[0], rawDefaultProp);
}
describe('enhanceTypeScriptProp', () => {
describe('defaultValue', () => {
function createTestComponent(
defaultValue: DocgenPropDefaultValue | undefined,
typeName = 'anything-is-fine'
): Component {
return createComponent({
docgenInfo: {
...createDocgenProp({
name: 'prop',
tsType: { name: typeName },
defaultValue,
}),
},
});
}
it('should support short object', () => {
const component = createTestComponent(createDefaultValue("{ foo: 'foo', bar: 'bar' }"));
const { defaultValue } = extractPropDef(component);
const expectedSummary = "{ foo: 'foo', bar: 'bar' }";
expect(defaultValue?.summary.replace(/\s/g, '')).toBe(expectedSummary.replace(/\s/g, ''));
expect(defaultValue?.detail).toBeUndefined();
});
it('should support long object', () => {
const component = createTestComponent(
createDefaultValue("{ foo: 'foo', bar: 'bar', another: 'another' }")
);
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('object');
const expectedDetail = `{
foo: 'foo',
bar: 'bar',
another: 'another'
}`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should not have deep object in summary', () => {
const component = createTestComponent(
createDefaultValue("{ foo: 'foo', bar: { hey: 'ho' } }")
);
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('object');
});
it('should support short function', () => {
const component = createTestComponent(createDefaultValue('() => {}'));
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('() => {}');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support long function', () => {
const component = createTestComponent(
createDefaultValue(
'(foo, bar) => {\n const concat = foo + bar;\n const append = concat + " hey!";\n \n return append;\n}'
)
);
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('func');
const expectedDetail = `(foo, bar) => {
const concat = foo + bar;
const append = concat + ' hey!';
return append
}`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should use the name of function when available and indicate that args are present', () => {
const component = createTestComponent(
createDefaultValue('function concat(a, b) {\n return a + b;\n}')
);
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('concat( ... )');
const expectedDetail = `function concat(a, b) {
return a + b
}`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should use the name of function when available', () => {
const component = createTestComponent(
createDefaultValue('function hello() {\n return "hello";\n}')
);
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('hello()');
const expectedDetail = `function hello() {
return 'hello'
}`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should support short element', () => {
const component = createTestComponent(createDefaultValue('<div>Hey!</div>'));
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('<div>Hey!</div>');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support long element', () => {
const component = createTestComponent(
createDefaultValue(
'<div>Hey! Hey! Hey!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</div>'
)
);
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('element');
expect(defaultValue?.detail).toBe(
'<div>Hey! Hey! Hey!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</div>'
);
});
it('should support element with props', () => {
const component = createTestComponent(createDefaultValue('<Component className="toto" />'));
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('<Component />');
expect(defaultValue?.detail).toBe('<Component className="toto" />');
});
it("should use the name of the React component when it's available", () => {
const component = createTestComponent(
createDefaultValue(
'function InlinedFunctionalComponent() {\n return <div>Inlined FunctionalComponent!</div>;\n}'
)
);
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('<InlinedFunctionalComponent />');
const expectedDetail = `function InlinedFunctionalComponent() {
return <div>Inlined FunctionalComponent!</div>;
}`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should not use the name of an HTML element', () => {
const component = createTestComponent(createDefaultValue('<div>Hey!</div>'));
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).not.toBe('<div />');
});
it('should support short array', () => {
const component = createTestComponent(createDefaultValue('[1]'));
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('[1]');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support long array', () => {
const component = createTestComponent(
createDefaultValue(
'[\n {\n thing: {\n id: 2,\n func: () => {},\n arr: [],\n },\n },\n]'
)
);
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('array');
const expectedDetail = `[{
thing: {
id: 2,
func: () => {
},
arr: []
}
}]`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should not have deep array in summary', () => {
const component = createTestComponent(createDefaultValue('[[[1]]]'));
const { defaultValue } = extractPropDef(component);
expect(defaultValue?.summary).toBe('array');
});
describe('fromRawDefaultProp', () => {
[
{ type: 'number', defaultProp: 1 },
{ type: 'boolean', defaultProp: true },
{ type: 'symbol', defaultProp: Symbol('hey!') },
].forEach((x) => {
it(`should support ${x.type}`, () => {
// @ts-expect-error (not strict)
const component = createTestComponent(null);
const { defaultValue } = extractPropDef(component, x.defaultProp);
expect(defaultValue?.summary).toBe(x.defaultProp.toString());
expect(defaultValue?.detail).toBeUndefined();
});
});
it('should support strings', () => {
const component = createTestComponent(undefined);
const { defaultValue } = extractPropDef(component, 'foo');
expect(defaultValue?.summary).toBe('"foo"');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support array of primitives', () => {
const component = createTestComponent(undefined);
const { defaultValue } = extractPropDef(component, [1, 2, 3]);
expect(defaultValue?.summary).toBe('[1, 2, 3]');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support array of short object', () => {
const component = createTestComponent(undefined);
const { defaultValue } = extractPropDef(component, [{ foo: 'bar' }]);
expect(defaultValue?.summary).toBe("[{ 'foo': 'bar' }]");
expect(defaultValue?.detail).toBeUndefined();
});
it('should support array of long object', () => {
const component = createTestComponent(undefined);
const { defaultValue } = extractPropDef(component, [{ foo: 'bar', bar: 'foo', hey: 'ho' }]);
expect(defaultValue?.summary).toBe('array');
const expectedDetail = `[{
'foo': 'bar',
'bar': 'foo',
'hey': 'ho'
}]`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should support short object', () => {
const component = createTestComponent(undefined);
const { defaultValue } = extractPropDef(component, { foo: 'bar' });
expect(defaultValue?.summary).toBe("{ 'foo': 'bar' }");
expect(defaultValue?.detail).toBeUndefined();
});
it('should support long object', () => {
const component = createTestComponent(undefined);
const { defaultValue } = extractPropDef(component, { foo: 'bar', bar: 'foo', hey: 'ho' });
expect(defaultValue?.summary).toBe('object');
const expectedDetail = `{
'foo': 'bar',
'bar': 'foo',
'hey': 'ho'
}`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
it('should support anonymous function', () => {
const component = createTestComponent(undefined);
const { defaultValue } = extractPropDef(component, () => 'hey!');
expect(defaultValue?.summary).toBe('func');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support named function', () => {
const component = createTestComponent(undefined);
const { defaultValue } = extractPropDef(component, function hello() {
return 'world!';
});
expect(defaultValue?.summary).toBe('hello()');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support named function with params', () => {
const component = createTestComponent(undefined);
const { defaultValue } = extractPropDef(component, function add(a: number, b: number) {
return a + b;
});
expect(defaultValue?.summary).toBe('add( ... )');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support React element', () => {
const component = createTestComponent(undefined);
const defaultProp = <ReactComponent />;
// Simulate babel-plugin-add-react-displayname.
defaultProp.type.displayName = 'ReactComponent';
const { defaultValue } = extractPropDef(component, defaultProp);
expect(defaultValue?.summary).toBe('<ReactComponent />');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support React element with props', () => {
const component = createTestComponent(undefined);
// @ts-expect-error (Converted from ts-ignore)
const defaultProp = <ReactComponent className="toto" />;
// Simulate babel-plugin-add-react-displayname.
defaultProp.type.displayName = 'ReactComponent';
const { defaultValue } = extractPropDef(component, defaultProp);
expect(defaultValue?.summary).toBe('<ReactComponent />');
expect(defaultValue?.detail).toBe('<ReactComponent className="toto" />');
});
it('should support short HTML element', () => {
const component = createTestComponent(undefined);
const { defaultValue } = extractPropDef(component, <div>HTML element</div>);
expect(defaultValue?.summary).toBe('<div>HTML element</div>');
expect(defaultValue?.detail).toBeUndefined();
});
it('should support long HTML element', () => {
const component = createTestComponent(undefined);
const { defaultValue } = extractPropDef(
component,
<div>HTML element!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</div>
);
expect(defaultValue?.summary).toBe('element');
const expectedDetail = `<div>
HTML element!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
</div>`;
expect(defaultValue?.detail?.replace(/\s/g, '')).toBe(expectedDetail.replace(/\s/g, ''));
});
['element', 'elementType'].forEach((x) => {
it(`should support inlined React class component for ${x}`, () => {
const component = createTestComponent(undefined, x);
const { defaultValue } = extractPropDef(
component,
class InlinedClassComponent extends React.PureComponent {
render() {
return <div>Inlined ClassComponent!</div>;
}
}
);
expect(defaultValue?.summary).toBe('<InlinedClassComponent />');
expect(defaultValue?.detail).toBeUndefined();
});
it(`should support inlined anonymous React functional component for ${x}`, () => {
const component = createTestComponent(undefined, x);
const { defaultValue } = extractPropDef(component, () => {
return <div>Inlined FunctionalComponent!</div>;
});
expect(defaultValue?.summary).toBe('element');
expect(defaultValue?.detail).toBeUndefined();
});
it(`should support inlined anonymous React functional component with props for ${x}`, () => {
const component = createTestComponent(undefined, x);
const { defaultValue } = extractPropDef(component, ({ foo }: { foo: string }) => {
return <div>{foo}</div>;
});
expect(defaultValue?.summary).toBe('element');
expect(defaultValue?.detail).toBeUndefined();
});
it(`should support inlined named React functional component for ${x}`, () => {
const component = createTestComponent(undefined, x);
const { defaultValue } = extractPropDef(component, function InlinedFunctionalComponent() {
return <div>Inlined FunctionalComponent!</div>;
});
expect(defaultValue?.summary).toBe('<InlinedFunctionalComponent />');
expect(defaultValue?.detail).toBeUndefined();
});
it(`should support inlined named React functional component with props for ${x}`, () => {
const component = createTestComponent(undefined, x);
const { defaultValue } = extractPropDef(
component,
function InlinedFunctionalComponent({ foo }: { foo: string }) {
return <div>{foo}</div>;
}
);
expect(defaultValue?.summary).toBe('<InlinedFunctionalComponent />');
expect(defaultValue?.detail).toBeUndefined();
});
});
});
});
});
|
1,818 | 0 | petrpan-code/storybookjs/storybook/code/renderers/svelte | petrpan-code/storybookjs/storybook/code/renderers/svelte/src/public-types.test.ts | import { describe, test } from '@jest/globals';
import { satisfies } from '@storybook/core-common';
import type { ComponentAnnotations, StoryAnnotations } from '@storybook/types';
import { expectTypeOf } from 'expect-type';
import type { ComponentProps, SvelteComponentTyped } from 'svelte';
import Button from './__test__/Button.svelte';
import Decorator1 from './__test__/Decorator.svelte';
import Decorator2 from './__test__/Decorator2.svelte';
import type { Decorator, Meta, StoryObj } from './public-types';
import type { SvelteRenderer } from './types';
type SvelteStory<Component extends SvelteComponentTyped, Args, RequiredArgs> = StoryAnnotations<
SvelteRenderer<Component>,
Args,
RequiredArgs
>;
describe('Meta', () => {
test('Generic parameter of Meta can be a component', () => {
const meta: Meta<Button> = {
component: Button,
args: {
label: 'good',
disabled: false,
},
};
expectTypeOf(meta).toEqualTypeOf<
ComponentAnnotations<SvelteRenderer<Button>, { disabled: boolean; label: string }>
>();
});
test('Generic parameter of Meta can be the props of the component', () => {
const meta: Meta<{ disabled: boolean; label: string }> = {
component: Button,
args: { label: 'good', disabled: false },
};
expectTypeOf(meta).toEqualTypeOf<
ComponentAnnotations<SvelteRenderer, { disabled: boolean; label: string }>
>();
});
test('Events are inferred from component', () => {
const meta: Meta<Button> = {
component: Button,
args: {
label: 'good',
disabled: false,
},
render: (args) => ({
Component: Button,
props: args,
on: {
mousemove: (event) => {
expectTypeOf(event).toEqualTypeOf<MouseEvent>();
},
},
}),
};
expectTypeOf(meta).toMatchTypeOf<Meta<Button>>();
});
test('Events fallback to custom events when no component is specified', () => {
const meta: Meta<{ disabled: boolean; label: string }> = {
component: Button,
args: { label: 'good', disabled: false },
render: (args) => ({
Component: Button,
props: args,
on: {
mousemove: (event) => {
expectTypeOf(event).toEqualTypeOf<CustomEvent>();
},
},
}),
};
expectTypeOf(meta).toMatchTypeOf<Meta<Button>>();
});
});
describe('StoryObj', () => {
test('✅ Required args may be provided partial in meta and the story', () => {
const meta = satisfies<Meta<Button>>()({
component: Button,
args: { label: 'good' },
});
type Actual = StoryObj<typeof meta>;
type Expected = SvelteStory<
Button,
{ disabled: boolean; label: string },
{ disabled: boolean; label?: string }
>;
expectTypeOf<Actual>().toEqualTypeOf<Expected>();
});
test('❌ The combined shape of meta args and story args must match the required args.', () => {
{
const meta = satisfies<Meta<Button>>()({ component: Button });
type Expected = SvelteStory<
Button,
{ disabled: boolean; label: string },
{ disabled: boolean; label: string }
>;
expectTypeOf<StoryObj<typeof meta>>().toEqualTypeOf<Expected>();
}
{
const meta = satisfies<Meta<Button>>()({
component: Button,
args: { label: 'good' },
});
// @ts-expect-error disabled not provided ❌
const Basic: StoryObj<typeof meta> = {};
type Expected = SvelteStory<
Button,
{ disabled: boolean; label: string },
{ disabled: boolean; label?: string }
>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
}
{
const meta = satisfies<Meta<{ label: string; disabled: boolean }>>()({ component: Button });
const Basic: StoryObj<typeof meta> = {
// @ts-expect-error disabled not provided ❌
args: { label: 'good' },
};
type Expected = SvelteStory<
Button,
{ disabled: boolean; label: string },
{ disabled: boolean; label: string }
>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
}
});
test('Component can be used as generic parameter for StoryObj', () => {
expectTypeOf<StoryObj<Button>>().toEqualTypeOf<
SvelteStory<
Button,
{ disabled: boolean; label: string },
{ disabled?: boolean; label?: string }
>
>();
});
});
type ThemeData = 'light' | 'dark';
describe('Story args can be inferred', () => {
test('Correct args are inferred when type is widened for render function', () => {
const meta = satisfies<Meta<ComponentProps<Button> & { theme: ThemeData }>>()({
component: Button,
args: { disabled: false },
render: (args, { component }) => {
return {
Component: component,
props: args,
};
},
});
const Basic: StoryObj<typeof meta> = { args: { theme: 'light', label: 'good' } };
type Expected = SvelteStory<
Button,
{ theme: ThemeData; disabled: boolean; label: string },
{ theme: ThemeData; disabled?: boolean; label: string }
>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
const withDecorator: Decorator<{ decoratorArg: string }> = (
_storyFn,
{ args: { decoratorArg } }
) => ({
Component: Decorator1,
props: { decoratorArg },
});
test('Correct args are inferred when type is widened for decorators', () => {
type Props = ComponentProps<Button> & { decoratorArg: string };
const meta = satisfies<Meta<Props>>()({
component: Button,
args: { disabled: false },
decorators: [withDecorator],
});
const Basic: StoryObj<typeof meta> = { args: { decoratorArg: 'title', label: 'good' } };
type Expected = SvelteStory<
Button,
Props,
{ decoratorArg: string; disabled?: boolean; label: string }
>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
test('Correct args are inferred when type is widened for multiple decorators', () => {
type Props = ComponentProps<Button> & { decoratorArg: string; decoratorArg2: string };
const secondDecorator: Decorator<{ decoratorArg2: string }> = (
_storyFn,
{ args: { decoratorArg2 } }
) => ({
Component: Decorator2,
props: { decoratorArg2 },
});
const meta = satisfies<Meta<Props>>()({
component: Button,
args: { disabled: false },
decorators: [withDecorator, secondDecorator],
});
const Basic: StoryObj<typeof meta> = {
args: { decoratorArg: '', decoratorArg2: '', label: 'good' },
};
type Expected = SvelteStory<
Button,
Props,
{ decoratorArg: string; decoratorArg2: string; disabled?: boolean; label: string }
>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
});
|
1,826 | 0 | petrpan-code/storybookjs/storybook/code/renderers/svelte/src | petrpan-code/storybookjs/storybook/code/renderers/svelte/src/docs/extractArgTypes.test.ts | import { describe, expect } from '@jest/globals';
import svelteDoc from 'sveltedoc-parser';
import * as fs from 'fs';
import { createArgTypes } from './extractArgTypes';
const content = fs.readFileSync(`${__dirname}/sample/MockButton.svelte`, 'utf-8');
describe('Extracting Arguments', () => {
it('should be svelte', () => {
expect(content).toMatchInlineSnapshot(`
<script>
import { createEventDispatcher, afterUpdate } from 'svelte';
export let text = '';
export let rounded = true;
const dispatch = createEventDispatcher();
function onClick(event) {
rounded = !rounded;
/**
* Click Event
*/
dispatch('click', event);
}
afterUpdate(() => {
/**
* After Update
*/
dispatch('afterUpdate');
});
</script>
<style>
.rounded {
border-radius: 35px;
}
.button {
border: 3px solid;
padding: 10px 20px;
background-color: white;
outline: none;
}
</style>
<svelte:options accessors="{true}">
</svelte:options>
<button class="button"
class:rounded
on:click="{onClick}"
>
<strong>
{rounded ? 'Round' : 'Square'} corners
</strong>
<br>
{text}
<slot {rounded}>
</slot>
</button>
`);
});
it('should generate ArgTypes', async () => {
const doc = await svelteDoc.parse({ fileContent: content, version: 3 });
const results = createArgTypes(doc);
expect(results).toMatchInlineSnapshot(`
Object {
"event_afterUpdate": Object {
"action": "afterUpdate",
"control": false,
"description": "After Update",
"name": "afterUpdate",
"table": Object {
"category": "events",
},
},
"event_click": Object {
"action": "click",
"control": false,
"description": "Click Event",
"name": "click",
"table": Object {
"category": "events",
},
},
"rounded": Object {
"control": Object {
"type": "boolean",
},
"description": undefined,
"name": "rounded",
"table": Object {
"category": "properties",
"defaultValue": Object {
"summary": true,
},
"type": Object {
"summary": "boolean",
},
},
"type": Object {
"name": "boolean",
"required": false,
},
},
"slot_default": Object {
"control": false,
"description": "Default Slot
\`{rounded}\`",
"name": "default",
"table": Object {
"category": "slots",
},
},
"text": Object {
"control": Object {
"type": "text",
},
"description": undefined,
"name": "text",
"table": Object {
"category": "properties",
"defaultValue": Object {
"summary": "",
},
"type": Object {
"summary": "string",
},
},
"type": Object {
"name": "string",
"required": false,
},
},
}
`);
});
});
|
1,828 | 0 | petrpan-code/storybookjs/storybook/code/renderers/svelte/src | petrpan-code/storybookjs/storybook/code/renderers/svelte/src/docs/extractComponentDescription.test.ts | import { describe, expect, test } from '@jest/globals';
import { extractComponentDescription } from './extractComponentDescription';
describe('extractComponentDescription', () => {
test('Extract from docgen', () => {
expect(extractComponentDescription({ __docgen: { description: 'a description' } })).toBe(
'a description'
);
});
test('Null Component', () => {
expect(extractComponentDescription(null)).toBeFalsy();
});
test('Missing docgen', () => {
expect(extractComponentDescription({})).toBeFalsy();
});
});
|
1,830 | 0 | petrpan-code/storybookjs/storybook/code/renderers/svelte/src | petrpan-code/storybookjs/storybook/code/renderers/svelte/src/docs/sourceDecorator.test.ts | import { describe, expect, test } from '@jest/globals';
import type { Args } from '@storybook/types';
import { generateSvelteSource } from './sourceDecorator';
expect.addSnapshotSerializer({
print: (val: any) => val,
test: (val: unknown) => typeof val === 'string',
});
const loremIpsum = 'Lorem ipsum dolor sit amet';
const lotOfProperties = { property1: loremIpsum, property2: loremIpsum, property3: loremIpsum };
function generateForArgs(args: Args, slotProperty: string | null = null) {
return generateSvelteSource({ name: 'Component' }, args, {}, slotProperty);
}
describe('generateSvelteSource', () => {
test('boolean true', () => {
expect(generateForArgs({ bool: true })).toMatchInlineSnapshot(`<Component bool/>`);
});
test('boolean false', () => {
expect(generateForArgs({ bool: false })).toMatchInlineSnapshot(`<Component bool={false}/>`);
});
test('null property', () => {
expect(generateForArgs({ propnull: null })).toMatchInlineSnapshot(`<Component />`);
});
test('string property', () => {
expect(generateForArgs({ str: 'mystr' })).toMatchInlineSnapshot(`<Component str="mystr"/>`);
});
test('number property', () => {
expect(generateForArgs({ count: 42 })).toMatchInlineSnapshot(`<Component count={42}/>`);
});
test('object property', () => {
expect(generateForArgs({ obj: { x: true } })).toMatchInlineSnapshot(
`<Component obj={{"x":true}}/>`
);
});
test('multiple properties', () => {
expect(generateForArgs({ a: 1, b: 2 })).toMatchInlineSnapshot(`<Component a={1} b={2}/>`);
});
test('lot of properties', () => {
expect(generateForArgs(lotOfProperties)).toMatchInlineSnapshot(`
<Component
property1="Lorem ipsum dolor sit amet"
property2="Lorem ipsum dolor sit amet"
property3="Lorem ipsum dolor sit amet"/>
`);
});
test('slot property', () => {
expect(generateForArgs({ content: 'xyz', myProp: 'abc' }, 'content')).toMatchInlineSnapshot(`
<Component myProp="abc">
xyz
</Component>
`);
});
test('slot property with lot of properties', () => {
expect(generateForArgs({ content: 'xyz', ...lotOfProperties }, 'content'))
.toMatchInlineSnapshot(`
<Component
property1="Lorem ipsum dolor sit amet"
property2="Lorem ipsum dolor sit amet"
property3="Lorem ipsum dolor sit amet">
xyz
</Component>
`);
});
test('component is not set', () => {
expect(generateSvelteSource(null, {}, {}, null)).toBeNull();
});
test('Skip event property', () => {
expect(
generateSvelteSource(
{ name: 'Component' },
{ event_click: () => {} },
{ event_click: { action: 'click' } }
)
).toMatchInlineSnapshot(`<Component />`);
});
test('Property value is a function', () => {
expect(
generateSvelteSource({ name: 'Component' }, { myHandler: () => {} }, {})
).toMatchInlineSnapshot(`<Component myHandler={<handler>}/>`);
});
});
|
1,882 | 0 | petrpan-code/storybookjs/storybook/code/renderers/vue | petrpan-code/storybookjs/storybook/code/renderers/vue/src/public-types.test.ts | import { satisfies } from '@storybook/core-common';
import type { ComponentAnnotations, StoryAnnotations } from '@storybook/types';
import { expectTypeOf } from 'expect-type';
import type { SetOptional } from 'type-fest';
import type { Component } from 'vue';
import type { ExtendedVue } from 'vue/types/vue';
import { Vue } from 'vue/types/vue';
import type { Decorator, Meta, StoryObj } from './public-types';
import Button from './__tests__/Button.vue';
import type { VueRenderer } from './types';
describe('Meta', () => {
test('Generic parameter of Meta can be a component', () => {
const meta: Meta<typeof Button> = {
component: Button,
args: { label: 'good', disabled: false },
};
expectTypeOf(meta).toEqualTypeOf<
ComponentAnnotations<
VueRenderer,
{
disabled: boolean;
label: string;
}
>
>();
});
test('Generic parameter of Meta can be the props of the component', () => {
const meta: Meta<{ disabled: boolean; label: string }> = {
component: Button,
args: { label: 'good', disabled: false },
};
expectTypeOf(meta).toEqualTypeOf<
ComponentAnnotations<VueRenderer, { disabled: boolean; label: string }>
>();
});
});
describe('StoryObj', () => {
type ButtonProps = {
disabled: boolean;
label: string;
};
test('✅ Required args may be provided partial in meta and the story', () => {
const meta = satisfies<Meta<typeof Button>>()({
component: Button,
args: { label: 'good' },
});
type Actual = StoryObj<typeof meta>;
type Expected = StoryAnnotations<VueRenderer, ButtonProps, SetOptional<ButtonProps, 'label'>>;
expectTypeOf<Actual>().toEqualTypeOf<Expected>();
});
test('❌ The combined shape of meta args and story args must match the required args.', () => {
{
const meta = satisfies<Meta<typeof Button>>()({ component: Button });
type Expected = StoryAnnotations<VueRenderer, ButtonProps, ButtonProps>;
expectTypeOf<StoryObj<typeof meta>>().toEqualTypeOf<Expected>();
}
{
const meta = satisfies<Meta<typeof Button>>()({
component: Button,
args: { label: 'good' },
});
// @ts-expect-error disabled not provided ❌
const Basic: StoryObj<typeof meta> = {};
type Expected = StoryAnnotations<VueRenderer, ButtonProps, SetOptional<ButtonProps, 'label'>>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
}
{
const meta = satisfies<Meta<{ label: string; disabled: boolean }>>()({ component: Button });
const Basic: StoryObj<typeof meta> = {
// @ts-expect-error disabled not provided ❌
args: { label: 'good' },
};
type Expected = StoryAnnotations<VueRenderer, ButtonProps, ButtonProps>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
}
});
test('Component can be used as generic parameter for StoryObj', () => {
expectTypeOf<StoryObj<typeof Button>>().toEqualTypeOf<
StoryAnnotations<VueRenderer, ButtonProps>
>();
});
});
type ThemeData = 'light' | 'dark';
type ComponentProps<C> = C extends ExtendedVue<any, any, any, any, infer P>
? P
: C extends Component<infer P>
? P
: unknown;
describe('Story args can be inferred', () => {
test('Correct args are inferred when type is widened for render function', () => {
type Props = ComponentProps<typeof Button> & { theme: ThemeData };
const meta = satisfies<Meta<Props>>()({
component: Button,
args: { disabled: false },
render: (args) =>
Vue.extend({
components: { Button },
template: `<div>Using the theme: ${args.theme}<Button v-bind="$props"/></div>`,
props: Object.keys(args),
}),
});
const Basic: StoryObj<typeof meta> = { args: { theme: 'light', label: 'good' } };
type Expected = StoryAnnotations<VueRenderer, Props, SetOptional<Props, 'disabled'>>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
const withDecorator: Decorator<{ decoratorArg: string }> = (
storyFn,
{ args: { decoratorArg } }
) =>
Vue.extend({
components: { Story: storyFn() },
template: `<div>Decorator: ${decoratorArg}<Story/></div>`,
});
test('Correct args are inferred when type is widened for decorators', () => {
type Props = ComponentProps<typeof Button> & { decoratorArg: string };
const meta = satisfies<Meta<Props>>()({
component: Button,
args: { disabled: false },
decorators: [withDecorator],
});
const Basic: StoryObj<typeof meta> = { args: { decoratorArg: 'title', label: 'good' } };
type Expected = StoryAnnotations<VueRenderer, Props, SetOptional<Props, 'disabled'>>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
test('Correct args are inferred when type is widened for multiple decorators', () => {
type Props = ComponentProps<typeof Button> & { decoratorArg: string; decoratorArg2: string };
const secondDecorator: Decorator<{ decoratorArg2: string }> = (
storyFn,
{ args: { decoratorArg2 } }
) => {
return Vue.extend({
components: { Story: storyFn() },
template: `<div>Decorator: ${decoratorArg2}<Story/></div>`,
});
};
const meta = satisfies<Meta<Props>>()({
component: Button,
args: { disabled: false },
decorators: [withDecorator, secondDecorator],
});
const Basic: StoryObj<typeof meta> = {
args: { decoratorArg: '', decoratorArg2: '', label: 'good' },
};
type Expected = StoryAnnotations<VueRenderer, Props, SetOptional<Props, 'disabled'>>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
});
|
1,890 | 0 | petrpan-code/storybookjs/storybook/code/renderers/vue/src | petrpan-code/storybookjs/storybook/code/renderers/vue/src/docs/sourceDecorator.test.ts | /* eslint no-underscore-dangle: ["error", { "allow": ["_vnode"] }] */
import type { ComponentOptions, VueConstructor } from 'vue';
import Vue from 'vue/dist/vue';
import { vnodeToString } from './sourceDecorator';
expect.addSnapshotSerializer({
print: (val: any) => val,
test: (val) => typeof val === 'string',
});
const getVNode = (Component: ComponentOptions<any, any, any>) => {
const vm = new (Vue as unknown as VueConstructor)({
render(h) {
return h(Component);
},
}).$mount();
// @ts-expect-error TS says it is called $vnode
return vm.$children[0]._vnode;
};
describe('vnodeToString', () => {
it('basic', () => {
expect(
vnodeToString(
getVNode({
template: `<button>Button</button>`,
})
)
).toMatchInlineSnapshot(`<button >Button</button>`);
});
it('static class', () => {
expect(
vnodeToString(
getVNode({
template: `<button class="foo bar">Button</button>`,
})
)
).toMatchInlineSnapshot(`<button class="foo bar">Button</button>`);
});
it('string dynamic class', () => {
expect(
vnodeToString(
getVNode({
template: `<button :class="'foo'">Button</button>`,
})
)
).toMatchInlineSnapshot(`<button class="foo">Button</button>`);
});
it('non-string dynamic class', () => {
expect(
vnodeToString(
getVNode({
template: `<button :class="1">Button</button>`,
})
)
).toMatchInlineSnapshot(`<button >Button</button>`);
});
it('array dynamic class', () => {
expect(
vnodeToString(
getVNode({
template: `<button :class="['foo', null, false, 0, {bar: true, baz: false}]">Button</button>`,
})
)
).toMatchInlineSnapshot(`<button class="foo bar">Button</button>`);
});
it('object dynamic class', () => {
expect(
vnodeToString(
getVNode({
template: `<button :class="{foo: true, bar: false}">Button</button>`,
})
)
).toMatchInlineSnapshot(`<button class="foo">Button</button>`);
});
it('merge dynamic and static classes', () => {
expect(
vnodeToString(
getVNode({
template: `<button class="foo" :class="{bar: null, baz: 1}">Button</button>`,
})
)
).toMatchInlineSnapshot(`<button class="foo baz">Button</button>`);
});
it('attributes', () => {
const MyComponent: ComponentOptions<any, any, any> = {
props: ['propA', 'propB', 'propC', 'propD', 'propE', 'propF', 'propG'],
template: '<div/>',
};
expect(
vnodeToString(
getVNode({
components: { MyComponent },
data(): { props: Record<string, any> } {
return {
props: {
propA: 'propA',
propB: 1,
propC: null,
propD: {
foo: 'bar',
},
propE: true,
propF() {
const foo = 'bar';
return foo;
},
propG: undefined,
},
};
},
template: `<my-component v-bind="props"/>`,
})
)
).toMatchInlineSnapshot(
`<my-component propE :propD='{"foo":"bar"}' :propC="null" :propB="1" propA="propA"/>`
);
});
it('children', () => {
expect(
vnodeToString(
getVNode({
template: `
<div>
<form>
<button>Button</button>
</form>
</div>`,
})
)
).toMatchInlineSnapshot(`<div ><form ><button >Button</button></form></div>`);
});
it('empty tag', () => {
expect(
vnodeToString(
getVNode({
template: `
<div>
</div>`,
})
)
).toMatchInlineSnapshot(`<div />`);
});
it('tag in text', () => {
expect(
vnodeToString(
getVNode({
template: `
<div>
<>
</div>`,
})
)
).toMatchInlineSnapshot(`
<div >{{\`
<>
\`}}</div>
`);
});
it('component element with children', () => {
const MyComponent: ComponentOptions<any, any, any> = {
props: ['propA'],
template: '<div><slot /></div>',
};
expect(
vnodeToString(
getVNode({
components: { MyComponent },
data(): { props: Record<string, any> } {
return {
props: {
propA: 'propA',
},
};
},
template: `<my-component v-bind="props"><div /></my-component>`,
})
)
).toMatchInlineSnapshot(`<my-component propA="propA"><div /></my-component>`);
});
});
|
1,921 | 0 | petrpan-code/storybookjs/storybook/code/renderers/vue3 | petrpan-code/storybookjs/storybook/code/renderers/vue3/src/public-types.test.ts | import { satisfies } from '@storybook/core-common';
import type { ComponentAnnotations, StoryAnnotations } from '@storybook/types';
import { expectTypeOf } from 'expect-type';
import type { SetOptional } from 'type-fest';
import { h } from 'vue';
import type { ComponentPropsAndSlots, Decorator, Meta, StoryObj } from './public-types';
import type { VueRenderer } from './types';
import BaseLayout from './__tests__/BaseLayout.vue';
import Button from './__tests__/Button.vue';
import DecoratorTsVue from './__tests__/Decorator.vue';
import Decorator2TsVue from './__tests__/Decorator2.vue';
type ButtonProps = ComponentPropsAndSlots<typeof Button>;
describe('Meta', () => {
test('Generic parameter of Meta can be a component', () => {
const meta: Meta<typeof Button> = {
component: Button,
args: { label: 'good', disabled: false },
};
expectTypeOf(meta).toEqualTypeOf<ComponentAnnotations<VueRenderer, ButtonProps>>();
});
test('Generic parameter of Meta can be the props of the component', () => {
const meta: Meta<{ disabled: boolean; label: string }> = {
component: Button,
args: { label: 'good', disabled: false },
};
expectTypeOf(meta).toEqualTypeOf<
ComponentAnnotations<VueRenderer, { disabled: boolean; label: string }>
>();
});
test('Events are inferred from component', () => {
const meta: Meta<typeof Button> = {
component: Button,
args: {
label: 'good',
disabled: false,
onMyChangeEvent: (value) => {
expectTypeOf(value).toEqualTypeOf<number>();
},
},
render: (args) => {
return h(Button, {
...args,
onMyChangeEvent: (value) => {
expectTypeOf(value).toEqualTypeOf<number>();
},
});
},
};
expectTypeOf(meta).toMatchTypeOf<Meta<typeof Button>>();
});
});
describe('StoryObj', () => {
test('✅ Required args may be provided partial in meta and the story', () => {
const meta = satisfies<Meta<typeof Button>>()({
component: Button,
args: { label: 'good' },
});
type Actual = StoryObj<typeof meta>;
type Expected = StoryAnnotations<VueRenderer, ButtonProps, SetOptional<ButtonProps, 'label'>>;
expectTypeOf<Actual>().toEqualTypeOf<Expected>();
});
test('❌ The combined shape of meta args and story args must match the required args.', () => {
{
const meta = satisfies<Meta<typeof Button>>()({ component: Button });
type Expected = StoryAnnotations<VueRenderer, ButtonProps, ButtonProps>;
expectTypeOf<StoryObj<typeof meta>>().toEqualTypeOf<Expected>();
}
{
const meta = satisfies<Meta<typeof Button>>()({
component: Button,
args: { label: 'good' },
});
// @ts-expect-error disabled not provided ❌
const Basic: StoryObj<typeof meta> = {};
type Expected = StoryAnnotations<VueRenderer, ButtonProps, SetOptional<ButtonProps, 'label'>>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
}
{
const meta = satisfies<Meta<{ label: string; disabled: boolean }>>()({ component: Button });
const Basic: StoryObj<typeof meta> = {
// @ts-expect-error disabled not provided ❌
args: { label: 'good' },
};
type Expected = StoryAnnotations<VueRenderer, ButtonProps, ButtonProps>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
}
});
test('Component can be used as generic parameter for StoryObj', () => {
expectTypeOf<StoryObj<typeof Button>>().toEqualTypeOf<
StoryAnnotations<VueRenderer, ButtonProps>
>();
});
});
type ThemeData = 'light' | 'dark';
describe('Story args can be inferred', () => {
test('Correct args are inferred when type is widened for render function', () => {
type Props = ButtonProps & { theme: ThemeData };
const meta = satisfies<Meta<Props>>()({
component: Button,
args: { disabled: false },
render: (args) => {
return h('div', [h('div', `Use the theme ${args.theme}`), h(Button, args)]);
},
});
const Basic: StoryObj<typeof meta> = { args: { theme: 'light', label: 'good' } };
type Expected = StoryAnnotations<VueRenderer, Props, SetOptional<Props, 'disabled'>>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
const withDecorator: Decorator<{ decoratorArg: string }> = (
storyFn,
{ args: { decoratorArg } }
) => h(DecoratorTsVue, { decoratorArg }, h(storyFn()));
test('Correct args are inferred when type is widened for decorators', () => {
type Props = ButtonProps & { decoratorArg: string };
const meta = satisfies<Meta<Props>>()({
component: Button,
args: { disabled: false },
decorators: [withDecorator],
});
const Basic: StoryObj<typeof meta> = { args: { decoratorArg: 'title', label: 'good' } };
type Expected = StoryAnnotations<VueRenderer, Props, SetOptional<Props, 'disabled'>>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
test('Correct args are inferred when type is widened for multiple decorators', () => {
type Props = ButtonProps & {
decoratorArg: string;
decoratorArg2: string;
};
const secondDecorator: Decorator<{ decoratorArg2: string }> = (
storyFn,
{ args: { decoratorArg2 } }
) => h(Decorator2TsVue, { decoratorArg2 }, h(storyFn()));
const meta = satisfies<Meta<Props>>()({
component: Button,
args: { disabled: false },
decorators: [withDecorator, secondDecorator],
});
const Basic: StoryObj<typeof meta> = {
args: { decoratorArg: '', decoratorArg2: '', label: 'good' },
};
type Expected = StoryAnnotations<VueRenderer, Props, SetOptional<Props, 'disabled'>>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
});
test('Infer type of slots', () => {
const meta = {
component: BaseLayout,
} satisfies Meta<typeof BaseLayout>;
const Basic: StoryObj<typeof meta> = {
args: {
otherProp: true,
header: ({ title }) =>
h({
components: { Button },
template: `<Button :primary='true' label='${title}'></Button>`,
}),
default: 'default slot',
footer: h(Button, { disabled: true, label: 'footer' }),
},
};
type Props = ComponentPropsAndSlots<typeof BaseLayout>;
type Expected = StoryAnnotations<VueRenderer, Props, Props>;
expectTypeOf(Basic).toEqualTypeOf<Expected>();
});
|
1,923 | 0 | petrpan-code/storybookjs/storybook/code/renderers/vue3 | petrpan-code/storybookjs/storybook/code/renderers/vue3/src/render.test.ts | import { expectTypeOf } from 'expect-type';
import { reactive } from 'vue';
import { updateArgs } from './render';
describe('Render Story', () => {
test('update reactive Args updateArgs()', () => {
const reactiveArgs = reactive({ argFoo: 'foo', argBar: 'bar' }); // get reference to reactiveArgs or create a new one;
expectTypeOf(reactiveArgs).toMatchTypeOf<Record<string, any>>();
expectTypeOf(reactiveArgs).toEqualTypeOf<{ argFoo: string; argBar: string }>();
const newArgs = { argFoo: 'foo2', argBar: 'bar2' };
updateArgs(reactiveArgs, newArgs);
expectTypeOf(reactiveArgs).toEqualTypeOf<{ argFoo: string; argBar: string }>();
expect(reactiveArgs).toEqual({ argFoo: 'foo2', argBar: 'bar2' });
});
test('update reactive Args component inherit objectArg updateArgs()', () => {
const reactiveArgs = reactive({ objectArg: { argFoo: 'foo', argBar: 'bar' } }); // get reference to reactiveArgs or create a new one;
expectTypeOf(reactiveArgs).toMatchTypeOf<Record<string, any>>();
expectTypeOf(reactiveArgs).toEqualTypeOf<{ objectArg: { argFoo: string; argBar: string } }>();
const newArgs = { argFoo: 'foo2', argBar: 'bar2' };
updateArgs(reactiveArgs, newArgs);
expectTypeOf(reactiveArgs).toEqualTypeOf<{ objectArg: { argFoo: string; argBar: string } }>();
expect(reactiveArgs).toEqual({
argFoo: 'foo2',
argBar: 'bar2',
});
});
test('update reactive Args component inherit objectArg', () => {
const reactiveArgs = reactive({ objectArg: { argFoo: 'foo' } }); // get reference to reactiveArgs or create a new one;
expectTypeOf(reactiveArgs).toMatchTypeOf<Record<string, any>>();
expectTypeOf(reactiveArgs).toEqualTypeOf<{ objectArg: { argFoo: string } }>();
const newArgs = { argFoo: 'foo2', argBar: 'bar2' };
updateArgs(reactiveArgs, newArgs);
expect(reactiveArgs).toEqual({ argFoo: 'foo2', argBar: 'bar2' });
});
test('update reactive Args component 2 object args -> updateArgs()', () => {
const reactiveArgs = reactive({
objectArg: { argFoo: 'foo' },
objectArg2: { argBar: 'bar' },
}); // get reference to reactiveArgs or create a new one;
expectTypeOf(reactiveArgs).toMatchTypeOf<Record<string, any>>();
expectTypeOf(reactiveArgs).toEqualTypeOf<{
objectArg: { argFoo: string };
objectArg2: { argBar: string };
}>();
const newArgs = { argFoo: 'foo2', argBar: 'bar2' };
updateArgs(reactiveArgs, newArgs);
expect(reactiveArgs).toEqual({
argFoo: 'foo2',
argBar: 'bar2',
});
});
test('update reactive Args component object with object -> updateArgs()', () => {
const reactiveArgs = reactive({
objectArg: { argFoo: 'foo' },
}); // get reference to reactiveArgs or create a new one;
expectTypeOf(reactiveArgs).toMatchTypeOf<Record<string, any>>();
expectTypeOf(reactiveArgs).toEqualTypeOf<{
objectArg: { argFoo: string };
}>();
const newArgs = { objectArg: { argFoo: 'bar' } };
updateArgs(reactiveArgs, newArgs);
expect(reactiveArgs).toEqual({ objectArg: { argFoo: 'bar' } });
});
test('update reactive Args component no arg with all args -> updateArgs()', () => {
const reactiveArgs = reactive({ objectArg: { argFoo: 'foo' } }); // get reference to reactiveArgs or create a new one;
expectTypeOf(reactiveArgs).toMatchTypeOf<Record<string, any>>();
expectTypeOf(reactiveArgs).toEqualTypeOf<{
objectArg: { argFoo: string };
}>();
const newArgs = { objectArg: { argFoo: 'bar' } };
updateArgs(reactiveArgs, newArgs);
expect(reactiveArgs).toEqual({ objectArg: { argFoo: 'bar' } });
});
});
|
1,932 | 0 | petrpan-code/storybookjs/storybook/code/renderers/vue3/src | petrpan-code/storybookjs/storybook/code/renderers/vue3/src/docs/sourceDecorator.test.ts | import { describe, expect, test } from '@jest/globals';
import {
mapAttributesAndDirectives,
generateAttributesSource,
attributeSource,
htmlEventAttributeToVueEventAttribute as htmlEventToVueEvent,
} from './sourceDecorator';
expect.addSnapshotSerializer({
print: (val: any) => val,
test: (val: unknown) => typeof val === 'string',
});
describe('Vue3: sourceDecorator->mapAttributesAndDirective()', () => {
test('camelCase boolean Arg', () => {
expect(mapAttributesAndDirectives({ camelCaseBooleanArg: true })).toMatchInlineSnapshot(`
Array [
Object {
arg: Object {
content: camel-case-boolean-arg,
loc: Object {
source: camel-case-boolean-arg,
},
},
exp: Object {
isStatic: false,
loc: Object {
source: true,
},
},
loc: Object {
source: :camel-case-boolean-arg="true",
},
modifiers: Array [
,
],
name: bind,
type: 6,
},
]
`);
});
test('camelCase string Arg', () => {
expect(mapAttributesAndDirectives({ camelCaseStringArg: 'foo' })).toMatchInlineSnapshot(`
Array [
Object {
arg: Object {
content: camel-case-string-arg,
loc: Object {
source: camel-case-string-arg,
},
},
exp: Object {
isStatic: false,
loc: Object {
source: foo,
},
},
loc: Object {
source: camel-case-string-arg="foo",
},
modifiers: Array [
,
],
name: bind,
type: 6,
},
]
`);
});
test('boolean arg', () => {
expect(mapAttributesAndDirectives({ booleanarg: true })).toMatchInlineSnapshot(`
Array [
Object {
arg: Object {
content: booleanarg,
loc: Object {
source: booleanarg,
},
},
exp: Object {
isStatic: false,
loc: Object {
source: true,
},
},
loc: Object {
source: :booleanarg="true",
},
modifiers: Array [
,
],
name: bind,
type: 6,
},
]
`);
});
test('string arg', () => {
expect(mapAttributesAndDirectives({ stringarg: 'bar' })).toMatchInlineSnapshot(`
Array [
Object {
arg: Object {
content: stringarg,
loc: Object {
source: stringarg,
},
},
exp: Object {
isStatic: false,
loc: Object {
source: bar,
},
},
loc: Object {
source: stringarg="bar",
},
modifiers: Array [
,
],
name: bind,
type: 6,
},
]
`);
});
test('number arg', () => {
expect(mapAttributesAndDirectives({ numberarg: 2023 })).toMatchInlineSnapshot(`
Array [
Object {
arg: Object {
content: numberarg,
loc: Object {
source: numberarg,
},
},
exp: Object {
isStatic: false,
loc: Object {
source: 2023,
},
},
loc: Object {
source: :numberarg="2023",
},
modifiers: Array [
,
],
name: bind,
type: 6,
},
]
`);
});
test('camelCase boolean, string, and number Args', () => {
expect(
mapAttributesAndDirectives({
camelCaseBooleanArg: true,
camelCaseStringArg: 'foo',
cameCaseNumberArg: 2023,
})
).toMatchInlineSnapshot(`
Array [
Object {
arg: Object {
content: camel-case-boolean-arg,
loc: Object {
source: camel-case-boolean-arg,
},
},
exp: Object {
isStatic: false,
loc: Object {
source: true,
},
},
loc: Object {
source: :camel-case-boolean-arg="true",
},
modifiers: Array [
,
],
name: bind,
type: 6,
},
Object {
arg: Object {
content: camel-case-string-arg,
loc: Object {
source: camel-case-string-arg,
},
},
exp: Object {
isStatic: false,
loc: Object {
source: foo,
},
},
loc: Object {
source: camel-case-string-arg="foo",
},
modifiers: Array [
,
],
name: bind,
type: 6,
},
Object {
arg: Object {
content: came-case-number-arg,
loc: Object {
source: came-case-number-arg,
},
},
exp: Object {
isStatic: false,
loc: Object {
source: 2023,
},
},
loc: Object {
source: :came-case-number-arg="2023",
},
modifiers: Array [
,
],
name: bind,
type: 6,
},
]
`);
});
});
describe('Vue3: sourceDecorator->generateAttributesSource()', () => {
test('camelCase boolean Arg', () => {
expect(
generateAttributesSource(
mapAttributesAndDirectives({ camelCaseBooleanArg: true }),
{ camelCaseBooleanArg: true },
[{ camelCaseBooleanArg: { type: 'boolean' } }] as any
)
).toMatchInlineSnapshot(`:camel-case-boolean-arg="true"`);
});
test('camelCase string Arg', () => {
expect(
generateAttributesSource(
mapAttributesAndDirectives({ camelCaseStringArg: 'foo' }),
{ camelCaseStringArg: 'foo' },
[{ camelCaseStringArg: { type: 'string' } }] as any
)
).toMatchInlineSnapshot(`camel-case-string-arg="foo"`);
});
test('camelCase boolean, string, and number Args', () => {
expect(
generateAttributesSource(
mapAttributesAndDirectives({
camelCaseBooleanArg: true,
camelCaseStringArg: 'foo',
cameCaseNumberArg: 2023,
}),
{
camelCaseBooleanArg: true,
camelCaseStringArg: 'foo',
cameCaseNumberArg: 2023,
},
[] as any
)
).toMatchInlineSnapshot(
`:camel-case-boolean-arg="true" camel-case-string-arg="foo" :came-case-number-arg="2023"`
);
});
});
describe('Vue3: sourceDecorator->attributeSoure()', () => {
test('camelCase boolean Arg', () => {
expect(attributeSource('stringArg', 'foo')).toMatchInlineSnapshot(`stringArg="foo"`);
});
test('html event attribute should convert to vue event directive', () => {
expect(attributeSource('onClick', () => {})).toMatchInlineSnapshot(`v-on:click='()=>({})'`);
expect(attributeSource('onclick', () => {})).toMatchInlineSnapshot(`v-on:click='()=>({})'`);
});
test('normal html attribute should not convert to vue event directive', () => {
expect(attributeSource('on-click', () => {})).toMatchInlineSnapshot(`on-click='()=>({})'`);
});
test('htmlEventAttributeToVueEventAttribute onEv => v-on:', () => {
const htmlEventAttributeToVueEventAttribute = (attribute: string) => {
return htmlEventToVueEvent(attribute);
};
expect(/^on[A-Za-z]/.test('onClick')).toBeTruthy();
expect(htmlEventAttributeToVueEventAttribute('onclick')).toMatchInlineSnapshot(`v-on:click`);
expect(htmlEventAttributeToVueEventAttribute('onClick')).toMatchInlineSnapshot(`v-on:click`);
expect(htmlEventAttributeToVueEventAttribute('onChange')).toMatchInlineSnapshot(`v-on:change`);
expect(htmlEventAttributeToVueEventAttribute('onFocus')).toMatchInlineSnapshot(`v-on:focus`);
expect(htmlEventAttributeToVueEventAttribute('on-focus')).toMatchInlineSnapshot(`on-focus`);
});
});
|
1,997 | 0 | petrpan-code/storybookjs/storybook/code/renderers/web-components/src | petrpan-code/storybookjs/storybook/code/renderers/web-components/src/docs/custom-elements.test.ts | /* eslint-disable no-underscore-dangle */
import { global } from '@storybook/global';
import { extractArgTypes } from './custom-elements';
import customElementsManifest from './__testfixtures__/custom-elements.json';
const { window } = global;
describe('extractArgTypes', () => {
beforeEach(() => {
window.__STORYBOOK_CUSTOM_ELEMENTS_MANIFEST__ = customElementsManifest;
});
afterEach(() => {
window.__STORYBOOK_CUSTOM_ELEMENTS_MANIFEST__ = undefined;
});
describe('events', () => {
it('should map to an action event handler', () => {
const extractedArgType = extractArgTypes('sb-header');
expect(extractedArgType?.onSbHeaderCreateAccount).toEqual({
name: 'onSbHeaderCreateAccount',
action: { name: 'sb-header:createAccount' },
table: { disable: true },
});
});
it('should map to a regular item', () => {
const extractedArgType = extractArgTypes('sb-header');
expect(extractedArgType?.['sb-header:createAccount']).toEqual({
name: 'sb-header:createAccount',
required: false,
description: 'Event send when user clicks on create account button',
type: { name: 'void' },
table: {
category: 'events',
type: { summary: 'CustomEvent' },
defaultValue: { summary: undefined },
},
});
});
});
});
|
1,999 | 0 | petrpan-code/storybookjs/storybook/code/renderers/web-components/src | petrpan-code/storybookjs/storybook/code/renderers/web-components/src/docs/sourceDecorator.test.ts | import { html, render } from 'lit';
import { styleMap } from 'lit/directives/style-map.js';
import { addons, useEffect } from '@storybook/preview-api';
import { SNIPPET_RENDERED } from '@storybook/docs-tools';
import type { StoryContext } from '../types';
import { sourceDecorator } from './sourceDecorator';
jest.mock('@storybook/preview-api');
const mockedAddons = addons as jest.Mocked<typeof addons>;
const mockedUseEffect = useEffect as jest.Mock;
expect.addSnapshotSerializer({
print: (val: any) => val,
test: (val) => typeof val === 'string',
});
const tick = () => new Promise((r) => setTimeout(r, 0));
const makeContext = (name: string, parameters: any, args: any, extra?: Partial<StoryContext>) =>
({
id: `lit-test--${name}`,
kind: 'js-text',
name,
parameters,
unmappedArgs: args,
args,
argTypes: {},
globals: {},
...extra,
} as StoryContext);
describe('sourceDecorator', () => {
let mockChannel: { on: jest.Mock; emit?: jest.Mock };
beforeEach(() => {
mockedAddons.getChannel.mockReset();
mockedUseEffect.mockImplementation((cb) => setTimeout(() => cb(), 0));
mockChannel = { on: jest.fn(), emit: jest.fn() };
mockedAddons.getChannel.mockReturnValue(mockChannel as any);
});
it('should render dynamically for args stories', async () => {
const storyFn = (args: any) => html`<div>args story</div>`;
const context = makeContext('args', { __isArgsStory: true }, {});
sourceDecorator(storyFn, context);
await tick();
expect(mockChannel.emit).toHaveBeenCalledWith(SNIPPET_RENDERED, {
id: 'lit-test--args',
args: {},
source: '<div>args story</div>',
});
});
it('should skip dynamic rendering for no-args stories', async () => {
const storyFn = () => html`<div>classic story</div>`;
const context = makeContext('classic', {}, {});
sourceDecorator(storyFn, context);
await tick();
expect(mockChannel.emit).not.toHaveBeenCalled();
});
it('should use the originalStoryFn if excludeDecorators is set', async () => {
const storyFn = (args: any) => html`<div>args story</div>`;
const decoratedStoryFn = (args: any) => html`
<div style=${styleMap({ padding: `${25}px`, border: '3px solid red' })}>${storyFn(args)}</div>
`;
const context = makeContext(
'args',
{
__isArgsStory: true,
docs: {
source: {
excludeDecorators: true,
},
},
},
{},
{ originalStoryFn: storyFn }
);
sourceDecorator(decoratedStoryFn, context);
await tick();
expect(mockChannel.emit).toHaveBeenCalledWith(SNIPPET_RENDERED, {
id: 'lit-test--args',
args: {},
source: '<div>args story</div>',
});
});
it('should handle document fragment without removing its child nodes', async () => {
const storyFn = () =>
html`my
<div>args story</div>`;
const decoratedStoryFn = () => {
const fragment = document.createDocumentFragment();
render(storyFn(), fragment);
return fragment;
};
const context = makeContext('args', { __isArgsStory: true }, {});
const story = sourceDecorator(decoratedStoryFn, context);
await tick();
expect(mockChannel.emit).toHaveBeenCalledWith(SNIPPET_RENDERED, {
id: 'lit-test--args',
args: {},
source: `my
<div>args story</div>`,
});
expect(story).toMatchInlineSnapshot(`
<DocumentFragment>
<!---->
my
<div>
args story
</div>
</DocumentFragment>
`);
});
});
|
2,001 | 0 | petrpan-code/storybookjs/storybook/code/renderers/web-components/src | petrpan-code/storybookjs/storybook/code/renderers/web-components/src/docs/web-components-properties.test.ts | import 'jest-specific-snapshot';
import path from 'path';
import fs from 'fs';
import tmp from 'tmp';
import { sync as spawnSync } from 'cross-spawn';
// File hierarchy:
// __testfixtures__ / some-test-case / input.*
const inputRegExp = /^input\..*$/;
const runWebComponentsAnalyzer = (inputPath: string) => {
const { name: tmpDir, removeCallback } = tmp.dirSync();
const customElementsFile = `${tmpDir}/custom-elements.json`;
spawnSync(
path.join(__dirname, '../../../../node_modules/.bin/wca'),
['analyze', inputPath, '--outFile', customElementsFile],
{
stdio: 'ignore',
shell: true,
}
);
const output = fs.readFileSync(customElementsFile, 'utf8');
try {
removeCallback();
} catch (e) {
//
}
return output;
};
describe('web-components component properties', () => {
// we need to mock lit and dynamically require custom-elements
// because lit is distributed as ESM not CJS
// https://github.com/Polymer/lit-html/issues/516
jest.mock('lit', () => {});
jest.mock('lit/directive-helpers.js', () => {});
// eslint-disable-next-line global-require
const { extractArgTypesFromElements } = require('./custom-elements');
const fixturesDir = path.join(__dirname, '__testfixtures__');
fs.readdirSync(fixturesDir, { withFileTypes: true }).forEach((testEntry) => {
if (testEntry.isDirectory()) {
const testDir = path.join(fixturesDir, testEntry.name);
const testFile = fs.readdirSync(testDir).find((fileName) => inputRegExp.test(fileName));
if (testFile) {
it(`${testEntry.name}`, () => {
const inputPath = path.join(testDir, testFile);
// snapshot the output of wca
const customElementsJson = runWebComponentsAnalyzer(inputPath);
const customElements = JSON.parse(customElementsJson);
customElements.tags.forEach((tag: any) => {
// eslint-disable-next-line no-param-reassign
tag.path = 'dummy-path-to-component';
});
expect(customElements).toMatchSpecificSnapshot(
path.join(testDir, 'custom-elements.snapshot')
);
// snapshot the properties
const properties = extractArgTypesFromElements('input', customElements);
expect(properties).toMatchSpecificSnapshot(path.join(testDir, 'properties.snapshot'));
});
}
}
});
});
|
2,068 | 0 | petrpan-code/storybookjs/storybook/code/ui/blocks/src | petrpan-code/storybookjs/storybook/code/ui/blocks/src/blocks/DocsPage.test.ts | import { extractTitle } from './Title';
describe('defaultTitleSlot', () => {
it('splits on last /', () => {
expect(extractTitle('a/b/c')).toBe('c');
expect(extractTitle('a|b')).toBe('a|b');
expect(extractTitle('a/b/c.d')).toBe('c.d');
});
});
|
2,153 | 0 | petrpan-code/storybookjs/storybook/code/ui/blocks/src | petrpan-code/storybookjs/storybook/code/ui/blocks/src/controls/Date.test.ts | import { parseDate, parseTime, formatDate, formatTime } from './Date';
describe('Date control', () => {
it.each([
// name, input, expected
['same date', '2022-01-01', '2022-01-01'],
['month and day not padded with zeros', '2022-1-1', '2022-01-01'],
['different year', '1900-10-1', '1900-10-01'],
])('parse and format date: %s', (name, input, expected) => {
expect(formatDate(parseDate(input))).toBe(expected);
});
it.each([
// name, input, expected
['same time', '12:00', '12:00'],
['hours not padded with a zero', '1:00', '01:00'],
['minutes not padded with a zero', '01:0', '01:00'],
['different minutes', '01:30', '01:30'],
])('parse and format time: %s', (name, input, expected) => {
expect(formatTime(parseTime(input))).toBe(expected);
});
});
|
2,165 | 0 | petrpan-code/storybookjs/storybook/code/ui/blocks/src | petrpan-code/storybookjs/storybook/code/ui/blocks/src/controls/helpers.test.ts | import { getControlId, getControlSetterButtonId } from './helpers';
describe('getControlId', () => {
it.each([
// caseName, input, expected
['lower case', 'some-id', 'control-some-id'],
['upper case', 'SOME-ID', 'control-SOME-ID'],
['all valid characters', 'some_weird-:custom.id', 'control-some_weird-:custom.id'],
])('%s', (name, input, expected) => {
expect(getControlId(input)).toBe(expected);
});
});
describe('getControlSetterButtonId', () => {
it.each([
// caseName, input, expected
['lower case', 'some-id', 'set-some-id'],
['upper case', 'SOME-ID', 'set-SOME-ID'],
['all valid characters', 'some_weird-:custom.id', 'set-some_weird-:custom.id'],
])('%s', (name, input, expected) => {
expect(getControlSetterButtonId(input)).toBe(expected);
});
});
|
2,253 | 0 | petrpan-code/storybookjs/storybook/code/ui/components/src/components | petrpan-code/storybookjs/storybook/code/ui/components/src/components/syntaxhighlighter/formatter.test.ts | import { dedent } from 'ts-dedent';
import { formatter } from './formatter';
describe('dedent', () => {
test('handles empty string', () => {
const input = '';
const result = formatter(true, input);
expect(result).toBe(input);
});
test('handles single line', () => {
const input = 'console.log("hello world")';
const result = formatter(true, input);
expect(result).toBe(input);
});
test('does not transform correct code', () => {
const input = dedent`
console.log("hello");
console.log("world");
`;
const result = formatter(true, input);
expect(result).toBe(input);
});
test('does transform incorrect code', () => {
const input = `
console.log("hello");
console.log("world");
`;
const result = formatter(true, input);
expect(result).toBe(`console.log("hello");
console.log("world");`);
});
test('more indentations - skip first line', () => {
const input = `
test('handles empty string', () => {
const input = '';
const result = formatter(input);
expect(result).toBe(input);
});
`;
const result = formatter(true, input);
expect(result).toBe(`test('handles empty string', () => {
const input = '';
const result = formatter(input);
expect(result).toBe(input);
});`);
});
test('more indentations - code on first line', () => {
const input = `// some comment
test('handles empty string', () => {
const input = '';
const result = formatter(input);
expect(result).toBe(input);
});
`;
const result = formatter(true, input);
expect(result).toBe(`// some comment
test('handles empty string', () => {
const input = '';
const result = formatter(input);
expect(result).toBe(input);
});`);
});
test('removes whitespace in empty line completely', () => {
const input = `
console.log("hello");
console.log("world");
`;
const result = formatter(true, input);
expect(result).toBe(`console.log("hello");
console.log("world");`);
});
});
describe('prettier (babel)', () => {
test('handles empty string', () => {
const input = '';
const result = formatter('angular', input);
expect(result).toBe(input);
});
test('handles single line', () => {
const input = 'console.log("hello world")';
const result = formatter('angular', input);
expect(result).toBe(input);
});
});
|
2,307 | 0 | petrpan-code/storybookjs/storybook/code/ui/components/src/components/typography | petrpan-code/storybookjs/storybook/code/ui/components/src/components/typography/link/link.test.tsx | import type { AnchorHTMLAttributes } from 'react';
import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ThemeProvider, themes, convert } from '@storybook/theming';
import type { LinkProps } from './link';
import { Link } from './link';
const LEFT_BUTTON = 0;
const MIDDLE_BUTTON = 1;
const RIGHT_BUTTON = 2;
function ThemedLink(props: LinkProps & AnchorHTMLAttributes<HTMLAnchorElement>) {
return (
<ThemeProvider theme={convert(themes.light)}>
<Link {...props} />
</ThemeProvider>
);
}
describe('Link', () => {
describe('events', () => {
it('should call onClick on a plain left click', () => {
const handleClick = jest.fn();
render(<ThemedLink onClick={handleClick}>Content</ThemedLink>);
userEvent.click(screen.getByText('Content'), { button: LEFT_BUTTON });
expect(handleClick).toHaveBeenCalled();
});
it("shouldn't call onClick on a middle click", () => {
const handleClick = jest.fn();
render(<ThemedLink onClick={handleClick}>Content</ThemedLink>);
userEvent.click(screen.getByText('Content'), { button: MIDDLE_BUTTON });
expect(handleClick).not.toHaveBeenCalled();
});
it("shouldn't call onClick on a right click", () => {
const handleClick = jest.fn();
render(<ThemedLink onClick={handleClick}>Content</ThemedLink>);
userEvent.click(screen.getByText('Content'), { button: RIGHT_BUTTON });
expect(handleClick).not.toHaveBeenCalled();
});
it("shouldn't call onClick on alt+click", () => {
const handleClick = jest.fn();
render(<ThemedLink onClick={handleClick}>Content</ThemedLink>);
userEvent.click(screen.getByText('Content'), { altKey: true });
expect(handleClick).not.toHaveBeenCalled();
});
it("shouldn't call onClick on ctrl+click", () => {
const handleClick = jest.fn();
render(<ThemedLink onClick={handleClick}>Content</ThemedLink>);
userEvent.click(screen.getByText('Content'), { ctrlKey: true });
expect(handleClick).not.toHaveBeenCalled();
});
it("shouldn't call onClick on cmd+click / win+click", () => {
const handleClick = jest.fn();
render(<ThemedLink onClick={handleClick}>Content</ThemedLink>);
userEvent.click(screen.getByText('Content'), { metaKey: true });
expect(handleClick).not.toHaveBeenCalled();
});
it("shouldn't call onClick on shift+click", () => {
const handleClick = jest.fn();
render(<ThemedLink onClick={handleClick}>Content</ThemedLink>);
userEvent.click(screen.getByText('Content'), { shiftKey: true });
expect(handleClick).not.toHaveBeenCalled();
});
});
});
|
2,327 | 0 | petrpan-code/storybookjs/storybook/code/ui/manager/src | petrpan-code/storybookjs/storybook/code/ui/manager/src/__tests__/index.test.ts | import { renderStorybookUI } from '..';
describe('Main API', () => {
it('should fail if provider is not extended from the base Provider', () => {
const run = () => {
const fakeProvider = {};
// @ts-expect-error (Converted from ts-ignore)
renderStorybookUI(null, fakeProvider);
};
expect(run).toThrow(/base Provider/);
});
});
|
2,390 | 0 | petrpan-code/storybookjs/storybook/code/ui/manager/src/components/sidebar | petrpan-code/storybookjs/storybook/code/ui/manager/src/components/sidebar/__tests__/Sidebar.test.tsx | import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { ThemeProvider, ensure, themes } from '@storybook/theming';
import type { HashEntry, Refs } from '@storybook/manager-api';
import type { Theme } from '@storybook/theming';
import type { RenderResult } from '@testing-library/react';
import type { API_IndexHash } from '@storybook/types';
import { Sidebar } from '../Sidebar';
import type { SidebarProps } from '../Sidebar';
const DOCS_NAME = 'Docs';
const factory = (props: Partial<SidebarProps>): RenderResult => {
const theme: Theme = ensure(themes.light);
return render(
<ThemeProvider theme={theme}>
<Sidebar
menu={[]}
index={{}}
previewInitialized
refs={{}}
status={{}}
extra={[]}
{...props}
/>
</ThemeProvider>
);
};
const generateStories = ({ title, refId }: { title: string; refId?: string }): API_IndexHash => {
const [root, componentName]: [string, string] = title.split('/') as any;
const rootId: string = root.toLowerCase().replace(/\s+/g, '-');
const hypenatedComponentName: string = componentName.toLowerCase().replace(/\s+/g, '-');
const componentId = `${rootId}-${hypenatedComponentName}`;
const docsId = `${rootId}-${hypenatedComponentName}--docs`;
const storyBase: HashEntry[] = [
// @ts-expect-error the missing fields are deprecated and replaced by the type prop
{
type: 'root',
id: rootId,
depth: 0,
refId,
name: root,
children: [componentId],
startCollapsed: false,
},
// @ts-expect-error the missing fields are deprecated and replaced by the type prop
{
type: 'component',
id: componentId,
depth: 1,
refId,
name: componentName,
children: [docsId],
parent: rootId,
},
// @ts-expect-error the missing fields are deprecated and replaced by the type prop
{
type: 'docs',
id: docsId,
depth: 2,
refId,
name: DOCS_NAME,
title,
parent: componentId,
importPath: './docs.js',
},
];
return storyBase.reduce((accumulator: API_IndexHash, current: HashEntry): API_IndexHash => {
accumulator[current.id] = current;
return accumulator;
}, {});
};
describe('Sidebar', () => {
test.skip("should not render an extra nested 'Page'", async () => {
const refId = 'next';
const title = 'Getting Started/Install';
const refIndex: API_IndexHash = generateStories({ refId, title });
const internalIndex: API_IndexHash = generateStories({ title: 'Welcome/Example' });
const refs: Refs = {
[refId]: {
index: refIndex,
id: refId,
previewInitialized: true,
title: refId,
url: 'https://ref.url',
},
};
factory({
refs,
refId,
index: internalIndex,
});
fireEvent.click(screen.getByText('Install'));
fireEvent.click(screen.getByText('Example'));
const pageItems: HTMLElement[] = await screen.queryAllByText('Page');
expect(pageItems).toHaveLength(0);
});
});
|
2,415 | 0 | petrpan-code/storybookjs/storybook/code/ui/manager/src | petrpan-code/storybookjs/storybook/code/ui/manager/src/utils/status.test.ts | import { getHighestStatus, getGroupStatus } from './status';
import { mockDataset } from '../components/sidebar/mockdata';
describe('getHighestStatus', () => {
test('default value', () => {
expect(getHighestStatus([])).toBe('unknown');
});
test('should return the highest status', () => {
expect(getHighestStatus(['success', 'error', 'warn', 'pending'])).toBe('error');
expect(getHighestStatus(['error', 'error', 'warn', 'pending'])).toBe('error');
expect(getHighestStatus(['warn', 'pending'])).toBe('warn');
});
});
describe('getGroupStatus', () => {
test('empty case', () => {
expect(getGroupStatus({}, {})).toEqual({});
});
test('should return a color', () => {
expect(
getGroupStatus(mockDataset.withRoot, {
'group-1--child-b1': { a: { status: 'warn', description: '', title: '' } },
})
).toMatchInlineSnapshot(`
Object {
"group-1": "warn",
"root-1-child-a1": "unknown",
"root-1-child-a2": "unknown",
"root-3-child-a2": "unknown",
}
`);
});
test('should return the highest status', () => {
expect(
getGroupStatus(mockDataset.withRoot, {
'group-1--child-b1': {
a: { status: 'warn', description: '', title: '' },
b: { status: 'error', description: '', title: '' },
},
})
).toMatchInlineSnapshot(`
Object {
"group-1": "error",
"root-1-child-a1": "unknown",
"root-1-child-a2": "unknown",
"root-3-child-a2": "unknown",
}
`);
});
});
|
3,679 | 0 | petrpan-code/storybookjs/storybook/docs/snippets | petrpan-code/storybookjs/storybook/docs/snippets/react/multiple-stories-test.ts.mdx | ```ts
// Form.test.ts|tsx
import { fireEvent, render, screen } from '@testing-library/react';
import { composeStories } from '@storybook/react';
import * as FormStories from './LoginForm.stories';
const { InvalidForm, ValidForm } = composeStories(FormStories);
test('Tests invalid form state', () => {
render(<InvalidForm />);
const buttonElement = screen.getByRole('button', {
name: 'Submit',
});
fireEvent.click(buttonElement);
const isFormValid = screen.getByLabelText('invalid-form');
expect(isFormValid).toBeInTheDocument();
});
test('Tests filled form', () => {
render(<ValidForm />);
const buttonElement = screen.getByRole('button', {
name: 'Submit',
});
fireEvent.click(buttonElement);
const isFormValid = screen.getByLabelText('invalid-form');
expect(isFormValid).not.toBeInTheDocument();
});
```
|
3,708 | 0 | petrpan-code/storybookjs/storybook/docs/snippets | petrpan-code/storybookjs/storybook/docs/snippets/react/reuse-args-test.ts.mdx | ```ts
// Button.test.ts|tsx
import { render, screen } from '@testing-library/react';
import { composeStories } from '@storybook/react';
import * as stories from './Button.stories';
const { Primary } = composeStories(stories);
test('reuses args from composed story', () => {
render(<Primary />);
const buttonElement = screen.getByRole('button');
// Testing against values coming from the story itself! No need for duplication
expect(buttonElement.textContent).toEqual(Primary.args.label);
});
```
|
3,712 | 0 | petrpan-code/storybookjs/storybook/docs/snippets | petrpan-code/storybookjs/storybook/docs/snippets/react/single-story-test.ts.mdx | ```ts
// Form.test.ts|tsx
import { fireEvent, render, screen } from '@testing-library/react';
import { composeStory } from '@storybook/react';
import Meta, { ValidForm as ValidFormStory } from './LoginForm.stories';
const FormOK = composeStory(ValidFormStory, Meta);
test('Validates form', () => {
render(<FormOK />);
const buttonElement = screen.getByRole('button', {
name: 'Submit',
});
fireEvent.click(buttonElement);
const isFormValid = screen.getByLabelText('invalid-form');
expect(isFormValid).not.toBeInTheDocument();
});
```
|
4,559 | 0 | petrpan-code/storybookjs/storybook/scripts/release | petrpan-code/storybookjs/storybook/scripts/release/__tests__/cancel-preparation-runs.test.ts | /* eslint-disable global-require */
/* eslint-disable no-underscore-dangle */
import {
PREPARE_NON_PATCH_WORKFLOW_PATH,
PREPARE_PATCH_WORKFLOW_PATH,
run as cancelPreparationWorkflows,
} from '../cancel-preparation-runs';
import * as github_ from '../utils/github-client';
jest.mock('../utils/github-client');
const github = jest.mocked(github_);
jest.spyOn(console, 'log').mockImplementation(() => {});
jest.spyOn(console, 'warn').mockImplementation(() => {});
jest.spyOn(console, 'error').mockImplementation(() => {});
describe('Cancel preparation runs', () => {
beforeEach(() => {
jest.clearAllMocks();
github.githubRestClient.mockImplementation(((route: string, options: any) => {
switch (route) {
case 'GET /repos/{owner}/{repo}/actions/workflows':
return {
data: {
workflows: [
{
id: 1,
path: PREPARE_PATCH_WORKFLOW_PATH,
},
{
id: 2,
path: PREPARE_NON_PATCH_WORKFLOW_PATH,
},
],
},
};
case 'GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs':
return {
data: {
workflow_runs: [
{
id: options.workflow_id === 1 ? 100 : 200,
status: 'in_progress',
},
{
id: options.workflow_id === 1 ? 150 : 250,
status: 'completed',
},
],
},
};
case 'POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel':
return undefined; // success
default:
throw new Error(`Unexpected route: ${route}`);
}
}) as any);
});
it('should fail early when no GH_TOKEN is set', async () => {
delete process.env.GH_TOKEN;
await expect(cancelPreparationWorkflows()).rejects.toThrowErrorMatchingInlineSnapshot(
`"GH_TOKEN environment variable must be set, exiting."`
);
});
it('should cancel all running preparation workflows in GitHub', async () => {
process.env.GH_TOKEN = 'MY_SECRET';
await expect(cancelPreparationWorkflows()).resolves.toBeUndefined();
expect(github.githubRestClient).toHaveBeenCalledTimes(5);
expect(github.githubRestClient).toHaveBeenCalledWith(
'POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel',
{
owner: 'storybookjs',
repo: 'storybook',
run_id: 100,
}
);
expect(github.githubRestClient).toHaveBeenCalledWith(
'POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel',
{
owner: 'storybookjs',
repo: 'storybook',
run_id: 200,
}
);
expect(github.githubRestClient).not.toHaveBeenCalledWith(
'POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel',
{
owner: 'storybookjs',
repo: 'storybook',
run_id: 150,
}
);
expect(github.githubRestClient).not.toHaveBeenCalledWith(
'POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel',
{
owner: 'storybookjs',
repo: 'storybook',
run_id: 250,
}
);
});
});
|
4,560 | 0 | petrpan-code/storybookjs/storybook/scripts/release | petrpan-code/storybookjs/storybook/scripts/release/__tests__/ensure-next-ahead.test.ts | /* eslint-disable global-require */
/* eslint-disable no-underscore-dangle */
import path from 'path';
import { run as ensureNextAhead } from '../ensure-next-ahead';
import * as gitClient_ from '../utils/git-client';
import * as bumpVersion_ from '../version';
jest.mock('../utils/git-client', () => jest.requireActual('jest-mock-extended').mockDeep());
const gitClient = jest.mocked(gitClient_);
// eslint-disable-next-line jest/no-mocks-import
jest.mock('fs-extra', () => require('../../../code/__mocks__/fs-extra'));
const fsExtra = require('fs-extra');
jest.mock('../version', () => jest.requireActual('jest-mock-extended').mockDeep());
const bumpVersion = jest.mocked(bumpVersion_);
jest.spyOn(console, 'log').mockImplementation(() => {});
jest.spyOn(console, 'warn').mockImplementation(() => {});
jest.spyOn(console, 'error').mockImplementation(() => {});
const CODE_PACKAGE_JSON_PATH = path.join(__dirname, '..', '..', '..', 'code', 'package.json');
describe('Ensure next ahead', () => {
beforeEach(() => {
jest.clearAllMocks();
gitClient.git.status.mockResolvedValue({ current: 'next' } as any);
fsExtra.__setMockFiles({
[CODE_PACKAGE_JSON_PATH]: JSON.stringify({ version: '2.0.0' }),
});
});
it('should throw when main-version is missing', async () => {
await expect(ensureNextAhead({})).rejects.toThrowErrorMatchingInlineSnapshot(`
"[
{
"code": "invalid_type",
"expected": "string",
"received": "undefined",
"path": [
"mainVersion"
],
"message": "Required"
}
]"
`);
});
it('should throw when main-version is not a semver string', async () => {
await expect(ensureNextAhead({ mainVersion: '200' })).rejects
.toThrowErrorMatchingInlineSnapshot(`
"[
{
"code": "custom",
"message": "main-version must be a valid semver version string like '7.4.2'.",
"path": []
}
]"
`);
});
it('should not bump version when next is already ahead of main', async () => {
await expect(ensureNextAhead({ mainVersion: '1.0.0' })).resolves.toBeUndefined();
expect(bumpVersion.run).not.toHaveBeenCalled();
});
it('should bump version to 3.1.0-alpha.0 when main is 3.0.0 and next is 2.0.0', async () => {
await expect(ensureNextAhead({ mainVersion: '3.0.0' })).resolves.toBeUndefined();
expect(bumpVersion.run).toHaveBeenCalledWith({ exact: '3.1.0-alpha.0' });
});
it('should bump version to 2.1.0-alpha.0 when main and next are both 2.0.0', async () => {
await expect(ensureNextAhead({ mainVersion: '2.0.0' })).resolves.toBeUndefined();
expect(bumpVersion.run).toHaveBeenCalledWith({ exact: '2.1.0-alpha.0' });
});
it('should bump version to 2.1.0-alpha.0 when main is 2.0.0 and and next is 2.0.0-rc.10', async () => {
fsExtra.__setMockFiles({
[CODE_PACKAGE_JSON_PATH]: JSON.stringify({ version: '2.0.0-rc.10' }),
});
await expect(ensureNextAhead({ mainVersion: '2.0.0' })).resolves.toBeUndefined();
expect(bumpVersion.run).toHaveBeenCalledWith({ exact: '2.1.0-alpha.0' });
});
});
|
4,561 | 0 | petrpan-code/storybookjs/storybook/scripts/release | petrpan-code/storybookjs/storybook/scripts/release/__tests__/generate-pr-description.test.ts | import {
generateReleaseDescription,
generateNonReleaseDescription,
mapToChangelist,
mapCherryPicksToTodo,
} from '../generate-pr-description';
import type { Change } from '../utils/get-changes';
describe('Generate PR Description', () => {
const changes: Change[] = [
{
user: 'JReinhold',
id: 'pr-id-42',
title: 'Some PR title for a bug',
labels: ['bug', 'build', 'other label', 'patch:yes'],
commit: 'abc123',
pull: 42,
state: 'MERGED',
links: {
commit: '[abc123](https://github.com/storybookjs/storybook/commit/abc123)',
pull: '[#42](https://github.com/storybookjs/storybook/pull/42)',
user: '[@JReinhold](https://github.com/JReinhold)',
},
},
{
// this Bump version commit should be ignored
id: null,
user: 'storybook-bot',
pull: null,
state: null,
commit: '012b58140c3606efeacbe99c0c410624b0a1ed1f',
title: 'Bump version on `next`: preminor (alpha) from 7.2.0 to 7.3.0-alpha.0',
labels: null,
links: {
commit:
'[`012b58140c3606efeacbe99c0c410624b0a1ed1f`](https://github.com/storybookjs/storybook/commit/012b58140c3606efeacbe99c0c410624b0a1ed1f)',
pull: null,
user: '[@storybook-bot](https://github.com/storybook-bot)',
},
},
{
id: null,
user: 'shilman',
title: 'Some title for a "direct commit"',
labels: null,
state: null,
commit: '22bb11',
pull: null,
links: {
commit: '[22bb11](https://github.com/storybookjs/storybook/commit/22bb11)',
pull: null,
user: '[@shilman](https://github.com/shilman)',
},
},
{
id: 'pr-id-11',
user: 'shilman',
title: 'Another PR `title` for docs',
labels: ['another label', 'documentation', 'patch:yes'],
commit: 'ddd222',
state: 'MERGED',
pull: 11,
links: {
commit: '[ddd222](https://github.com/storybookjs/storybook/commit/ddd222)',
pull: '[#11](https://github.com/storybookjs/storybook/pull/11)',
user: '[@shilman](https://github.com/shilman)',
},
},
{
id: 'pr-id-48',
user: 'JReinhold',
title: "Some PR title for a 'new' feature",
labels: ['feature request', 'other label'],
commit: 'wow1337',
pull: 48,
state: 'MERGED',
links: {
commit: '[wow1337](https://github.com/storybookjs/storybook/commit/wow1337)',
pull: '[#48](https://github.com/storybookjs/storybook/pull/48)',
user: '[@JReinhold](https://github.com/JReinhold)',
},
},
{
id: 'pr-id-77',
user: 'JReinhold',
title: 'Some PR title with a missing label',
labels: ['incorrect label', 'other label'],
commit: 'bad999',
state: 'MERGED',
pull: 77,
links: {
commit: '[bad999](https://github.com/storybookjs/storybook/commit/bad999)',
pull: '[#77](https://github.com/storybookjs/storybook/pull/77)',
user: '[@JReinhold](https://github.com/JReinhold)',
},
},
];
describe('mapToChangelist', () => {
it('should return a correct string for patch PRs', () => {
expect(mapToChangelist({ changes, unpickedPatches: true })).toMatchInlineSnapshot(`
"- [ ] **🐛 Bug**: Some PR title for a bug [#42](https://github.com/storybookjs/storybook/pull/42)
- [ ] **✨ Feature Request**: Some PR title for a 'new' feature [#48](https://github.com/storybookjs/storybook/pull/48)
- [ ] **⚠️ Direct commit**: Some title for a "direct commit" [22bb11](https://github.com/storybookjs/storybook/commit/22bb11)
- [ ] **📝 Documentation**: Another PR \`title\` for docs [#11](https://github.com/storybookjs/storybook/pull/11)
- [ ] **❔ Missing Label**: Some PR title with a missing label [#77](https://github.com/storybookjs/storybook/pull/77)"
`);
});
it('should return a correct string for prerelease PRs', () => {
expect(mapToChangelist({ changes, unpickedPatches: false })).toMatchInlineSnapshot(`
"- [ ] **🐛 Bug**: Some PR title for a bug [#42](https://github.com/storybookjs/storybook/pull/42) (will also be patched)
- [ ] **✨ Feature Request**: Some PR title for a 'new' feature [#48](https://github.com/storybookjs/storybook/pull/48)
- [ ] **⚠️ Direct commit**: Some title for a "direct commit" [22bb11](https://github.com/storybookjs/storybook/commit/22bb11)
- [ ] **📝 Documentation**: Another PR \`title\` for docs [#11](https://github.com/storybookjs/storybook/pull/11) (will also be patched)
- [ ] **❔ Missing Label**: Some PR title with a missing label [#77](https://github.com/storybookjs/storybook/pull/77)"
`);
});
});
describe('mapCherryPicksToTodo', () => {
it('should return a correct string for releases', () => {
expect(mapCherryPicksToTodo({ changes, commits: ['abc123'] })).toMatchInlineSnapshot(`
"## 🍒 Manual cherry picking needed!
The following pull requests could not be cherry-picked automatically because it resulted in merge conflicts.
For each pull request below, you need to either manually cherry pick it, or discard it by replacing the "patch:yes" label with "patch:no" on the PR and re-generate this PR.
- [ ] [#42](https://github.com/storybookjs/storybook/pull/42): \`git cherry-pick -m1 -x abc123\`"
`);
});
});
describe('description generator', () => {
const changeList = `- **🐛 Bug**: Some PR title for a bug [#42](https://github.com/storybookjs/storybook/pull/42)
\t- [ ] The change is appropriate for the version bump
\t- [ ] The PR is labeled correctly
\t- [ ] The PR title is correct
- **⚠️ Direct commit**: Some title for a \\"direct commit\\" [22bb11](https://github.com/storybookjs/storybook/commit/22bb11)
\t- [ ] The change is appropriate for the version bump
- **📝 Documentation**: Another PR \\\`title\\\` for docs [#11](https://github.com/storybookjs/storybook/pull/11)
\t- [ ] The change is appropriate for the version bump
\t- [ ] The PR is labeled correctly
\t- [ ] The PR title is correct
- **✨ Feature Request**: Some PR title for a \\'new\\' feature [#48](https://github.com/storybookjs/storybook/pull/48)
\t- [ ] The change is appropriate for the version bump
\t- [ ] The PR is labeled correctly
\t- [ ] The PR title is correct
- **⚠️ Missing Label**: Some PR title with a missing label [#77](https://github.com/storybookjs/storybook/pull/77)
\t- [ ] The change is appropriate for the version bump
\t- [ ] The PR is labeled correctly
\t- [ ] The PR title is correct`;
const manualCherryPicks = `## 🍒 Manual cherry picking needed!
The following pull requests could not be cherry-picked automatically because it resulted in merge conflicts.
For each pull request below, you need to either manually cherry pick it, or discard it by removing the "patch" label from the PR and re-generate this PR.
- [ ] [#42](https://github.com/storybookjs/storybook/pull/42): \`git cherry-pick -m1 -x abc123\``;
it('should return a correct string with cherry picks for releases', () => {
const changelogText = `## 7.1.0-alpha.11
- Some PR \`title\` for a bug [#42](https://github.com/storybookjs/storybook/pull/42), thanks [@JReinhold](https://github.com/JReinhold)
- Some PR 'title' for a feature request [#48](https://github.com/storybookjs/storybook/pull/48), thanks [@JReinhold](https://github.com/JReinhold)
- Antoher PR "title" for maintainance [#49](https://github.com/storybookjs/storybook/pull/49), thanks [@JReinhold](https://github.com/JReinhold)`;
expect(
generateReleaseDescription({
currentVersion: '7.1.0-alpha.10',
nextVersion: '7.1.0-alpha.11',
changeList,
changelogText,
manualCherryPicks,
})
).toMatchInlineSnapshot(`
"This is an automated pull request that bumps the version from \\\`7.1.0-alpha.10\\\` to \\\`7.1.0-alpha.11\\\`.
Once this pull request is merged, it will trigger a new release of version \\\`7.1.0-alpha.11\\\`.
If you\\'re not a core maintainer with permissions to release you can ignore this pull request.
## To do
Before merging the PR, there are a few QA steps to go through:
- [ ] Add the \\"freeze\\" label to this PR, to ensure it doesn\\'t get automatically forced pushed by new changes.
- [ ] Add the \\"ci:daily\\" label to this PR, to trigger the full test suite to run on this PR.
And for each change below:
1. Ensure the change is appropriate for the version bump. E.g. patch release should only contain patches, not new or de-stabilizing features. If a change is not appropriate, revert the PR.
2. Ensure the PR is labeled correctly with one of: \\"BREAKING CHANGE\\", \\"feature request\\", \\"bug\\", \\"maintenance\\", \\"dependencies\\", \\"documentation\\", \\"build\\", \\"unknown\\".
3. Ensure the PR title is correct, and follows the format \\"[Area]: [Summary]\\", e.g. *\\"React: Fix hooks in CSF3 render functions\\"*. If it is not correct, change the title in the PR.
- Areas include: React, Vue, Core, Docs, Controls, etc.
- First word of summary indicates the type: “Add”, “Fix”, “Upgrade”, etc.
- The entire title should fit on a line
This is a list of all the PRs merged and commits pushed directly to \\\`next\\\`, that will be part of this release:
- **🐛 Bug**: Some PR title for a bug [#42](https://github.com/storybookjs/storybook/pull/42)
- [ ] The change is appropriate for the version bump
- [ ] The PR is labeled correctly
- [ ] The PR title is correct
- **⚠️ Direct commit**: Some title for a \\\\"direct commit\\\\" [22bb11](https://github.com/storybookjs/storybook/commit/22bb11)
- [ ] The change is appropriate for the version bump
- **📝 Documentation**: Another PR \\\\\`title\\\\\` for docs [#11](https://github.com/storybookjs/storybook/pull/11)
- [ ] The change is appropriate for the version bump
- [ ] The PR is labeled correctly
- [ ] The PR title is correct
- **✨ Feature Request**: Some PR title for a \\\\'new\\\\' feature [#48](https://github.com/storybookjs/storybook/pull/48)
- [ ] The change is appropriate for the version bump
- [ ] The PR is labeled correctly
- [ ] The PR title is correct
- **⚠️ Missing Label**: Some PR title with a missing label [#77](https://github.com/storybookjs/storybook/pull/77)
- [ ] The change is appropriate for the version bump
- [ ] The PR is labeled correctly
- [ ] The PR title is correct
## 🍒 Manual cherry picking needed!
The following pull requests could not be cherry-picked automatically because it resulted in merge conflicts.
For each pull request below, you need to either manually cherry pick it, or discard it by removing the \\"patch\\" label from the PR and re-generate this PR.
- [ ] [#42](https://github.com/storybookjs/storybook/pull/42): \\\`git cherry-pick -m1 -x abc123\\\`
If you\\'ve made any changes doing the above QA (change PR titles, revert PRs), manually trigger a re-generation of this PR with [this workflow](https://github.com/storybookjs/storybook/actions/workflows/prepare-non-patch-release.yml) and wait for it to finish. It will wipe your progress in this to do, which is expected.
Feel free to manually commit any changes necessary to this branch **after** you\\'ve done the last re-generation, following the [Make Manual Changes](https://github.com/storybookjs/storybook/blob/next/CONTRIBUTING/RELEASING.md#5-make-manual-changes) section in the docs, *especially* if you\\'re making changes to the changelog.
When everything above is done:
- Merge this PR
- [Follow the run of the publish action](https://github.com/storybookjs/storybook/actions/workflows/publish.yml)
---
# Generated changelog
## 7.1.0-alpha.11
- Some PR \\\`title\\\` for a bug [#42](https://github.com/storybookjs/storybook/pull/42), thanks [@ JReinhold](https://github.com/JReinhold)
- Some PR \\'title\\' for a feature request [#48](https://github.com/storybookjs/storybook/pull/48), thanks [@ JReinhold](https://github.com/JReinhold)
- Antoher PR \\"title\\" for maintainance [#49](https://github.com/storybookjs/storybook/pull/49), thanks [@ JReinhold](https://github.com/JReinhold)"
`);
});
it('should return a correct string for non-releases with cherry picks', () => {
expect(generateNonReleaseDescription(changeList, manualCherryPicks)).toMatchInlineSnapshot(`
"This is an automated pull request. None of the changes requires a version bump, they are only internal or documentation related. Merging this PR will not trigger a new release, but documentation will be updated.
If you\\'re not a core maintainer with permissions to release you can ignore this pull request.
## To do
Before merging the PR:
- [ ] Add the \\"freeze\\" label to this PR, to ensure it doesn\\'t get automatically forced pushed by new changes.
- [ ] Add the \\"ci:daily\\" label to this PR, to trigger the full test suite to run on this PR.
This is a list of all the PRs merged and commits pushed directly to \\\`next\\\` since the last release:
- **🐛 Bug**: Some PR title for a bug [#42](https://github.com/storybookjs/storybook/pull/42)
- [ ] The change is appropriate for the version bump
- [ ] The PR is labeled correctly
- [ ] The PR title is correct
- **⚠️ Direct commit**: Some title for a \\\\"direct commit\\\\" [22bb11](https://github.com/storybookjs/storybook/commit/22bb11)
- [ ] The change is appropriate for the version bump
- **📝 Documentation**: Another PR \\\\\`title\\\\\` for docs [#11](https://github.com/storybookjs/storybook/pull/11)
- [ ] The change is appropriate for the version bump
- [ ] The PR is labeled correctly
- [ ] The PR title is correct
- **✨ Feature Request**: Some PR title for a \\\\'new\\\\' feature [#48](https://github.com/storybookjs/storybook/pull/48)
- [ ] The change is appropriate for the version bump
- [ ] The PR is labeled correctly
- [ ] The PR title is correct
- **⚠️ Missing Label**: Some PR title with a missing label [#77](https://github.com/storybookjs/storybook/pull/77)
- [ ] The change is appropriate for the version bump
- [ ] The PR is labeled correctly
- [ ] The PR title is correct
## 🍒 Manual cherry picking needed!
The following pull requests could not be cherry-picked automatically because it resulted in merge conflicts.
For each pull request below, you need to either manually cherry pick it, or discard it by removing the \\"patch\\" label from the PR and re-generate this PR.
- [ ] [#42](https://github.com/storybookjs/storybook/pull/42): \\\`git cherry-pick -m1 -x abc123\\\`
If you\\'ve made any changes (change PR titles, revert PRs), manually trigger a re-generation of this PR with [this workflow](https://github.com/storybookjs/storybook/actions/workflows/prepare-patch-release.yml) and wait for it to finish.
Feel free to manually commit any changes necessary to this branch **after** you\\'ve done the last re-generation, following the [Make Manual Changes](https://github.com/storybookjs/storybook/blob/next/CONTRIBUTING/RELEASING.md#5-make-manual-changes) section in the docs.
When everything above is done:
- Merge this PR
- [Follow the run of the publish action](https://github.com/storybookjs/storybook/actions/workflows/publish.yml)"
`);
});
it('should return a correct string without cherry picks for releases', () => {
const changelogText = `## 7.1.0-alpha.11
- Some PR \`title\` for a bug [#42](https://github.com/storybookjs/storybook/pull/42), thanks [@JReinhold](https://github.com/JReinhold)
- Some PR 'title' for a feature request [#48](https://github.com/storybookjs/storybook/pull/48), thanks [@JReinhold](https://github.com/JReinhold)
- Antoher PR "title" for maintainance [#49](https://github.com/storybookjs/storybook/pull/49), thanks [@JReinhold](https://github.com/JReinhold)`;
expect(
generateReleaseDescription({
currentVersion: '7.1.0-alpha.10',
nextVersion: '7.1.0-alpha.11',
changeList,
changelogText,
})
).toMatchInlineSnapshot(`
"This is an automated pull request that bumps the version from \\\`7.1.0-alpha.10\\\` to \\\`7.1.0-alpha.11\\\`.
Once this pull request is merged, it will trigger a new release of version \\\`7.1.0-alpha.11\\\`.
If you\\'re not a core maintainer with permissions to release you can ignore this pull request.
## To do
Before merging the PR, there are a few QA steps to go through:
- [ ] Add the \\"freeze\\" label to this PR, to ensure it doesn\\'t get automatically forced pushed by new changes.
- [ ] Add the \\"ci:daily\\" label to this PR, to trigger the full test suite to run on this PR.
And for each change below:
1. Ensure the change is appropriate for the version bump. E.g. patch release should only contain patches, not new or de-stabilizing features. If a change is not appropriate, revert the PR.
2. Ensure the PR is labeled correctly with one of: \\"BREAKING CHANGE\\", \\"feature request\\", \\"bug\\", \\"maintenance\\", \\"dependencies\\", \\"documentation\\", \\"build\\", \\"unknown\\".
3. Ensure the PR title is correct, and follows the format \\"[Area]: [Summary]\\", e.g. *\\"React: Fix hooks in CSF3 render functions\\"*. If it is not correct, change the title in the PR.
- Areas include: React, Vue, Core, Docs, Controls, etc.
- First word of summary indicates the type: “Add”, “Fix”, “Upgrade”, etc.
- The entire title should fit on a line
This is a list of all the PRs merged and commits pushed directly to \\\`next\\\`, that will be part of this release:
- **🐛 Bug**: Some PR title for a bug [#42](https://github.com/storybookjs/storybook/pull/42)
- [ ] The change is appropriate for the version bump
- [ ] The PR is labeled correctly
- [ ] The PR title is correct
- **⚠️ Direct commit**: Some title for a \\\\"direct commit\\\\" [22bb11](https://github.com/storybookjs/storybook/commit/22bb11)
- [ ] The change is appropriate for the version bump
- **📝 Documentation**: Another PR \\\\\`title\\\\\` for docs [#11](https://github.com/storybookjs/storybook/pull/11)
- [ ] The change is appropriate for the version bump
- [ ] The PR is labeled correctly
- [ ] The PR title is correct
- **✨ Feature Request**: Some PR title for a \\\\'new\\\\' feature [#48](https://github.com/storybookjs/storybook/pull/48)
- [ ] The change is appropriate for the version bump
- [ ] The PR is labeled correctly
- [ ] The PR title is correct
- **⚠️ Missing Label**: Some PR title with a missing label [#77](https://github.com/storybookjs/storybook/pull/77)
- [ ] The change is appropriate for the version bump
- [ ] The PR is labeled correctly
- [ ] The PR title is correct
If you\\'ve made any changes doing the above QA (change PR titles, revert PRs), manually trigger a re-generation of this PR with [this workflow](https://github.com/storybookjs/storybook/actions/workflows/prepare-non-patch-release.yml) and wait for it to finish. It will wipe your progress in this to do, which is expected.
Feel free to manually commit any changes necessary to this branch **after** you\\'ve done the last re-generation, following the [Make Manual Changes](https://github.com/storybookjs/storybook/blob/next/CONTRIBUTING/RELEASING.md#5-make-manual-changes) section in the docs, *especially* if you\\'re making changes to the changelog.
When everything above is done:
- Merge this PR
- [Follow the run of the publish action](https://github.com/storybookjs/storybook/actions/workflows/publish.yml)
---
# Generated changelog
## 7.1.0-alpha.11
- Some PR \\\`title\\\` for a bug [#42](https://github.com/storybookjs/storybook/pull/42), thanks [@ JReinhold](https://github.com/JReinhold)
- Some PR \\'title\\' for a feature request [#48](https://github.com/storybookjs/storybook/pull/48), thanks [@ JReinhold](https://github.com/JReinhold)
- Antoher PR \\"title\\" for maintainance [#49](https://github.com/storybookjs/storybook/pull/49), thanks [@ JReinhold](https://github.com/JReinhold)"
`);
});
it('should return a correct string for non-releases without cherry picks', () => {
expect(generateNonReleaseDescription(changeList)).toMatchInlineSnapshot(`
"This is an automated pull request. None of the changes requires a version bump, they are only internal or documentation related. Merging this PR will not trigger a new release, but documentation will be updated.
If you\\'re not a core maintainer with permissions to release you can ignore this pull request.
## To do
Before merging the PR:
- [ ] Add the \\"freeze\\" label to this PR, to ensure it doesn\\'t get automatically forced pushed by new changes.
- [ ] Add the \\"ci:daily\\" label to this PR, to trigger the full test suite to run on this PR.
This is a list of all the PRs merged and commits pushed directly to \\\`next\\\` since the last release:
- **🐛 Bug**: Some PR title for a bug [#42](https://github.com/storybookjs/storybook/pull/42)
- [ ] The change is appropriate for the version bump
- [ ] The PR is labeled correctly
- [ ] The PR title is correct
- **⚠️ Direct commit**: Some title for a \\\\"direct commit\\\\" [22bb11](https://github.com/storybookjs/storybook/commit/22bb11)
- [ ] The change is appropriate for the version bump
- **📝 Documentation**: Another PR \\\\\`title\\\\\` for docs [#11](https://github.com/storybookjs/storybook/pull/11)
- [ ] The change is appropriate for the version bump
- [ ] The PR is labeled correctly
- [ ] The PR title is correct
- **✨ Feature Request**: Some PR title for a \\\\'new\\\\' feature [#48](https://github.com/storybookjs/storybook/pull/48)
- [ ] The change is appropriate for the version bump
- [ ] The PR is labeled correctly
- [ ] The PR title is correct
- **⚠️ Missing Label**: Some PR title with a missing label [#77](https://github.com/storybookjs/storybook/pull/77)
- [ ] The change is appropriate for the version bump
- [ ] The PR is labeled correctly
- [ ] The PR title is correct
If you\\'ve made any changes (change PR titles, revert PRs), manually trigger a re-generation of this PR with [this workflow](https://github.com/storybookjs/storybook/actions/workflows/prepare-patch-release.yml) and wait for it to finish.
Feel free to manually commit any changes necessary to this branch **after** you\\'ve done the last re-generation, following the [Make Manual Changes](https://github.com/storybookjs/storybook/blob/next/CONTRIBUTING/RELEASING.md#5-make-manual-changes) section in the docs.
When everything above is done:
- Merge this PR
- [Follow the run of the publish action](https://github.com/storybookjs/storybook/actions/workflows/publish.yml)"
`);
});
});
});
|
4,562 | 0 | petrpan-code/storybookjs/storybook/scripts/release | petrpan-code/storybookjs/storybook/scripts/release/__tests__/is-pr-frozen.test.ts | /* eslint-disable no-underscore-dangle */
/* eslint-disable global-require */
import path from 'path';
import { run as isPrFrozen } from '../is-pr-frozen';
// eslint-disable-next-line jest/no-mocks-import
jest.mock('fs-extra', () => require('../../../code/__mocks__/fs-extra'));
jest.mock('../utils/get-github-info');
const fsExtra = require('fs-extra');
const simpleGit = require('simple-git');
const { getPullInfoFromCommit } = require('../utils/get-github-info');
const CODE_DIR_PATH = path.join(__dirname, '..', '..', '..', 'code');
const CODE_PACKAGE_JSON_PATH = path.join(CODE_DIR_PATH, 'package.json');
fsExtra.__setMockFiles({
[CODE_PACKAGE_JSON_PATH]: JSON.stringify({ version: '1.0.0' }),
});
describe('isPrFrozen', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should return true when PR is frozen', async () => {
getPullInfoFromCommit.mockResolvedValue({
labels: ['freeze'],
state: 'OPEN',
});
await expect(isPrFrozen({ patch: false })).resolves.toBe(true);
});
it('should return false when PR is not frozen', async () => {
getPullInfoFromCommit.mockResolvedValue({
labels: [],
state: 'OPEN',
});
await expect(isPrFrozen({ patch: false })).resolves.toBe(false);
});
it('should return false when PR is closed', async () => {
getPullInfoFromCommit.mockResolvedValue({
labels: ['freeze'],
state: 'CLOSED',
});
await expect(isPrFrozen({ patch: false })).resolves.toBe(false);
});
it('should look for patch PRs when patch is true', async () => {
getPullInfoFromCommit.mockResolvedValue({
labels: [],
});
await isPrFrozen({ patch: true });
expect(simpleGit.__fetch).toHaveBeenCalledWith('origin', 'version-patch-from-1.0.0', {
'--depth': 1,
});
});
it('should look for prerelease PRs when patch is false', async () => {
getPullInfoFromCommit.mockResolvedValue({
labels: [],
});
await isPrFrozen({ patch: false });
expect(simpleGit.__fetch).toHaveBeenCalledWith('origin', 'version-non-patch-from-1.0.0', {
'--depth': 1,
});
});
});
|
4,563 | 0 | petrpan-code/storybookjs/storybook/scripts/release | petrpan-code/storybookjs/storybook/scripts/release/__tests__/label-patches.test.ts | import type { LogResult } from 'simple-git';
import ansiRegex from 'ansi-regex';
import { run } from '../label-patches';
import * as gitClient_ from '../utils/git-client';
import * as githubInfo_ from '../utils/get-github-info';
import * as github_ from '../utils/github-client';
jest.mock('uuid');
jest.mock('../utils/get-github-info');
jest.mock('../utils/github-client');
jest.mock('../utils/git-client', () => jest.requireActual('jest-mock-extended').mockDeep());
const gitClient = jest.mocked(gitClient_);
const github = jest.mocked(github_);
const githubInfo = jest.mocked(githubInfo_);
const remoteMock = [
{
name: 'origin',
refs: {
fetch: 'https://github.com/storybookjs/storybook.git',
push: 'https://github.com/storybookjs/storybook.git',
},
},
];
const gitLogMock: LogResult = {
all: [
{
hash: 'some-hash',
date: '2023-06-07T09:45:11+02:00',
message: 'Something else',
refs: 'HEAD -> main',
body: '',
author_name: 'Jeppe Reinhold',
author_email: 'jeppe@chromatic.com',
},
{
hash: 'b75879c4d3d72f7830e9c5fca9f75a303ddb194d',
date: '2023-06-07T09:45:11+02:00',
message: 'Merge pull request #55 from storybookjs/fixes',
refs: 'HEAD -> main',
body:
'Legal: Fix license\n' +
'(cherry picked from commit 930b47f011f750c44a1782267d698ccdd3c04da3)\n',
author_name: 'Jeppe Reinhold',
author_email: 'jeppe@chromatic.com',
},
],
latest: null!,
total: 1,
};
const pullInfoMock = {
user: 'JReinhold',
id: 'pr_id',
pull: 55,
commit: '930b47f011f750c44a1782267d698ccdd3c04da3',
title: 'Legal: Fix license',
labels: ['documentation', 'patch:yes', 'patch:done'],
state: 'MERGED',
links: {
commit:
'[`930b47f011f750c44a1782267d698ccdd3c04da3`](https://github.com/storybookjs/storybook/commit/930b47f011f750c44a1782267d698ccdd3c04da3)',
pull: '[#55](https://github.com/storybookjs/storybook/pull/55)',
user: '[@JReinhold](https://github.com/JReinhold)',
},
};
beforeEach(() => {
// mock IO
jest.clearAllMocks();
gitClient.getLatestTag.mockResolvedValue('v7.2.1');
gitClient.git.log.mockResolvedValue(gitLogMock);
gitClient.git.getRemotes.mockResolvedValue(remoteMock);
githubInfo.getPullInfoFromCommit.mockResolvedValue(pullInfoMock);
github.getLabelIds.mockResolvedValue({ 'patch:done': 'pick-id' });
github.getUnpickedPRs.mockResolvedValue([
{
number: 42,
id: 'some-id',
branch: 'some-patching-branch',
title: 'Fix: Patch this PR',
mergeCommit: 'abcd1234',
},
{
number: 44,
id: 'other-id',
branch: 'other-patching-branch',
title: 'Fix: Also patch this PR',
mergeCommit: 'abcd1234',
},
]);
});
test('it should fail early when no GH_TOKEN is set', async () => {
delete process.env.GH_TOKEN;
await expect(run({})).rejects.toThrowErrorMatchingInlineSnapshot(
`"GH_TOKEN environment variable must be set, exiting."`
);
});
test('it should label the PR associated with cheery picks in the current branch', async () => {
process.env.GH_TOKEN = 'MY_SECRET';
const writeStderr = jest.spyOn(process.stderr, 'write').mockImplementation();
await run({});
expect(github.githubGraphQlClient.mock.calls).toMatchInlineSnapshot(`
[
[
"
mutation ($input: AddLabelsToLabelableInput!) {
addLabelsToLabelable(input: $input) {
clientMutationId
}
}
",
{
"input": {
"clientMutationId": "7efda802-d7d1-5d76-97d6-cc16a9f3e357",
"labelIds": [
"pick-id",
],
"labelableId": "pr_id",
},
},
],
]
`);
const stderrCalls = writeStderr.mock.calls
.map(([text]) =>
typeof text === 'string'
? text
.replace(ansiRegex(), '')
.replace(/[^\x20-\x7E]/g, '')
.replaceAll('-', '')
.trim()
: text
)
.filter((it) => it !== '');
expect(stderrCalls).toMatchInlineSnapshot(`
[
"Looking for latest tag",
"Found latest tag: v7.2.1",
"Looking at cherry pick commits since v7.2.1",
"Found the following picks : Commit: 930b47f011f750c44a1782267d698ccdd3c04da3 PR: [#55](https://github.com/storybookjs/storybook/pull/55)",
"Labeling 1 PRs with the patch:done label...",
"Successfully labeled all PRs with the patch:done label.",
]
`);
});
test('it should label all PRs when the --all flag is passed', async () => {
process.env.GH_TOKEN = 'MY_SECRET';
// clear the git log, it shouldn't depend on it in --all mode
gitClient.git.log.mockResolvedValue({
all: [],
latest: null!,
total: 0,
});
const writeStderr = jest.spyOn(process.stderr, 'write').mockImplementation();
await run({ all: true });
expect(github.githubGraphQlClient.mock.calls).toMatchInlineSnapshot(`
[
[
"
mutation ($input: AddLabelsToLabelableInput!) {
addLabelsToLabelable(input: $input) {
clientMutationId
}
}
",
{
"input": {
"clientMutationId": "39cffd21-7933-56e4-9d9c-1afeda9d5906",
"labelIds": [
"pick-id",
],
"labelableId": "some-id",
},
},
],
[
"
mutation ($input: AddLabelsToLabelableInput!) {
addLabelsToLabelable(input: $input) {
clientMutationId
}
}
",
{
"input": {
"clientMutationId": "cc31033b-5da7-5c9e-adf2-80a2963e19a8",
"labelIds": [
"pick-id",
],
"labelableId": "other-id",
},
},
],
]
`);
const stderrCalls = writeStderr.mock.calls
.map(([text]) =>
typeof text === 'string'
? text
.replace(ansiRegex(), '')
.replace(/[^\x20-\x7E]/g, '')
.replaceAll('-', '')
.trim()
: text
)
.filter((it) => it !== '');
expect(stderrCalls).toMatchInlineSnapshot(`
[
"Labeling 2 PRs with the patch:done label...",
"Successfully labeled all PRs with the patch:done label.",
]
`);
expect(github.getUnpickedPRs).toHaveBeenCalledTimes(1);
});
|
4,564 | 0 | petrpan-code/storybookjs/storybook/scripts/release | petrpan-code/storybookjs/storybook/scripts/release/__tests__/version.test.ts | /* eslint-disable global-require */
/* eslint-disable no-underscore-dangle */
import path from 'path';
import { run as version } from '../version';
// eslint-disable-next-line jest/no-mocks-import
jest.mock('fs-extra', () => require('../../../code/__mocks__/fs-extra'));
const fsExtra = require('fs-extra');
jest.mock('../../../code/lib/cli/src/versions', () => ({
'@storybook/addon-a11y': '7.1.0-alpha.29',
}));
jest.mock('execa');
const { execaCommand } = require('execa');
jest.mock('../../utils/workspace', () => ({
getWorkspaces: jest.fn().mockResolvedValue([
{
name: '@storybook/addon-a11y',
location: 'addons/a11y',
},
]),
}));
jest.spyOn(console, 'log').mockImplementation(() => {});
jest.spyOn(console, 'warn').mockImplementation(() => {});
jest.spyOn(console, 'error').mockImplementation(() => {});
beforeEach(() => {
jest.clearAllMocks();
});
describe('Version', () => {
const CODE_DIR_PATH = path.join(__dirname, '..', '..', '..', 'code');
const CODE_PACKAGE_JSON_PATH = path.join(CODE_DIR_PATH, 'package.json');
const MANAGER_API_VERSION_PATH = path.join(
CODE_DIR_PATH,
'lib',
'manager-api',
'src',
'version.ts'
);
const VERSIONS_PATH = path.join(CODE_DIR_PATH, 'lib', 'cli', 'src', 'versions.ts');
const A11Y_PACKAGE_JSON_PATH = path.join(CODE_DIR_PATH, 'addons', 'a11y', 'package.json');
it('should throw when release type is invalid', async () => {
fsExtra.__setMockFiles({
[CODE_PACKAGE_JSON_PATH]: JSON.stringify({ version: '1.0.0' }),
[MANAGER_API_VERSION_PATH]: `export const version = "1.0.0";`,
[VERSIONS_PATH]: `export default { "@storybook/addon-a11y": "1.0.0" };`,
});
await expect(version({ releaseType: 'invalid' })).rejects.toThrowErrorMatchingInlineSnapshot(`
"[
{
"received": "invalid",
"code": "invalid_enum_value",
"options": [
"major",
"minor",
"patch",
"prerelease",
"premajor",
"preminor",
"prepatch"
],
"path": [
"releaseType"
],
"message": "Invalid enum value. Expected 'major' | 'minor' | 'patch' | 'prerelease' | 'premajor' | 'preminor' | 'prepatch', received 'invalid'"
}
]"
`);
});
it('should throw when prerelease identifier is combined with non-pre release type', async () => {
fsExtra.__setMockFiles({
[CODE_PACKAGE_JSON_PATH]: JSON.stringify({ version: '1.0.0' }),
[MANAGER_API_VERSION_PATH]: `export const version = "1.0.0";`,
[VERSIONS_PATH]: `export default { "@storybook/addon-a11y": "1.0.0" };`,
});
await expect(version({ releaseType: 'major', preId: 'alpha' })).rejects
.toThrowErrorMatchingInlineSnapshot(`
"[
{
"code": "custom",
"message": "Using prerelease identifier requires one of release types: premajor, preminor, prepatch, prerelease",
"path": []
}
]"
`);
});
it('should throw when exact is combined with release type', async () => {
fsExtra.__setMockFiles({
[CODE_PACKAGE_JSON_PATH]: JSON.stringify({ version: '1.0.0' }),
[MANAGER_API_VERSION_PATH]: `export const version = "1.0.0";`,
[VERSIONS_PATH]: `export default { "@storybook/addon-a11y": "1.0.0" };`,
});
await expect(version({ releaseType: 'major', exact: '1.0.0' })).rejects
.toThrowErrorMatchingInlineSnapshot(`
"[
{
"code": "custom",
"message": "Combining --exact with --release-type is invalid, but having one of them is required",
"path": []
}
]"
`);
});
it('should throw when exact is invalid semver', async () => {
fsExtra.__setMockFiles({
[CODE_PACKAGE_JSON_PATH]: JSON.stringify({ version: '1.0.0' }),
[MANAGER_API_VERSION_PATH]: `export const version = "1.0.0";`,
[VERSIONS_PATH]: `export default { "@storybook/addon-a11y": "1.0.0" };`,
});
await expect(version({ exact: 'not-semver' })).rejects.toThrowErrorMatchingInlineSnapshot(`
"[
{
"code": "custom",
"message": "--exact version has to be a valid semver string",
"path": [
"exact"
]
}
]"
`);
});
it('should throw when apply is combined with releaseType', async () => {
fsExtra.__setMockFiles({
[CODE_PACKAGE_JSON_PATH]: JSON.stringify({ version: '1.0.0' }),
[MANAGER_API_VERSION_PATH]: `export const version = "1.0.0";`,
[VERSIONS_PATH]: `export default { "@storybook/addon-a11y": "1.0.0" };`,
});
await expect(version({ apply: true, releaseType: 'prerelease' })).rejects
.toThrowErrorMatchingInlineSnapshot(`
"[
{
"code": "custom",
"message": "--apply cannot be combined with --exact or --release-type, as it will always read from code/package.json#deferredNextVersion",
"path": []
}
]"
`);
});
it('should throw when apply is combined with exact', async () => {
fsExtra.__setMockFiles({
[CODE_PACKAGE_JSON_PATH]: JSON.stringify({ version: '1.0.0' }),
[MANAGER_API_VERSION_PATH]: `export const version = "1.0.0";`,
[VERSIONS_PATH]: `export default { "@storybook/addon-a11y": "1.0.0" };`,
});
await expect(version({ apply: true, exact: '1.0.0' })).rejects
.toThrowErrorMatchingInlineSnapshot(`
"[
{
"code": "custom",
"message": "--apply cannot be combined with --exact or --release-type, as it will always read from code/package.json#deferredNextVersion",
"path": []
}
]"
`);
});
it('should throw when apply is combined with deferred', async () => {
fsExtra.__setMockFiles({
[CODE_PACKAGE_JSON_PATH]: JSON.stringify({ version: '1.0.0' }),
[MANAGER_API_VERSION_PATH]: `export const version = "1.0.0";`,
[VERSIONS_PATH]: `export default { "@storybook/addon-a11y": "1.0.0" };`,
});
await expect(version({ apply: true, deferred: true })).rejects
.toThrowErrorMatchingInlineSnapshot(`
"[
{
"code": "custom",
"message": "--deferred cannot be combined with --apply",
"path": []
}
]"
`);
});
it('should throw when applying without a "deferredNextVersion" set', async () => {
fsExtra.__setMockFiles({
[CODE_PACKAGE_JSON_PATH]: JSON.stringify({ version: '1.0.0' }),
});
await expect(version({ apply: true })).rejects.toThrowErrorMatchingInlineSnapshot(
`"The 'deferredNextVersion' property in code/package.json is unset. This is necessary to apply a deferred version bump"`
);
expect(fsExtra.writeJson).not.toHaveBeenCalled();
expect(fsExtra.writeFile).not.toHaveBeenCalled();
expect(execaCommand).not.toHaveBeenCalled();
});
it.each([
// prettier-ignore
{ releaseType: 'major', currentVersion: '1.1.1', expectedVersion: '2.0.0' },
// prettier-ignore
{ releaseType: 'minor', currentVersion: '1.1.1', expectedVersion: '1.2.0' },
// prettier-ignore
{ releaseType: 'patch', currentVersion: '1.1.1', expectedVersion: '1.1.2' },
// prettier-ignore
{ releaseType: 'premajor', preId: 'alpha', currentVersion: '1.1.1', expectedVersion: '2.0.0-alpha.0' },
// prettier-ignore
{ releaseType: 'preminor', preId: 'alpha', currentVersion: '1.1.1', expectedVersion: '1.2.0-alpha.0' },
// prettier-ignore
{ releaseType: 'prepatch', preId: 'alpha', currentVersion: '1.1.1', expectedVersion: '1.1.2-alpha.0' },
// prettier-ignore
{ releaseType: 'prerelease', currentVersion: '1.1.1-alpha.5', expectedVersion: '1.1.1-alpha.6' },
// prettier-ignore
{ releaseType: 'prerelease', preId: 'alpha', currentVersion: '1.1.1-alpha.5', expectedVersion: '1.1.1-alpha.6' },
// prettier-ignore
{ releaseType: 'prerelease', preId: 'beta', currentVersion: '1.1.1-alpha.10', expectedVersion: '1.1.1-beta.0' },
// prettier-ignore
{ releaseType: 'major', currentVersion: '1.1.1-rc.10', expectedVersion: '2.0.0' },
// prettier-ignore
{ releaseType: 'minor', currentVersion: '1.1.1-rc.10', expectedVersion: '1.2.0' },
// prettier-ignore
{ releaseType: 'patch', currentVersion: '1.1.1-rc.10', expectedVersion: '1.1.1' },
// prettier-ignore
{ exact: '4.2.0-canary.69', currentVersion: '1.1.1-rc.10', expectedVersion: '4.2.0-canary.69' },
// prettier-ignore
{ apply: true, currentVersion: '1.0.0', deferredNextVersion: '1.2.0', expectedVersion: '1.2.0' },
])(
'bump with type: "$releaseType", pre id "$preId" or exact "$exact" or apply $apply, from: $currentVersion, to: $expectedVersion',
async ({
releaseType,
preId,
exact,
apply,
currentVersion,
expectedVersion,
deferredNextVersion,
}) => {
fsExtra.__setMockFiles({
[CODE_PACKAGE_JSON_PATH]: JSON.stringify({ version: currentVersion, deferredNextVersion }),
[MANAGER_API_VERSION_PATH]: `export const version = "${currentVersion}";`,
[VERSIONS_PATH]: `export default { "@storybook/addon-a11y": "${currentVersion}" };`,
[A11Y_PACKAGE_JSON_PATH]: JSON.stringify({
version: currentVersion,
}),
[VERSIONS_PATH]: `export default { "@storybook/addon-a11y": "${currentVersion}" };`,
});
await version({ releaseType, preId, exact, apply });
expect(fsExtra.writeJson).toHaveBeenCalledTimes(apply ? 3 : 2);
if (apply) {
// eslint-disable-next-line jest/no-conditional-expect -- guarded against problems with the assertion above
expect(fsExtra.writeJson).toHaveBeenCalledWith(
CODE_PACKAGE_JSON_PATH,
// this call is the write that removes the "deferredNextVersion" property
{ version: currentVersion },
{ spaces: 2 }
);
}
expect(fsExtra.writeJson).toHaveBeenCalledWith(
CODE_PACKAGE_JSON_PATH,
{ version: expectedVersion },
{ spaces: 2 }
);
expect(fsExtra.writeFile).toHaveBeenCalledWith(
MANAGER_API_VERSION_PATH,
`export const version = "${expectedVersion}";`
);
expect(fsExtra.writeFile).toHaveBeenCalledWith(
VERSIONS_PATH,
`export default { "@storybook/addon-a11y": "${expectedVersion}" };`
);
expect(fsExtra.writeJson).toHaveBeenCalledWith(
A11Y_PACKAGE_JSON_PATH,
expect.objectContaining({
// should update package version
version: expectedVersion,
}),
{ spaces: 2 }
);
expect(execaCommand).toHaveBeenCalledWith('yarn install --mode=update-lockfile', {
cwd: path.join(CODE_DIR_PATH),
cleanup: true,
stdio: undefined,
});
}
);
it('should only set version in "deferredNextVersion" when using --deferred', async () => {
fsExtra.__setMockFiles({
[CODE_PACKAGE_JSON_PATH]: JSON.stringify({ version: '1.0.0' }),
});
await version({ releaseType: 'premajor', preId: 'beta', deferred: true });
expect(fsExtra.writeJson).toHaveBeenCalledTimes(1);
expect(fsExtra.writeJson).toHaveBeenCalledWith(
CODE_PACKAGE_JSON_PATH,
{ version: '1.0.0', deferredNextVersion: '2.0.0-beta.0' },
{ spaces: 2 }
);
expect(fsExtra.writeFile).not.toHaveBeenCalled();
expect(execaCommand).not.toHaveBeenCalled();
});
});
|
4,565 | 0 | petrpan-code/storybookjs/storybook/scripts/release | petrpan-code/storybookjs/storybook/scripts/release/__tests__/write-changelog.test.ts | /* eslint-disable global-require */
/* eslint-disable no-underscore-dangle */
import path from 'path';
import dedent from 'ts-dedent';
import { run as writeChangelog } from '../write-changelog';
import * as changesUtils from '../utils/get-changes';
// eslint-disable-next-line jest/no-mocks-import
jest.mock('fs-extra', () => require('../../../code/__mocks__/fs-extra'));
const fsExtra = require('fs-extra');
const getChangesMock = jest.spyOn(changesUtils, 'getChanges');
jest.spyOn(console, 'log').mockImplementation(() => {});
jest.spyOn(console, 'warn').mockImplementation(() => {});
jest.spyOn(console, 'error').mockImplementation(() => {});
const STABLE_CHANGELOG_PATH = path.join(__dirname, '..', '..', '..', 'CHANGELOG.md');
const PRERELEASE_CHANGELOG_PATH = path.join(__dirname, '..', '..', '..', 'CHANGELOG.prerelease.md');
const LATEST_VERSION_PATH = path.join(
__dirname,
'..',
'..',
'..',
'docs',
'versions',
'latest.json'
);
const NEXT_VERSION_PATH = path.join(__dirname, '..', '..', '..', 'docs', 'versions', 'next.json');
beforeEach(() => {
jest.clearAllMocks();
});
const EXISTING_STABLE_CHANGELOG = dedent`## 7.0.0
- Core: Some change`;
const EXISTING_PRERELEASE_CHANGELOG = dedent`## 7.1.0-alpha.20
- CLI: Super fast now`;
fsExtra.__setMockFiles({
[STABLE_CHANGELOG_PATH]: EXISTING_STABLE_CHANGELOG,
[PRERELEASE_CHANGELOG_PATH]: EXISTING_PRERELEASE_CHANGELOG,
});
describe('Write changelog', () => {
it('should write to stable changelogs and version files in docs', async () => {
getChangesMock.mockResolvedValue({
changes: [],
changelogText: `## 7.0.1
- React: Make it reactive
- CLI: Not UI`,
});
await writeChangelog(['7.0.1'], {});
expect(fsExtra.writeFile).toHaveBeenCalledTimes(1);
expect(fsExtra.writeFile.mock.calls[0][0]).toBe(STABLE_CHANGELOG_PATH);
expect(fsExtra.writeFile.mock.calls[0][1]).toMatchInlineSnapshot(`
"## 7.0.1
- React: Make it reactive
- CLI: Not UI
## 7.0.0
- Core: Some change"
`);
expect(fsExtra.writeJson).toBeCalledTimes(1);
expect(fsExtra.writeJson.mock.calls[0][0]).toBe(LATEST_VERSION_PATH);
expect(fsExtra.writeJson.mock.calls[0][1]).toMatchInlineSnapshot(`
{
"info": {
"plain": "- React: Make it reactive
- CLI: Not UI",
},
"version": "7.0.1",
}
`);
});
it('should escape double quotes for json files', async () => {
getChangesMock.mockResolvedValue({
changes: [],
changelogText: `## 7.0.1
- React: Make it reactive
- Revert "CLI: Not UI"
- CLI: Not UI`,
});
await writeChangelog(['7.0.1'], {});
expect(fsExtra.writeFile).toHaveBeenCalledTimes(1);
expect(fsExtra.writeFile.mock.calls[0][0]).toBe(STABLE_CHANGELOG_PATH);
expect(fsExtra.writeFile.mock.calls[0][1]).toMatchInlineSnapshot(`
"## 7.0.1
- React: Make it reactive
- Revert "CLI: Not UI"
- CLI: Not UI
## 7.0.0
- Core: Some change"
`);
expect(fsExtra.writeJson).toBeCalledTimes(1);
expect(fsExtra.writeJson.mock.calls[0][0]).toBe(LATEST_VERSION_PATH);
expect(fsExtra.writeJson.mock.calls[0][1]).toMatchInlineSnapshot(`
{
"info": {
"plain": "- React: Make it reactive
- Revert \\"CLI: Not UI\\"
- CLI: Not UI",
},
"version": "7.0.1",
}
`);
});
it('should write to prerelase changelogs and version files in docs', async () => {
getChangesMock.mockResolvedValue({
changes: [],
changelogText: `## 7.1.0-alpha.21
- React: Make it reactive
- CLI: Not UI`,
});
await writeChangelog(['7.1.0-alpha.21'], {});
expect(fsExtra.writeFile).toHaveBeenCalledTimes(1);
expect(fsExtra.writeFile.mock.calls[0][0]).toBe(PRERELEASE_CHANGELOG_PATH);
expect(fsExtra.writeFile.mock.calls[0][1]).toMatchInlineSnapshot(`
"## 7.1.0-alpha.21
- React: Make it reactive
- CLI: Not UI
## 7.1.0-alpha.20
- CLI: Super fast now"
`);
expect(fsExtra.writeJson).toBeCalledTimes(1);
expect(fsExtra.writeJson.mock.calls[0][0]).toBe(NEXT_VERSION_PATH);
expect(fsExtra.writeJson.mock.calls[0][1]).toMatchInlineSnapshot(`
{
"info": {
"plain": "- React: Make it reactive
- CLI: Not UI",
},
"version": "7.1.0-alpha.21",
}
`);
});
});
|
4,595 | 0 | petrpan-code/storybookjs/storybook/scripts | petrpan-code/storybookjs/storybook/scripts/tasks/smoke-test.ts | import type { Task } from '../task';
import { exec } from '../utils/exec';
export const smokeTest: Task = {
description: 'Run the smoke tests of a sandbox',
dependsOn: ['sandbox'],
async ready() {
return false;
},
async run({ sandboxDir }, { dryRun, debug }) {
// eslint-disable-next-line no-console
console.log(`smoke testing in ${sandboxDir}`);
return exec(`yarn storybook --smoke-test`, { cwd: sandboxDir }, { dryRun, debug });
},
};
|
4,611 | 0 | petrpan-code/storybookjs/storybook/scripts | petrpan-code/storybookjs/storybook/scripts/utils/options.test.ts | import { describe, expect, it } from '@jest/globals';
import { createCommand } from 'commander';
import { areOptionsSatisfied, createOptions, getCommand, getOptions } from './options';
const allOptions = createOptions({
first: {
type: 'boolean',
description: 'first',
},
second: {
type: 'boolean',
description: 'second',
inverse: true,
},
third: {
type: 'string',
description: 'third',
values: ['one', 'two', 'three'] as const,
required: true as const,
},
fourth: {
type: 'string',
description: 'fourth',
},
fifth: {
type: 'string[]',
description: 'fifth',
values: ['a', 'b', 'c'] as const,
},
sixth: {
type: 'string[]',
description: 'sixth',
},
});
describe('getOptions', () => {
it('deals with boolean options', () => {
expect(getOptions(createCommand(), allOptions, ['command', 'name', '--first'])).toMatchObject({
first: true,
second: true,
});
});
it('deals with inverse boolean options', () => {
expect(
getOptions(createCommand(), allOptions, ['command', 'name', '--no-second'])
).toMatchObject({
first: false,
second: false,
});
});
it('deals with short options', () => {
expect(getOptions(createCommand(), allOptions, ['command', 'name', '-f', '-S'])).toMatchObject({
first: true,
second: false,
});
});
it('deals with string options', () => {
expect(
getOptions(createCommand(), allOptions, ['command', 'name', '--third', 'one'])
).toMatchObject({
third: 'one',
});
});
it('disallows invalid string options', () => {
expect(() =>
getOptions(createCommand(), allOptions, ['command', 'name', '--third', 'random'])
).toThrow(/Unexpected value/);
});
it('allows arbitrary string options when values are not specified', () => {
expect(
getOptions(createCommand(), allOptions, ['command', 'name', '--fourth', 'random'])
).toMatchObject({
fourth: 'random',
});
});
it('deals with multiple string options', () => {
expect(
getOptions(createCommand(), allOptions, ['command', 'name', '--fifth', 'a'])
).toMatchObject({
fifth: ['a'],
});
expect(
getOptions(createCommand(), allOptions, ['command', 'name', '--fifth', 'a', '--fifth', 'b'])
).toMatchObject({
fifth: ['a', 'b'],
});
});
it('disallows invalid multiple string options', () => {
expect(() =>
getOptions(createCommand(), allOptions, ['command', 'name', '--fifth', 'random'])
).toThrow(/Unexpected value/);
});
it('allows arbitrary multiple string options when values are not specified', () => {
expect(
getOptions(createCommand(), allOptions, ['command', 'name', '--sixth', 'random'])
).toMatchObject({
sixth: ['random'],
});
});
});
describe('areOptionsSatisfied', () => {
it('checks each required string option has a value', () => {
expect(
areOptionsSatisfied(allOptions, {
first: true,
second: true,
third: undefined,
fourth: undefined,
fifth: ['a', 'c'],
sixth: [],
})
).toBe(false);
expect(
areOptionsSatisfied(allOptions, {
first: true,
second: true,
third: 'one',
fourth: undefined,
fifth: [],
sixth: [],
})
).toBe(true);
});
});
describe('getCommand', () => {
const { first, second, third, fifth } = allOptions;
it('works with boolean options', () => {
expect(getCommand('node foo', { first, second }, { first: true, second: true })).toBe(
'node foo --first'
);
});
it('works with inverse boolean options', () => {
expect(getCommand('node foo', { first, second }, { first: false, second: false })).toBe(
'node foo --no-second'
);
});
it('works with string options', () => {
expect(getCommand('node foo', { third }, { third: 'one' })).toBe('node foo --third one');
});
it('works with multiple string options', () => {
expect(getCommand('node foo', { fifth }, { fifth: ['a', 'b'] })).toBe(
'node foo --fifth a --fifth b'
);
});
// This is for convenience
it('works with partial options', () => {
expect(getCommand('node foo', allOptions, { third: 'one' })).toBe(
'node foo --no-second --third one'
);
});
it('works with combinations string options', () => {
expect(
getCommand('node foo', allOptions, {
first: true,
second: false,
third: 'one',
fifth: ['a', 'b'],
})
).toBe('node foo --first --no-second --third one --fifth a --fifth b');
});
});
|
5,021 | 0 | petrpan-code/apache/superset/superset-embedded-sdk | petrpan-code/apache/superset/superset-embedded-sdk/src/guestTokenRefresh.test.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import {
REFRESH_TIMING_BUFFER_MS,
getGuestTokenRefreshTiming,
MIN_REFRESH_WAIT_MS,
DEFAULT_TOKEN_EXP_MS,
} from "./guestTokenRefresh";
describe("guest token refresh", () => {
beforeAll(() => {
jest.useFakeTimers("modern"); // "modern" allows us to fake the system time
jest.setSystemTime(new Date("2022-03-03 01:00"));
jest.spyOn(global, "setTimeout");
});
afterAll(() => {
jest.useRealTimers();
});
function makeFakeJWT(claims: any) {
// not a valid jwt, but close enough for this code
const tokenifiedClaims = Buffer.from(JSON.stringify(claims)).toString(
"base64"
);
return `abc.${tokenifiedClaims}.xyz`;
}
it("schedules refresh with an epoch exp", () => {
// exp is in seconds
const ttl = 1300;
const exp = Date.now() / 1000 + ttl;
const fakeToken = makeFakeJWT({ exp });
const timing = getGuestTokenRefreshTiming(fakeToken);
expect(timing).toBeGreaterThan(MIN_REFRESH_WAIT_MS);
expect(timing).toBe(ttl * 1000 - REFRESH_TIMING_BUFFER_MS);
});
it("schedules refresh with an epoch exp containing a decimal", () => {
const ttl = 1300.123;
const exp = Date.now() / 1000 + ttl;
const fakeToken = makeFakeJWT({ exp });
const timing = getGuestTokenRefreshTiming(fakeToken);
expect(timing).toBeGreaterThan(MIN_REFRESH_WAIT_MS);
expect(timing).toBe(ttl * 1000 - REFRESH_TIMING_BUFFER_MS);
});
it("schedules refresh with iso exp", () => {
const exp = new Date("2022-03-03 01:09").toISOString();
const fakeToken = makeFakeJWT({ exp });
const timing = getGuestTokenRefreshTiming(fakeToken);
const expectedTiming = 1000 * 60 * 9 - REFRESH_TIMING_BUFFER_MS;
expect(timing).toBeGreaterThan(MIN_REFRESH_WAIT_MS);
expect(timing).toBe(expectedTiming);
});
it("avoids refresh spam", () => {
const fakeToken = makeFakeJWT({ exp: Date.now() / 1000 });
const timing = getGuestTokenRefreshTiming(fakeToken);
expect(timing).toBe(MIN_REFRESH_WAIT_MS - REFRESH_TIMING_BUFFER_MS);
});
it("uses a default when it cannot parse the date", () => {
const fakeToken = makeFakeJWT({ exp: "invalid date" });
const timing = getGuestTokenRefreshTiming(fakeToken);
expect(timing).toBeGreaterThan(MIN_REFRESH_WAIT_MS);
expect(timing).toBe(DEFAULT_TOKEN_EXP_MS - REFRESH_TIMING_BUFFER_MS);
});
});
|
5,049 | 0 | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/alerts_and_reports/alerts.test.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { ALERT_LIST } from 'cypress/utils/urls';
describe('Alert list view', () => {
before(() => {
cy.visit(ALERT_LIST);
});
it('should load alert lists', () => {
cy.getBySel('listview-table').should('be.visible');
cy.getBySel('sort-header').eq(1).contains('Last run');
cy.getBySel('sort-header').eq(2).contains('Name');
cy.getBySel('sort-header').eq(3).contains('Schedule');
cy.getBySel('sort-header').eq(4).contains('Notification method');
cy.getBySel('sort-header').eq(5).contains('Created by');
cy.getBySel('sort-header').eq(6).contains('Owners');
cy.getBySel('sort-header').eq(7).contains('Modified');
cy.getBySel('sort-header').eq(8).contains('Active');
// TODO Cypress won't recognize the Actions column
// cy.getBySel('sort-header').eq(9).contains('Actions');
});
});
|
5,050 | 0 | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/alerts_and_reports/reports.test.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { REPORT_LIST } from 'cypress/utils/urls';
describe('Report list view', () => {
before(() => {
cy.visit(REPORT_LIST);
});
it('should load report lists', () => {
cy.getBySel('listview-table').should('be.visible');
cy.getBySel('sort-header').eq(1).contains('Last run');
cy.getBySel('sort-header').eq(2).contains('Name');
cy.getBySel('sort-header').eq(3).contains('Schedule');
cy.getBySel('sort-header').eq(4).contains('Notification method');
cy.getBySel('sort-header').eq(5).contains('Created by');
cy.getBySel('sort-header').eq(6).contains('Owners');
cy.getBySel('sort-header').eq(7).contains('Modified');
cy.getBySel('sort-header').eq(8).contains('Active');
// TODO Cypress won't recognize the Actions column
// cy.getBySel('sort-header').eq(9).contains('Actions');
});
});
|
5,051 | 0 | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/chart_list/chartlist.applitools.test.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { CHART_LIST } from 'cypress/utils/urls';
describe('charts list view', () => {
beforeEach(() => {
cy.visit(CHART_LIST);
});
afterEach(() => {
cy.eyesClose();
});
it('should load the Charts list', () => {
cy.get('[aria-label="list-view"]').click();
cy.eyesOpen({
testName: 'Charts list-view',
});
cy.eyesCheckWindow('Charts list-view loaded');
});
it('should load the Charts card list', () => {
cy.get('[aria-label="card-view"]').click();
cy.eyesOpen({
testName: 'Charts card-view',
});
cy.eyesCheckWindow('Charts card-view loaded');
});
});
|
5,052 | 0 | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/chart_list/filter.test.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { CHART_LIST } from 'cypress/utils/urls';
import { setGridMode, clearAllInputs } from 'cypress/utils';
import { setFilter } from '../explore/utils';
describe('Charts filters', () => {
before(() => {
cy.visit(CHART_LIST);
setGridMode('card');
});
beforeEach(() => {
clearAllInputs();
});
it('should allow filtering by "Owner"', () => {
setFilter('Owner', 'alpha user');
setFilter('Owner', 'admin user');
});
it('should allow filtering by "Created by" correctly', () => {
setFilter('Created by', 'alpha user');
setFilter('Created by', 'admin user');
});
it('should allow filtering by "Chart type" correctly', () => {
setFilter('Chart type', 'Area Chart (legacy)');
setFilter('Chart type', 'Bubble Chart');
});
it('should allow filtering by "Dataset" correctly', () => {
setFilter('Dataset', 'energy_usage');
setFilter('Dataset', 'unicode_test');
});
it('should allow filtering by "Dashboards" correctly', () => {
setFilter('Dashboards', 'Unicode Test');
setFilter('Dashboards', 'Tabbed Dashboard');
});
});
|
5,053 | 0 | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/chart_list/list.test.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { CHART_LIST } from 'cypress/utils/urls';
import { setGridMode, toggleBulkSelect } from 'cypress/utils';
import {
setFilter,
interceptBulkDelete,
interceptUpdate,
interceptDelete,
visitSampleChartFromList,
saveChartToDashboard,
interceptFiltering,
} from '../explore/utils';
import { interceptGet as interceptDashboardGet } from '../dashboard/utils';
function orderAlphabetical() {
setFilter('Sort', 'Alphabetical');
}
function openProperties() {
cy.get('[aria-label="more-vert"]').eq(1).click();
cy.getBySel('chart-list-edit-option').click();
}
function openMenu() {
cy.get('[aria-label="more-vert"]').eq(1).click();
}
function confirmDelete() {
cy.getBySel('delete-modal-input').type('DELETE');
cy.getBySel('modal-confirm-button').click();
}
function visitChartList() {
interceptFiltering();
cy.visit(CHART_LIST);
cy.wait('@filtering');
}
describe('Charts list', () => {
describe.skip('Cross-referenced dashboards', () => {
beforeEach(() => {
cy.createSampleDashboards([0, 1, 2, 3]);
cy.createSampleCharts([0]);
visitChartList();
});
it('should show the cross-referenced dashboards in the table cell', () => {
interceptDashboardGet();
cy.getBySel('table-row')
.first()
.find('[data-test="table-row-cell"]')
.find('[data-test="crosslinks"]')
.should('be.empty');
cy.getBySel('table-row')
.eq(10)
.find('[data-test="table-row-cell"]')
.find('[data-test="crosslinks"]')
.contains('Supported Charts Dashboard')
.invoke('removeAttr', 'target')
.click();
cy.wait('@get');
});
it('should show the newly added dashboards in a tooltip', () => {
interceptDashboardGet();
visitSampleChartFromList('1 - Sample chart');
saveChartToDashboard('1 - Sample dashboard');
saveChartToDashboard('2 - Sample dashboard');
saveChartToDashboard('3 - Sample dashboard');
visitChartList();
cy.getBySel('count-crosslinks').should('be.visible');
cy.getBySel('crosslinks')
.first()
.trigger('mouseover')
.then(() => {
cy.get('.ant-tooltip')
.contains('3 - Sample dashboard')
.invoke('removeAttr', 'target')
.click();
cy.wait('@get');
});
});
});
describe('list mode', () => {
before(() => {
cy.createSampleDashboards([0, 1, 2, 3]);
cy.createSampleCharts([0]);
visitChartList();
setGridMode('list');
});
it('should load rows in list mode', () => {
cy.getBySel('listview-table').should('be.visible');
cy.getBySel('sort-header').eq(1).contains('Chart');
cy.getBySel('sort-header').eq(2).contains('Visualization type');
cy.getBySel('sort-header').eq(3).contains('Dataset');
// cy.getBySel('sort-header').eq(4).contains('Dashboards added to');
cy.getBySel('sort-header').eq(4).contains('Modified by');
cy.getBySel('sort-header').eq(5).contains('Last modified');
cy.getBySel('sort-header').eq(6).contains('Created by');
cy.getBySel('sort-header').eq(7).contains('Actions');
});
it('should sort correctly in list mode', () => {
cy.getBySel('sort-header').eq(1).click();
cy.getBySel('table-row').first().contains('% Rural');
cy.getBySel('sort-header').eq(1).click();
cy.getBySel('table-row').first().contains("World's Population");
cy.getBySel('sort-header').eq(1).click();
});
it('should bulk select in list mode', () => {
toggleBulkSelect();
cy.get('#header-toggle-all').click();
cy.get('[aria-label="checkbox-on"]').should('have.length', 26);
cy.getBySel('bulk-select-copy').contains('25 Selected');
cy.getBySel('bulk-select-action')
.should('have.length', 2)
.then($btns => {
expect($btns).to.contain('Delete');
expect($btns).to.contain('Export');
});
cy.getBySel('bulk-select-deselect-all').click();
cy.get('[aria-label="checkbox-on"]').should('have.length', 0);
cy.getBySel('bulk-select-copy').contains('0 Selected');
cy.getBySel('bulk-select-action').should('not.exist');
});
});
describe('card mode', () => {
before(() => {
visitChartList();
setGridMode('card');
});
it('should load rows in card mode', () => {
cy.getBySel('listview-table').should('not.exist');
cy.getBySel('styled-card').should('have.length', 25);
});
it('should bulk select in card mode', () => {
toggleBulkSelect();
cy.getBySel('styled-card').click({ multiple: true });
cy.getBySel('bulk-select-copy').contains('25 Selected');
cy.getBySel('bulk-select-action')
.should('have.length', 2)
.then($btns => {
expect($btns).to.contain('Delete');
expect($btns).to.contain('Export');
});
cy.getBySel('bulk-select-deselect-all').click();
cy.getBySel('bulk-select-copy').contains('0 Selected');
cy.getBySel('bulk-select-action').should('not.exist');
});
it('should sort in card mode', () => {
orderAlphabetical();
cy.getBySel('styled-card').first().contains('% Rural');
});
});
describe('common actions', () => {
beforeEach(() => {
cy.createSampleCharts([0, 1, 2, 3]);
visitChartList();
});
it('should allow to favorite/unfavorite', () => {
cy.intercept({ url: `/api/v1/chart/*/favorites/`, method: 'POST' }).as(
'select',
);
cy.intercept({ url: `/api/v1/chart/*/favorites/`, method: 'DELETE' }).as(
'unselect',
);
setGridMode('card');
orderAlphabetical();
cy.getBySel('styled-card').first().contains('% Rural');
cy.getBySel('styled-card')
.first()
.find("[aria-label='favorite-unselected']")
.click();
cy.wait('@select');
cy.getBySel('styled-card')
.first()
.find("[aria-label='favorite-selected']")
.click();
cy.wait('@unselect');
cy.getBySel('styled-card')
.first()
.find("[aria-label='favorite-selected']")
.should('not.exist');
});
it('should bulk delete correctly', () => {
interceptBulkDelete();
toggleBulkSelect();
// bulk deletes in card-view
setGridMode('card');
orderAlphabetical();
cy.getBySel('styled-card').eq(1).contains('1 - Sample chart').click();
cy.getBySel('styled-card').eq(2).contains('2 - Sample chart').click();
cy.getBySel('bulk-select-action').eq(0).contains('Delete').click();
confirmDelete();
cy.wait('@bulkDelete');
cy.getBySel('styled-card')
.eq(1)
.should('not.contain', '1 - Sample chart');
cy.getBySel('styled-card')
.eq(2)
.should('not.contain', '2 - Sample chart');
// bulk deletes in list-view
setGridMode('list');
cy.getBySel('table-row').eq(1).contains('3 - Sample chart');
cy.getBySel('table-row').eq(2).contains('4 - Sample chart');
cy.get('[data-test="table-row"] input[type="checkbox"]').eq(1).click();
cy.get('[data-test="table-row"] input[type="checkbox"]').eq(2).click();
cy.getBySel('bulk-select-action').eq(0).contains('Delete').click();
confirmDelete();
cy.wait('@bulkDelete');
cy.getBySel('table-row').eq(1).should('not.contain', '3 - Sample chart');
cy.getBySel('table-row').eq(2).should('not.contain', '4 - Sample chart');
});
it('should delete correctly', () => {
interceptDelete();
// deletes in card-view
setGridMode('card');
orderAlphabetical();
cy.getBySel('styled-card').eq(1).contains('1 - Sample chart');
openMenu();
cy.getBySel('chart-list-delete-option').click();
confirmDelete();
cy.wait('@delete');
cy.getBySel('styled-card')
.eq(1)
.should('not.contain', '1 - Sample chart');
// deletes in list-view
setGridMode('list');
cy.getBySel('table-row').eq(1).contains('2 - Sample chart');
cy.getBySel('trash').eq(1).click();
confirmDelete();
cy.wait('@delete');
cy.getBySel('table-row').eq(1).should('not.contain', '2 - Sample chart');
});
it('should edit correctly', () => {
interceptUpdate();
// edits in card-view
setGridMode('card');
orderAlphabetical();
cy.getBySel('styled-card').eq(1).contains('1 - Sample chart');
// change title
openProperties();
cy.getBySel('properties-modal-name-input').type(' | EDITED');
cy.get('button:contains("Save")').click();
cy.wait('@update');
cy.getBySel('styled-card').eq(1).contains('1 - Sample chart | EDITED');
// edits in list-view
setGridMode('list');
cy.getBySel('edit-alt').eq(1).click();
cy.getBySel('properties-modal-name-input')
.clear()
.type('1 - Sample chart');
cy.get('button:contains("Save")').click();
cy.wait('@update');
cy.getBySel('table-row').eq(1).contains('1 - Sample chart');
});
});
});
|
5,054 | 0 | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/dashboard/_skip.controls.test.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import {
waitForChartLoad,
ChartSpec,
getChartAliasesBySpec,
} from 'cypress/utils';
import { WORLD_HEALTH_DASHBOARD } from 'cypress/utils/urls';
import { WORLD_HEALTH_CHARTS } from './utils';
import { isLegacyResponse } from '../../utils/vizPlugins';
describe.skip('Dashboard top-level controls', () => {
beforeEach(() => {
cy.visit(WORLD_HEALTH_DASHBOARD);
});
// flaky test
it('should allow chart level refresh', () => {
const mapSpec = WORLD_HEALTH_CHARTS.find(
({ viz }) => viz === 'world_map',
) as ChartSpec;
waitForChartLoad(mapSpec).then(gridComponent => {
const mapId = gridComponent.attr('data-test-chart-id');
cy.get('[data-test="grid-container"]').find('.world_map').should('exist');
cy.get(`#slice_${mapId}-controls`).click();
cy.get(`[data-test="slice_${mapId}-menu"]`)
.find('[data-test="refresh-chart-menu-item"]')
.click({ force: true });
// likely cause for flakiness:
// The query completes before this assertion happens.
// Solution: pause the network before clicking, assert, then unpause network.
cy.get('[data-test="refresh-chart-menu-item"]').should(
'have.class',
'ant-dropdown-menu-item-disabled',
);
waitForChartLoad(mapSpec);
cy.get('[data-test="refresh-chart-menu-item"]').should(
'not.have.class',
'ant-dropdown-menu-item-disabled',
);
});
});
it('should allow dashboard level force refresh', () => {
// when charts are not start loading, for example, under a secondary tab,
// should allow force refresh
WORLD_HEALTH_CHARTS.forEach(waitForChartLoad);
getChartAliasesBySpec(WORLD_HEALTH_CHARTS).then(aliases => {
cy.get('[aria-label="more-horiz"]').click();
cy.get('[data-test="refresh-dashboard-menu-item"]').should(
'not.have.class',
'ant-dropdown-menu-item-disabled',
);
cy.get('[data-test="refresh-dashboard-menu-item"]').click({
force: true,
});
cy.get('[data-test="refresh-dashboard-menu-item"]').should(
'have.class',
'ant-dropdown-menu-item-disabled',
);
// wait all charts force refreshed.
cy.wait(aliases).then(xhrs => {
xhrs.forEach(async ({ response, request }) => {
const responseBody = response?.body;
const isCached = isLegacyResponse(responseBody)
? responseBody.is_cached
: responseBody.result[0].is_cached;
// request url should indicate force-refresh operation
expect(request.url).to.have.string('force=true');
// is_cached in response should be false
expect(isCached).to.equal(false);
});
});
});
cy.get('[aria-label="more-horiz"]').click();
cy.get('[data-test="refresh-dashboard-menu-item"]').and(
'not.have.class',
'ant-dropdown-menu-item-disabled',
);
});
});
|
5,055 | 0 | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/dashboard/_skip.filter.test.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import {
isLegacyResponse,
parsePostForm,
getChartAliasesBySpec,
waitForChartLoad,
} from 'cypress/utils';
import { WORLD_HEALTH_DASHBOARD } from 'cypress/utils/urls';
import { WORLD_HEALTH_CHARTS } from './utils';
describe.skip('Dashboard filter', () => {
before(() => {
cy.visit(WORLD_HEALTH_DASHBOARD);
});
it('should apply filter', () => {
WORLD_HEALTH_CHARTS.forEach(waitForChartLoad);
getChartAliasesBySpec(
WORLD_HEALTH_CHARTS.filter(({ viz }) => viz !== 'filter_box'),
).then(nonFilterChartAliases => {
cy.get('.Select__placeholder:first').click();
// should show the filter indicator
cy.get('span[aria-label="filter"]:visible').should(nodes => {
expect(nodes.length).to.least(9);
});
cy.get('.Select__control:first input[type=text]').type('So', {
force: true,
delay: 100,
});
cy.get('.Select__menu').first().contains('South Asia').click();
// should still have all filter indicators
cy.get('span[aria-label="filter"]:visible').should(nodes => {
expect(nodes.length).to.least(9);
});
cy.get('.filter_box button').click({ force: true });
cy.wait(nonFilterChartAliases).then(requests => {
requests.forEach(({ response, request }) => {
const responseBody = response?.body;
let requestFilter;
if (isLegacyResponse(responseBody)) {
const requestFormData = parsePostForm(request.body);
const requestParams = JSON.parse(
requestFormData.form_data as string,
);
requestFilter = requestParams.extra_filters[0];
} else {
requestFilter = request.body.queries[0].filters[0];
}
expect(requestFilter).deep.eq({
col: 'region',
op: 'IN',
val: ['South Asia'],
});
});
});
});
// TODO add test with South Asia{enter} type action to select filter
});
});
|
5,056 | 0 | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/dashboard/_skip.key_value.test.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import qs from 'querystringify';
import { waitForChartLoad } from 'cypress/utils';
import { WORLD_HEALTH_DASHBOARD } from 'cypress/utils/urls';
import { WORLD_HEALTH_CHARTS } from './utils';
interface QueryString {
native_filters_key: string;
}
describe.skip('nativefilter url param key', () => {
// const urlParams = { param1: '123', param2: 'abc' };
let initialFilterKey: string;
it('should have cachekey in nativefilter param', () => {
// things in `before` will not retry and the `waitForChartLoad` check is
// especially flaky and may need more retries
cy.visit(WORLD_HEALTH_DASHBOARD);
WORLD_HEALTH_CHARTS.forEach(waitForChartLoad);
cy.wait(1000); // wait for key to be published (debounced)
cy.location().then(loc => {
const queryParams = qs.parse(loc.search) as QueryString;
expect(typeof queryParams.native_filters_key).eq('string');
});
});
it('should have different key when page reloads', () => {
cy.visit(WORLD_HEALTH_DASHBOARD);
WORLD_HEALTH_CHARTS.forEach(waitForChartLoad);
cy.wait(1000); // wait for key to be published (debounced)
cy.location().then(loc => {
const queryParams = qs.parse(loc.search) as QueryString;
expect(queryParams.native_filters_key).not.equal(initialFilterKey);
});
});
});
|
5,057 | 0 | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/dashboard/_skip.url_params.test.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { parsePostForm, JsonObject, waitForChartLoad } from 'cypress/utils';
import { WORLD_HEALTH_DASHBOARD } from 'cypress/utils/urls';
import { WORLD_HEALTH_CHARTS } from './utils';
describe.skip('Dashboard form data', () => {
const urlParams = { param1: '123', param2: 'abc' };
before(() => {
cy.visit(WORLD_HEALTH_DASHBOARD, { qs: urlParams });
});
it('should apply url params to slice requests', () => {
cy.intercept('/api/v1/chart/data?*', request => {
// TODO: export url params to chart data API
request.body.queries.forEach((query: { url_params: JsonObject }) => {
expect(query.url_params).deep.eq(urlParams);
});
});
cy.intercept('/superset/explore_json/*', request => {
const requestParams = JSON.parse(
parsePostForm(request.body).form_data as string,
);
expect(requestParams.url_params).deep.eq(urlParams);
});
WORLD_HEALTH_CHARTS.forEach(waitForChartLoad);
});
});
|
5,059 | 0 | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/dashboard/dashboard.applitools.test.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { WORLD_HEALTH_DASHBOARD } from 'cypress/utils/urls';
import { waitForChartLoad } from 'cypress/utils';
import { WORLD_HEALTH_CHARTS } from './utils';
describe('Dashboard load', () => {
beforeEach(() => {
cy.visit(WORLD_HEALTH_DASHBOARD);
WORLD_HEALTH_CHARTS.forEach(waitForChartLoad);
});
afterEach(() => {
cy.eyesClose();
});
it('should load the Dashboard', () => {
cy.eyesOpen({
testName: 'Dashboard page',
});
cy.eyesCheckWindow('Dashboard loaded');
});
it('should load the Dashboard in edit mode', () => {
cy.get('.header-with-actions')
.find('[aria-label="Edit dashboard"]')
.click();
// wait for a chart to appear
cy.get('[data-test="grid-container"]').find('.box_plot', {
timeout: 10000,
});
cy.eyesOpen({
testName: 'Dashboard edit mode',
});
cy.eyesCheckWindow('Dashboard edit mode loaded');
});
});
|
5,060 | 0 | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/dashboard/drillby.test.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// eslint-disable-next-line import/no-extraneous-dependencies
import { Interception } from 'cypress/types/net-stubbing';
import { waitForChartLoad } from 'cypress/utils';
import { SUPPORTED_CHARTS_DASHBOARD } from 'cypress/utils/urls';
import {
openTopLevelTab,
SUPPORTED_TIER1_CHARTS,
SUPPORTED_TIER2_CHARTS,
} from './utils';
import {
interceptExploreJson,
interceptV1ChartData,
interceptFormDataKey,
} from '../explore/utils';
const closeModal = () => {
cy.get('body').then($body => {
if ($body.find('[data-test="close-drill-by-modal"]').length) {
cy.getBySel('close-drill-by-modal').click({ force: true });
}
});
};
const openTableContextMenu = (
cellContent: string,
tableSelector = "[data-test-viz-type='table']",
) => {
cy.get(tableSelector)
.scrollIntoView()
.contains(cellContent)
.first()
.rightclick();
};
const drillBy = (targetDrillByColumn: string, isLegacy = false) => {
if (isLegacy) {
interceptExploreJson('legacyData');
} else {
interceptV1ChartData();
}
cy.get('.ant-dropdown:not(.ant-dropdown-hidden)')
.first()
.find("[role='menu'] [role='menuitem'] [title='Drill by']")
.trigger('mouseover');
cy.get(
'.ant-dropdown-menu-submenu:not(.ant-dropdown-menu-hidden) [data-test="drill-by-submenu"]',
)
.find('[role="menuitem"]')
.contains(new RegExp(`^${targetDrillByColumn}$`))
.first()
.click({ force: true });
if (isLegacy) {
return cy.wait('@legacyData');
}
return cy.wait('@v1Data');
};
const verifyExpectedFormData = (
interceptedRequest: Interception,
expectedFormData: Record<string, any>,
) => {
const actualFormData = interceptedRequest.request.body?.form_data;
Object.entries(expectedFormData).forEach(([key, val]) => {
expect(actualFormData?.[key]).to.eql(val);
});
};
const testEchart = (
vizType: string,
chartName: string,
drillClickCoordinates: [[number, number], [number, number]],
furtherDrillDimension = 'name',
) => {
cy.get(`[data-test-viz-type='${vizType}'] canvas`).then($canvas => {
// click 'boy'
cy.wrap($canvas)
.scrollIntoView()
.trigger(
'mouseover',
drillClickCoordinates[0][0],
drillClickCoordinates[0][1],
)
.rightclick(drillClickCoordinates[0][0], drillClickCoordinates[0][1]);
drillBy('state').then(intercepted => {
verifyExpectedFormData(intercepted, {
groupby: ['state'],
adhoc_filters: [
{
clause: 'WHERE',
comparator: 'boy',
expressionType: 'SIMPLE',
operator: '==',
operatorId: 'EQUALS',
subject: 'gender',
},
],
});
});
cy.getBySel(`"Drill by: ${chartName}-modal"`).as('drillByModal');
cy.get('@drillByModal')
.find('.draggable-trigger')
.should('contain', chartName);
cy.get('@drillByModal')
.find('.ant-breadcrumb')
.should('be.visible')
.and('contain', 'gender (boy)')
.and('contain', '/')
.and('contain', 'state');
cy.get('@drillByModal')
.find('[data-test="drill-by-chart"]')
.should('be.visible');
// further drill
cy.get(`[data-test="drill-by-chart"] canvas`).then($canvas => {
// click 'other'
cy.wrap($canvas)
.scrollIntoView()
.trigger(
'mouseover',
drillClickCoordinates[1][0],
drillClickCoordinates[1][1],
)
.rightclick(drillClickCoordinates[1][0], drillClickCoordinates[1][1]);
drillBy(furtherDrillDimension).then(intercepted => {
verifyExpectedFormData(intercepted, {
groupby: [furtherDrillDimension],
adhoc_filters: [
{
clause: 'WHERE',
comparator: 'boy',
expressionType: 'SIMPLE',
operator: '==',
operatorId: 'EQUALS',
subject: 'gender',
},
{
clause: 'WHERE',
comparator: 'other',
expressionType: 'SIMPLE',
operator: '==',
operatorId: 'EQUALS',
subject: 'state',
},
],
});
});
cy.get('@drillByModal')
.find('[data-test="drill-by-chart"]')
.should('be.visible');
// undo - back to drill by state
interceptV1ChartData('drillByUndo');
cy.get('@drillByModal')
.find('.ant-breadcrumb')
.should('be.visible')
.and('contain', 'gender (boy)')
.and('contain', '/')
.and('contain', 'state (other)')
.and('contain', furtherDrillDimension)
.contains('state (other)')
.click();
cy.wait('@drillByUndo').then(intercepted => {
verifyExpectedFormData(intercepted, {
groupby: ['state'],
adhoc_filters: [
{
clause: 'WHERE',
comparator: 'boy',
expressionType: 'SIMPLE',
operator: '==',
operatorId: 'EQUALS',
subject: 'gender',
},
],
});
});
cy.get('@drillByModal')
.find('.ant-breadcrumb')
.should('be.visible')
.and('contain', 'gender (boy)')
.and('contain', '/')
.and('not.contain', 'state (other)')
.and('not.contain', furtherDrillDimension)
.and('contain', 'state');
cy.get('@drillByModal')
.find('[data-test="drill-by-chart"]')
.should('be.visible');
});
});
};
describe('Drill by modal', () => {
beforeEach(() => {
closeModal();
});
before(() => {
cy.visit(SUPPORTED_CHARTS_DASHBOARD);
});
describe('Modal actions + Table', () => {
before(() => {
closeModal();
openTopLevelTab('Tier 1');
SUPPORTED_TIER1_CHARTS.forEach(waitForChartLoad);
});
it('opens the modal from the context menu', () => {
openTableContextMenu('boy');
drillBy('state').then(intercepted => {
verifyExpectedFormData(intercepted, {
groupby: ['state'],
adhoc_filters: [
{
clause: 'WHERE',
comparator: 'boy',
expressionType: 'SIMPLE',
operator: '==',
operatorId: 'EQUALS',
subject: 'gender',
},
],
});
});
cy.getBySel('"Drill by: Table-modal"').as('drillByModal');
cy.get('@drillByModal')
.find('.draggable-trigger')
.should('contain', 'Drill by: Table');
cy.get('@drillByModal')
.find('[data-test="metadata-bar"]')
.should('be.visible');
cy.get('@drillByModal')
.find('.ant-breadcrumb')
.should('be.visible')
.and('contain', 'gender (boy)')
.and('contain', '/')
.and('contain', 'state');
cy.get('@drillByModal')
.find('[data-test="drill-by-chart"]')
.should('be.visible')
.and('contain', 'state')
.and('contain', 'sum__num');
// further drilling
openTableContextMenu('CA', '[data-test="drill-by-chart"]');
drillBy('name').then(intercepted => {
verifyExpectedFormData(intercepted, {
groupby: ['name'],
adhoc_filters: [
{
clause: 'WHERE',
comparator: 'boy',
expressionType: 'SIMPLE',
operator: '==',
operatorId: 'EQUALS',
subject: 'gender',
},
{
clause: 'WHERE',
comparator: 'CA',
expressionType: 'SIMPLE',
operator: '==',
operatorId: 'EQUALS',
subject: 'state',
},
],
});
});
cy.get('@drillByModal')
.find('[data-test="drill-by-chart"]')
.should('be.visible')
.and('not.contain', 'state')
.and('contain', 'name')
.and('contain', 'sum__num');
// undo - back to drill by state
interceptV1ChartData('drillByUndo');
interceptFormDataKey();
cy.get('@drillByModal')
.find('.ant-breadcrumb')
.should('be.visible')
.and('contain', 'gender (boy)')
.and('contain', '/')
.and('contain', 'state (CA)')
.and('contain', 'name')
.contains('state (CA)')
.click();
cy.wait('@drillByUndo').then(intercepted => {
verifyExpectedFormData(intercepted, {
groupby: ['state'],
adhoc_filters: [
{
clause: 'WHERE',
comparator: 'boy',
expressionType: 'SIMPLE',
operator: '==',
operatorId: 'EQUALS',
subject: 'gender',
},
],
});
});
cy.get('@drillByModal')
.find('[data-test="drill-by-chart"]')
.should('be.visible')
.and('not.contain', 'name')
.and('contain', 'state')
.and('contain', 'sum__num');
cy.get('@drillByModal')
.find('.ant-breadcrumb')
.should('be.visible')
.and('contain', 'gender (boy)')
.and('contain', '/')
.and('not.contain', 'state (CA)')
.and('not.contain', 'name')
.and('contain', 'state');
cy.get('@drillByModal')
.find('[data-test="drill-by-display-toggle"]')
.contains('Table')
.click();
cy.getBySel('drill-by-chart').should('not.exist');
cy.get('@drillByModal')
.find('[data-test="drill-by-results-table"]')
.should('be.visible');
cy.wait('@formDataKey').then(intercept => {
cy.get('@drillByModal')
.contains('Edit chart')
.should('have.attr', 'href')
.and(
'contain',
`/explore/?form_data_key=${intercept.response?.body?.key}`,
);
});
});
});
describe('Tier 1 charts', () => {
before(() => {
closeModal();
openTopLevelTab('Tier 1');
SUPPORTED_TIER1_CHARTS.forEach(waitForChartLoad);
});
it('Pivot Table', () => {
openTableContextMenu('boy', "[data-test-viz-type='pivot_table_v2']");
drillBy('name').then(intercepted => {
verifyExpectedFormData(intercepted, {
groupbyRows: ['state'],
groupbyColumns: ['name'],
adhoc_filters: [
{
clause: 'WHERE',
comparator: 'boy',
expressionType: 'SIMPLE',
operator: '==',
operatorId: 'EQUALS',
subject: 'gender',
},
],
});
});
cy.getBySel('"Drill by: Pivot Table-modal"').as('drillByModal');
cy.get('@drillByModal')
.find('.draggable-trigger')
.should('contain', 'Drill by: Pivot Table');
cy.get('@drillByModal')
.find('.ant-breadcrumb')
.should('be.visible')
.and('contain', 'gender (boy)')
.and('contain', '/')
.and('contain', 'name');
cy.get('@drillByModal')
.find('[data-test="drill-by-chart"]')
.should('be.visible')
.and('contain', 'state')
.and('contain', 'name')
.and('contain', 'sum__num')
.and('not.contain', 'Gender');
openTableContextMenu('CA', '[data-test="drill-by-chart"]');
drillBy('ds').then(intercepted => {
verifyExpectedFormData(intercepted, {
groupbyColumns: ['name'],
groupbyRows: ['ds'],
adhoc_filters: [
{
clause: 'WHERE',
comparator: 'boy',
expressionType: 'SIMPLE',
operator: '==',
operatorId: 'EQUALS',
subject: 'gender',
},
{
clause: 'WHERE',
comparator: 'CA',
expressionType: 'SIMPLE',
operator: '==',
operatorId: 'EQUALS',
subject: 'state',
},
],
});
});
cy.get('@drillByModal')
.find('[data-test="drill-by-chart"]')
.should('be.visible')
.and('contain', 'name')
.and('contain', 'ds')
.and('contain', 'sum__num')
.and('not.contain', 'state');
interceptV1ChartData('drillByUndo');
cy.get('@drillByModal')
.find('.ant-breadcrumb')
.should('be.visible')
.and('contain', 'gender (boy)')
.and('contain', '/')
.and('contain', 'name (CA)')
.and('contain', 'ds')
.contains('name (CA)')
.click();
cy.wait('@drillByUndo').then(intercepted => {
verifyExpectedFormData(intercepted, {
groupbyRows: ['state'],
groupbyColumns: ['name'],
adhoc_filters: [
{
clause: 'WHERE',
comparator: 'boy',
expressionType: 'SIMPLE',
operator: '==',
operatorId: 'EQUALS',
subject: 'gender',
},
],
});
});
cy.get('@drillByModal')
.find('[data-test="drill-by-chart"]')
.should('be.visible')
.and('not.contain', 'ds')
.and('contain', 'state')
.and('contain', 'name')
.and('contain', 'sum__num');
cy.get('@drillByModal')
.find('.ant-breadcrumb')
.should('be.visible')
.and('contain', 'gender (boy)')
.and('contain', '/')
.and('not.contain', 'name (CA)')
.and('not.contain', 'ds')
.and('contain', 'name');
});
it('Line chart', () => {
testEchart('echarts_timeseries_line', 'Time-Series Line Chart', [
[70, 93],
[70, 93],
]);
});
it('Area Chart', () => {
testEchart('echarts_area', 'Time-Series Area Chart', [
[70, 93],
[70, 93],
]);
});
it('Time-Series Scatter Chart', () => {
testEchart('echarts_timeseries_scatter', 'Time-Series Scatter Chart', [
[70, 93],
[70, 93],
]);
});
it('Time-Series Bar Chart V2', () => {
testEchart('echarts_timeseries_bar', 'Time-Series Bar Chart V2', [
[70, 94],
[362, 68],
]);
});
it('Pie Chart', () => {
testEchart('pie', 'Pie Chart', [
[243, 167],
[534, 248],
]);
});
});
describe('Tier 2 charts', () => {
before(() => {
closeModal();
openTopLevelTab('Tier 2');
SUPPORTED_TIER2_CHARTS.forEach(waitForChartLoad);
});
it('Box Plot Chart', () => {
testEchart(
'box_plot',
'Box Plot Chart',
[
[139, 277],
[787, 441],
],
'ds',
);
});
it('Time-Series Generic Chart', () => {
testEchart('echarts_timeseries', 'Time-Series Generic Chart', [
[70, 93],
[70, 93],
]);
});
it('Time-Series Smooth Line Chart', () => {
testEchart('echarts_timeseries_smooth', 'Time-Series Smooth Line Chart', [
[70, 93],
[70, 93],
]);
});
it('Time-Series Step Line Chart', () => {
testEchart('echarts_timeseries_step', 'Time-Series Step Line Chart', [
[70, 93],
[70, 93],
]);
});
it('Funnel Chart', () => {
testEchart('funnel', 'Funnel Chart', [
[154, 80],
[421, 39],
]);
});
it('Gauge Chart', () => {
testEchart('gauge_chart', 'Gauge Chart', [
[151, 95],
[300, 143],
]);
});
it('Radar Chart', () => {
testEchart('radar', 'Radar Chart', [
[182, 49],
[423, 91],
]);
});
it('Treemap V2 Chart', () => {
testEchart('treemap_v2', 'Treemap V2 Chart', [
[145, 84],
[220, 105],
]);
});
it('Mixed Chart', () => {
cy.get('[data-test-viz-type="mixed_timeseries"] canvas').then($canvas => {
// click 'boy'
cy.wrap($canvas)
.scrollIntoView()
.trigger('mouseover', 70, 93)
.rightclick(70, 93);
drillBy('name').then(intercepted => {
const { queries } = intercepted.request.body;
expect(queries[0].columns).to.eql(['name']);
expect(queries[0].filters).to.eql([
{ col: 'gender', op: '==', val: 'boy' },
]);
expect(queries[1].columns).to.eql(['state']);
expect(queries[1].filters).to.eql([]);
});
cy.getBySel('"Drill by: Mixed Chart-modal"').as('drillByModal');
cy.get('@drillByModal')
.find('.draggable-trigger')
.should('contain', 'Mixed Chart');
cy.get('@drillByModal')
.find('.ant-breadcrumb')
.should('be.visible')
.and('contain', 'gender (boy)')
.and('contain', '/')
.and('contain', 'name');
cy.get('@drillByModal')
.find('[data-test="drill-by-chart"]')
.should('be.visible');
// further drill
cy.get(`[data-test="drill-by-chart"] canvas`).then($canvas => {
// click second query
cy.wrap($canvas)
.scrollIntoView()
.trigger('mouseover', 246, 114)
.rightclick(246, 114);
drillBy('ds').then(intercepted => {
const { queries } = intercepted.request.body;
expect(queries[0].columns).to.eql(['name']);
expect(queries[0].filters).to.eql([
{ col: 'gender', op: '==', val: 'boy' },
]);
expect(queries[1].columns).to.eql(['ds']);
expect(queries[1].filters).to.eql([
{ col: 'state', op: '==', val: 'other' },
]);
});
cy.get('@drillByModal')
.find('[data-test="drill-by-chart"]')
.should('be.visible');
// undo - back to drill by state
interceptV1ChartData('drillByUndo');
cy.get('@drillByModal')
.find('.ant-breadcrumb')
.should('be.visible')
.and('contain', 'gender (boy)')
.and('contain', '/')
.and('contain', 'name (other)')
.and('contain', 'ds')
.contains('name (other)')
.click();
cy.wait('@drillByUndo').then(intercepted => {
const { queries } = intercepted.request.body;
expect(queries[0].columns).to.eql(['name']);
expect(queries[0].filters).to.eql([
{ col: 'gender', op: '==', val: 'boy' },
]);
expect(queries[1].columns).to.eql(['state']);
expect(queries[1].filters).to.eql([]);
});
cy.get('@drillByModal')
.find('.ant-breadcrumb')
.should('be.visible')
.and('contain', 'gender (boy)')
.and('contain', '/')
.and('not.contain', 'name (other)')
.and('not.contain', 'ds')
.and('contain', 'name');
cy.get('@drillByModal')
.find('[data-test="drill-by-chart"]')
.should('be.visible');
});
});
});
});
});
|
5,061 | 0 | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/dashboard/drilltodetail.test.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { waitForChartLoad } from 'cypress/utils';
import { SUPPORTED_CHARTS_DASHBOARD } from 'cypress/utils/urls';
import {
openTopLevelTab,
SUPPORTED_TIER1_CHARTS,
SUPPORTED_TIER2_CHARTS,
} from './utils';
function interceptSamples() {
cy.intercept(`/datasource/samples*`).as('samples');
}
function openModalFromMenu(chartType: string) {
interceptSamples();
cy.get(
`[data-test-viz-type='${chartType}'] [aria-label='More Options']`,
).click();
cy.get('.ant-dropdown')
.not('.ant-dropdown-hidden')
.find("[role='menu'] [role='menuitem']")
.eq(5)
.should('contain', 'Drill to detail')
.click();
cy.wait('@samples');
}
function openModalFromChartContext(targetMenuItem: string) {
interceptSamples();
cy.wait(500);
if (targetMenuItem.startsWith('Drill to detail by')) {
cy.get('.ant-dropdown')
.not('.ant-dropdown-hidden')
.first()
.find("[role='menu'] [role='menuitem'] [title='Drill to detail by']")
.trigger('mouseover');
cy.wait(500);
cy.get('[data-test="drill-to-detail-by-submenu"]')
.not('.ant-dropdown-menu-hidden [data-test="drill-to-detail-by-submenu"]')
.find('[role="menuitem"]')
.contains(new RegExp(`^${targetMenuItem}$`))
.first()
.click();
} else {
cy.get('.ant-dropdown')
.not('.ant-dropdown-hidden')
.first()
.find("[role='menu'] [role='menuitem']")
.contains(new RegExp(`^${targetMenuItem}$`))
.first()
.click();
}
cy.getBySel('metadata-bar').should('be.visible');
cy.wait('@samples');
}
function closeModal() {
cy.get('body').then($body => {
if ($body.find('[data-test="close-drilltodetail-modal"]').length) {
cy.getBySel('close-drilltodetail-modal').click({ force: true });
}
});
}
function testTimeChart(vizType: string) {
interceptSamples();
cy.get(`[data-test-viz-type='${vizType}'] canvas`).then($canvas => {
cy.wrap($canvas)
.scrollIntoView()
.trigger('mousemove', 70, 93)
.rightclick(70, 93);
openModalFromChartContext('Drill to detail by 1965');
cy.getBySel('filter-val').should('contain', '1965');
closeModal();
cy.wrap($canvas)
.scrollIntoView()
.trigger('mousemove', 70, 93)
.rightclick(70, 93);
openModalFromChartContext('Drill to detail by boy');
cy.getBySel('filter-val').should('contain', 'boy');
closeModal();
cy.wrap($canvas)
.scrollIntoView()
.trigger('mousemove', 70, 93)
.rightclick(70, 93);
openModalFromChartContext('Drill to detail by all');
cy.getBySel('filter-val').first().should('contain', '1965');
cy.getBySel('filter-val').eq(1).should('contain', 'boy');
closeModal();
cy.wrap($canvas)
.scrollIntoView()
.trigger('mousemove', 70, 145)
.rightclick(70, 145);
openModalFromChartContext('Drill to detail by girl');
cy.getBySel('filter-val').should('contain', 'girl');
closeModal();
cy.wrap($canvas)
.scrollIntoView()
.trigger('mousemove', 70, 145)
.rightclick(70, 145);
openModalFromChartContext('Drill to detail by all');
cy.getBySel('filter-val').first().should('contain', '1965');
cy.getBySel('filter-val').eq(1).should('contain', 'girl');
});
}
describe('Drill to detail modal', () => {
beforeEach(() => {
closeModal();
});
describe('Tier 1 charts', () => {
before(() => {
cy.visit(SUPPORTED_CHARTS_DASHBOARD);
openTopLevelTab('Tier 1');
SUPPORTED_TIER1_CHARTS.forEach(waitForChartLoad);
});
describe('Modal actions', () => {
it('opens the modal from the context menu', () => {
openModalFromMenu('big_number_total');
cy.get("[role='dialog'] .draggable-trigger").should(
'contain',
'Drill to detail: Big Number',
);
});
it('refreshes the data', () => {
openModalFromMenu('big_number_total');
// move to the last page
cy.get('.ant-pagination-item').eq(5).click();
// skips error on pagination
cy.on('uncaught:exception', () => false);
cy.wait('@samples');
// reload
cy.get("[aria-label='reload']").click();
cy.wait('@samples');
// make sure it started back from first page
cy.get('.ant-pagination-item-active').should('contain', '1');
});
it('paginates', () => {
openModalFromMenu('big_number_total');
// checking the data
cy.getBySel('row-count-label').should('contain', '75.7k rows');
cy.get('.virtual-table-cell').should($rows => {
expect($rows).to.contain('Amy');
});
// checking the paginated data
cy.get('.ant-pagination-item')
.should('have.length', 6)
.should($pages => {
expect($pages).to.contain('1');
expect($pages).to.contain('1514');
});
cy.get('.ant-pagination-item').eq(4).click();
// skips error on pagination
cy.on('uncaught:exception', () => false);
cy.wait('@samples');
cy.get('.virtual-table-cell').should($rows => {
expect($rows).to.contain('Kelly');
});
// verify scroll top on pagination
cy.getBySelLike('Number-modal').find('.virtual-grid').scrollTo(0, 200);
cy.get('.virtual-grid').contains('Juan').should('not.be.visible');
cy.get('.ant-pagination-item').eq(0).click();
cy.get('.virtual-grid').contains('Aaron').should('be.visible');
});
});
describe('Big number total', () => {
it('opens the modal with no filters', () => {
interceptSamples();
// opens the modal by clicking on the number on the chart
cy.get("[data-test-viz-type='big_number_total'] .header-line")
.scrollIntoView()
.rightclick();
openModalFromChartContext('Drill to detail');
cy.getBySel('filter-val').should('not.exist');
});
});
describe('Big number with trendline', () => {
it('opens the modal with the correct data', () => {
interceptSamples();
// opens the modal by clicking on the number
cy.get("[data-test-viz-type='big_number'] .header-line")
.scrollIntoView()
.rightclick();
openModalFromChartContext('Drill to detail');
cy.getBySel('filter-val').should('not.exist');
closeModal();
// opens the modal by clicking on the trendline
cy.get("[data-test-viz-type='big_number'] canvas").then($canvas => {
cy.wrap($canvas)
.scrollIntoView()
.trigger('mousemove', 1, 14)
.rightclick(1, 14);
openModalFromChartContext('Drill to detail by 1965');
// checking the filter
cy.getBySel('filter-val').should('contain', '1965');
});
});
});
describe('Table', () => {
it('opens the modal with the correct filters', () => {
interceptSamples();
cy.get("[data-test-viz-type='table']")
.scrollIntoView()
.contains('boy')
.rightclick();
openModalFromChartContext('Drill to detail by boy');
cy.getBySel('filter-val').should('contain', 'boy');
closeModal();
cy.get("[data-test-viz-type='table']")
.scrollIntoView()
.contains('girl')
.rightclick();
openModalFromChartContext('Drill to detail by girl');
cy.getBySel('filter-val').should('contain', 'girl');
});
});
describe('Pivot Table V2', () => {
it('opens the modal with the correct filters', () => {
interceptSamples();
cy.get("[data-test-viz-type='pivot_table_v2']")
.scrollIntoView()
.find('[role="gridcell"]')
.first()
.rightclick();
openModalFromChartContext('Drill to detail by boy');
cy.getBySel('filter-val').should('contain', 'boy');
closeModal();
cy.get("[data-test-viz-type='pivot_table_v2']")
.scrollIntoView()
.find('[role="gridcell"]')
.first()
.rightclick();
openModalFromChartContext('Drill to detail by CA');
cy.getBySel('filter-val').should('contain', 'CA');
closeModal();
cy.get("[data-test-viz-type='pivot_table_v2']")
.scrollIntoView()
.find('[role="gridcell"]')
.eq(3)
.rightclick();
openModalFromChartContext('Drill to detail by girl');
cy.getBySel('filter-val').should('contain', 'girl');
closeModal();
cy.get("[data-test-viz-type='pivot_table_v2']")
.scrollIntoView()
.find('[role="gridcell"]')
.eq(3)
.rightclick();
openModalFromChartContext('Drill to detail by FL');
cy.getBySel('filter-val').should('contain', 'FL');
closeModal();
cy.get("[data-test-viz-type='pivot_table_v2']")
.scrollIntoView()
.find('[role="gridcell"]')
.eq(3)
.rightclick();
openModalFromChartContext('Drill to detail by all');
cy.getBySel('filter-val').first().should('contain', 'girl');
cy.getBySel('filter-val').eq(1).should('contain', 'FL');
});
});
describe('Time-Series Line Chart', () => {
it('opens the modal with the correct filters', () => {
testTimeChart('echarts_timeseries_line');
});
});
describe('Time-series Bar Chart', () => {
it('opens the modal with the correct filters', () => {
interceptSamples();
cy.get("[data-test-viz-type='echarts_timeseries_bar'] canvas").then(
$canvas => {
cy.wrap($canvas).scrollIntoView().rightclick(70, 100);
openModalFromChartContext('Drill to detail by 1965');
cy.getBySel('filter-val').should('contain', '1965');
closeModal();
cy.wrap($canvas).scrollIntoView().rightclick(70, 100);
openModalFromChartContext('Drill to detail by boy');
cy.getBySel('filter-val').should('contain', 'boy');
closeModal();
cy.wrap($canvas).scrollIntoView().rightclick(70, 100);
openModalFromChartContext('Drill to detail by all');
cy.getBySel('filter-val').first().should('contain', '1965');
cy.getBySel('filter-val').eq(1).should('contain', 'boy');
closeModal();
cy.wrap($canvas).scrollIntoView().rightclick(72, 200);
openModalFromChartContext('Drill to detail by girl');
cy.getBySel('filter-val').should('contain', 'girl');
},
);
});
});
describe('Time-Series Area Chart', () => {
it('opens the modal with the correct filters', () => {
testTimeChart('echarts_area');
});
});
describe('Time-Series Scatter Chart', () => {
it('opens the modal with the correct filters', () => {
testTimeChart('echarts_timeseries_scatter');
});
});
describe('Pie', () => {
it('opens the modal with the correct filters', () => {
interceptSamples();
// opens the modal by clicking on the slice of the Pie chart
cy.get("[data-test-viz-type='pie'] canvas").then($canvas => {
cy.wrap($canvas).scrollIntoView().rightclick(130, 150);
openModalFromChartContext('Drill to detail by girl');
cy.getBySel('filter-val').should('contain', 'girl');
closeModal();
cy.wrap($canvas).scrollIntoView().rightclick(230, 190);
openModalFromChartContext('Drill to detail by boy');
cy.getBySel('filter-val').should('contain', 'boy');
});
});
});
describe('World Map', () => {
it('opens the modal with the correct filters', () => {
interceptSamples();
cy.get("[data-test-viz-type='world_map'] svg").then($canvas => {
cy.wrap($canvas).scrollIntoView().rightclick(70, 150);
openModalFromChartContext('Drill to detail by USA');
cy.getBySel('filter-val').should('contain', 'USA');
closeModal();
});
cy.get("[data-test-viz-type='world_map'] svg").then($canvas => {
cy.wrap($canvas).scrollIntoView().rightclick(200, 140);
openModalFromChartContext('Drill to detail by SVK');
cy.getBySel('filter-val').should('contain', 'SVK');
});
});
});
describe('Bar Chart', () => {
it('opens the modal for unsupported chart without filters', () => {
interceptSamples();
cy.get("[data-test-viz-type='dist_bar'] svg").then($canvas => {
cy.wrap($canvas).scrollIntoView().rightclick(70, 150);
openModalFromChartContext('Drill to detail');
cy.getBySel('filter-val').should('not.exist');
});
});
});
});
describe('Tier 2 charts', () => {
before(() => {
cy.visit(SUPPORTED_CHARTS_DASHBOARD);
openTopLevelTab('Tier 2');
SUPPORTED_TIER2_CHARTS.forEach(waitForChartLoad);
});
describe('Modal actions', () => {
it('clears filters', () => {
interceptSamples();
// opens the modal by clicking on the box on the chart
cy.get("[data-test-viz-type='box_plot'] canvas").then($canvas => {
const canvasWidth = $canvas.width() || 0;
const canvasHeight = $canvas.height() || 0;
const canvasCenterX = canvasWidth / 3;
const canvasCenterY = (canvasHeight * 5) / 6;
cy.wrap($canvas)
.scrollIntoView()
.rightclick(canvasCenterX, canvasCenterY, { force: true });
openModalFromChartContext('Drill to detail by boy');
// checking the filter
cy.getBySel('filter-val').should('contain', 'boy');
cy.getBySel('row-count-label').should('contain', '39.2k rows');
cy.get('.ant-pagination-item')
.should('have.length', 6)
.then($pages => {
expect($pages).to.contain('1');
expect($pages).to.contain('785');
});
// close the filter and test that data was reloaded
cy.getBySel('filter-col').find("[aria-label='close']").click();
cy.wait('@samples');
cy.getBySel('row-count-label').should('contain', '75.7k rows');
cy.get('.ant-pagination-item-active').should('contain', '1');
cy.get('.ant-pagination-item')
.should('have.length', 6)
.then($pages => {
expect($pages).to.contain('1');
expect($pages).to.contain('1514');
});
});
});
});
describe('Box plot', () => {
it('opens the modal with the correct filters', () => {
interceptSamples();
cy.get("[data-test-viz-type='box_plot'] canvas").then($canvas => {
cy.wrap($canvas)
.scrollIntoView()
.trigger('mousemove', 135, 275)
.rightclick(135, 275);
openModalFromChartContext('Drill to detail by boy');
cy.getBySel('filter-val').should('contain', 'boy');
closeModal();
cy.wrap($canvas)
.scrollIntoView()
.trigger('mousemove', 270, 280)
.rightclick(270, 280);
openModalFromChartContext('Drill to detail by girl');
cy.getBySel('filter-val').should('contain', 'girl');
});
});
});
describe('Time-Series Generic Chart', () => {
it('opens the modal with the correct filters', () => {
testTimeChart('echarts_timeseries');
});
});
describe('Time-Series Smooth Chart', () => {
it('opens the modal with the correct filters', () => {
testTimeChart('echarts_timeseries_smooth');
});
});
describe('Time-Series Step Line Chart', () => {
it('opens the modal with the correct filters', () => {
testTimeChart('echarts_timeseries_step');
});
});
describe('Funnel Chart', () => {
it('opens the modal with the correct filters', () => {
interceptSamples();
cy.get("[data-test-viz-type='funnel'] canvas").then($canvas => {
cy.wrap($canvas).scrollIntoView().rightclick(170, 90);
openModalFromChartContext('Drill to detail by boy');
cy.getBySel('filter-val').should('contain', 'boy');
closeModal();
cy.wrap($canvas).scrollIntoView().rightclick(190, 250);
openModalFromChartContext('Drill to detail by girl');
cy.getBySel('filter-val').should('contain', 'girl');
});
});
});
describe('Gauge Chart', () => {
it('opens the modal with the correct filters', () => {
interceptSamples();
cy.get("[data-test-viz-type='gauge_chart'] canvas").then($canvas => {
cy.wrap($canvas).scrollIntoView().rightclick(135, 95);
openModalFromChartContext('Drill to detail by boy');
cy.getBySel('filter-val').should('contain', 'boy');
closeModal();
cy.wrap($canvas).scrollIntoView().rightclick(95, 135);
openModalFromChartContext('Drill to detail by girl');
cy.getBySel('filter-val').should('contain', 'girl');
});
});
});
describe('Mixed Chart', () => {
it('opens the modal with the correct filters', () => {
testTimeChart('mixed_timeseries');
});
});
describe('Radar Chart', () => {
it('opens the modal with the correct filters', () => {
interceptSamples();
cy.get("[data-test-viz-type='radar'] canvas").then($canvas => {
cy.wrap($canvas).scrollIntoView().rightclick(180, 45);
openModalFromChartContext('Drill to detail by boy');
cy.getBySel('filter-val').should('contain', 'boy');
closeModal();
cy.wrap($canvas).scrollIntoView().rightclick(180, 85);
openModalFromChartContext('Drill to detail by girl');
cy.getBySel('filter-val').should('contain', 'girl');
});
});
});
describe('Treemap', () => {
it('opens the modal with the correct filters', () => {
interceptSamples();
cy.get("[data-test-viz-type='treemap_v2'] canvas").then($canvas => {
cy.wrap($canvas).scrollIntoView().rightclick(100, 30);
openModalFromChartContext('Drill to detail by boy');
cy.getBySel('filter-val').should('contain', 'boy');
closeModal();
cy.wrap($canvas).scrollIntoView().rightclick(150, 250);
openModalFromChartContext('Drill to detail by girl');
cy.getBySel('filter-val').should('contain', 'girl');
});
});
});
});
});
|
5,062 | 0 | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/dashboard/editmode.test.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { SAMPLE_DASHBOARD_1, TABBED_DASHBOARD } from 'cypress/utils/urls';
import { drag, resize, waitForChartLoad } from 'cypress/utils';
import * as ace from 'brace';
import { interceptGet, interceptUpdate, openTab } from './utils';
import {
interceptExploreJson,
interceptFiltering as interceptCharts,
} from '../explore/utils';
function editDashboard() {
cy.getBySel('edit-dashboard-button').click();
}
function closeModal() {
cy.getBySel('properties-modal-cancel-button').click({ force: true });
}
function openProperties() {
cy.get('body').then($body => {
if ($body.find('[data-test="properties-modal-cancel-button"]').length) {
closeModal();
}
cy.getBySel('actions-trigger').click({ force: true });
cy.getBySel('header-actions-menu')
.contains('Edit properties')
.click({ force: true });
cy.wait(500);
});
}
function openAdvancedProperties() {
cy.get('.ant-modal-body')
.contains('Advanced')
.should('be.visible')
.click({ force: true });
}
function dragComponent(
component = 'Unicode Cloud',
target = 'card-title',
withFiltering = true,
) {
if (withFiltering) {
cy.getBySel('dashboard-charts-filter-search-input').type(component);
cy.wait('@filtering');
}
cy.wait(500);
drag(`[data-test="${target}"]`, component).to(
'[data-test="grid-content"] [data-test="dragdroppable-object"]',
);
}
function discardChanges() {
cy.getBySel('undo-action').click({ force: true });
}
function visitEdit(sampleDashboard = SAMPLE_DASHBOARD_1) {
interceptCharts();
interceptGet();
if (sampleDashboard === SAMPLE_DASHBOARD_1) {
cy.createSampleDashboards([0]);
}
cy.visit(sampleDashboard);
cy.wait('@get');
editDashboard();
cy.wait('@filtering');
cy.wait(500);
}
function resetTabbedDashboard(go = false) {
cy.getDashboard('tabbed_dash').then((r: Record<string, any>) => {
const jsonMetadata = r?.json_metadata || '{}';
const metadata = JSON.parse(jsonMetadata);
const resetMetadata = JSON.stringify({
...metadata,
color_scheme: '',
label_colors: {},
shared_label_colors: {},
});
cy.updateDashboard(r.id, {
certification_details: r.certification_details,
certified_by: r.certified_by,
css: r.css,
dashboard_title: r.dashboard_title,
json_metadata: resetMetadata,
owners: r.owners,
slug: r.slug,
}).then(() => {
if (go) {
visitEdit(TABBED_DASHBOARD);
}
});
});
}
function visitResetTabbedDashboard() {
resetTabbedDashboard(true);
}
function selectColorScheme(color: string) {
cy.get(
'[data-test="dashboard-edit-properties-form"] [aria-label="Select color scheme"]',
)
.first()
.click();
cy.getBySel(color).click();
}
function applyChanges() {
cy.getBySel('properties-modal-apply-button').click({ force: true });
}
function saveChanges() {
interceptUpdate();
cy.getBySel('header-save-button').click({ force: true });
cy.wait('@update');
}
function assertMetadata(text: string) {
const regex = new RegExp(text);
cy.get('#json_metadata')
.should('be.visible')
.then(() => {
const metadata = cy.$$('#json_metadata')[0];
// cypress can read this locally, but not in ci
// so we have to use the ace module directly to fetch the value
expect(ace.edit(metadata).getValue()).to.match(regex);
});
}
function clearMetadata() {
cy.get('#json_metadata').then($jsonmetadata => {
cy.wrap($jsonmetadata).find('.ace_content').click();
cy.wrap($jsonmetadata)
.find('.ace_text-input')
.type('{selectall} {backspace}', { force: true });
});
}
function writeMetadata(metadata: string) {
cy.get('#json_metadata').then($jsonmetadata =>
cy
.wrap($jsonmetadata)
.find('.ace_text-input')
.type(metadata, { parseSpecialCharSequences: false, force: true }),
);
}
function openExplore(chartName: string) {
interceptExploreJson();
cy.get(
`[data-test-chart-name='${chartName}'] [aria-label='More Options']`,
).click();
cy.get('.ant-dropdown')
.not('.ant-dropdown-hidden')
.find("[role='menu'] [role='menuitem']")
.eq(2)
.should('contain', 'Edit chart')
.click();
cy.wait('@getJson');
}
describe('Dashboard edit', () => {
describe('Color consistency', () => {
beforeEach(() => {
visitResetTabbedDashboard();
});
after(() => {
resetTabbedDashboard();
});
it('should respect chart color scheme when none is set for the dashboard', () => {
openProperties();
cy.get('[aria-label="Select color scheme"]').should('have.value', '');
applyChanges();
saveChanges();
// open nested tab
openTab(1, 1);
waitForChartLoad({
name: 'Top 10 California Names Timeseries',
viz: 'line',
});
// label Anthony
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.first()
.should('have.css', 'fill', 'rgb(69, 78, 124)');
});
it('should apply same color to same labels with color scheme set', () => {
openProperties();
selectColorScheme('lyftColors');
applyChanges();
saveChanges();
// open nested tab
openTab(1, 1);
waitForChartLoad({
name: 'Top 10 California Names Timeseries',
viz: 'line',
});
// label Anthony
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.first()
.should('have.css', 'fill', 'rgb(51, 61, 71)');
// open 2nd main tab
openTab(0, 1);
waitForChartLoad({ name: 'Trends', viz: 'line' });
// label Anthony
cy.get('[data-test-chart-name="Trends"] .line .nv-legend-symbol')
.eq(2)
.should('have.css', 'fill', 'rgb(51, 61, 71)');
});
it('should apply same color to same labels with no color scheme set', () => {
openProperties();
cy.get('[aria-label="Select color scheme"]').should('have.value', '');
applyChanges();
saveChanges();
// open nested tab
openTab(1, 1);
waitForChartLoad({
name: 'Top 10 California Names Timeseries',
viz: 'line',
});
// label Anthony
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.first()
.should('have.css', 'fill', 'rgb(69, 78, 124)');
// open 2nd main tab
openTab(0, 1);
waitForChartLoad({ name: 'Trends', viz: 'line' });
// label Anthony
cy.get('[data-test-chart-name="Trends"] .line .nv-legend-symbol')
.eq(2)
.should('have.css', 'fill', 'rgb(69, 78, 124)');
});
it('custom label colors should take the precedence in nested tabs', () => {
openProperties();
openAdvancedProperties();
clearMetadata();
writeMetadata(
'{"color_scheme":"lyftColors","label_colors":{"Anthony":"red","Bangladesh":"red"}}',
);
applyChanges();
saveChanges();
// open nested tab
openTab(1, 1);
waitForChartLoad({
name: 'Top 10 California Names Timeseries',
viz: 'line',
});
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.first()
.should('have.css', 'fill', 'rgb(255, 0, 0)');
// open another nested tab
openTab(2, 1);
waitForChartLoad({ name: 'Growth Rate', viz: 'line' });
cy.get('[data-test-chart-name="Growth Rate"] .line .nv-legend-symbol')
.first()
.should('have.css', 'fill', 'rgb(255, 0, 0)');
});
it('label colors should take the precedence for rendered charts in nested tabs', () => {
// open the tab first time and let chart load
openTab(1, 1);
waitForChartLoad({
name: 'Top 10 California Names Timeseries',
viz: 'line',
});
// go to previous tab
openTab(1, 0);
openProperties();
openAdvancedProperties();
clearMetadata();
writeMetadata(
'{"color_scheme":"lyftColors","label_colors":{"Anthony":"red"}}',
);
applyChanges();
saveChanges();
// re-open the tab
openTab(1, 1);
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.first()
.should('have.css', 'fill', 'rgb(255, 0, 0)');
});
it('should re-apply original color after removing custom label color with color scheme set', () => {
openProperties();
openAdvancedProperties();
clearMetadata();
writeMetadata(
'{"color_scheme":"lyftColors","label_colors":{"Anthony":"red"}}',
);
applyChanges();
saveChanges();
openTab(1, 1);
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.first()
.should('have.css', 'fill', 'rgb(255, 0, 0)');
editDashboard();
openProperties();
openAdvancedProperties();
clearMetadata();
writeMetadata('{"color_scheme":"lyftColors","label_colors":{}}');
applyChanges();
saveChanges();
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.first()
.should('have.css', 'fill', 'rgb(234, 11, 140)');
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.eq(1)
.should('have.css', 'fill', 'rgb(108, 131, 142)');
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.eq(2)
.should('have.css', 'fill', 'rgb(41, 171, 226)');
});
it('should re-apply original color after removing custom label color with no color scheme set', () => {
// open nested tab
openTab(1, 1);
waitForChartLoad({
name: 'Top 10 California Names Timeseries',
viz: 'line',
});
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.first()
.should('have.css', 'fill', 'rgb(69, 78, 124)');
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.eq(1)
.should('have.css', 'fill', 'rgb(224, 67, 85)');
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.eq(2)
.should('have.css', 'fill', 'rgb(163, 143, 121)');
openProperties();
cy.get('[aria-label="Select color scheme"]').should('have.value', '');
openAdvancedProperties();
clearMetadata();
writeMetadata('{"color_scheme":"","label_colors":{"Anthony":"red"}}');
applyChanges();
saveChanges();
openTab(1, 1);
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.first()
.should('have.css', 'fill', 'rgb(255, 0, 0)');
editDashboard();
openProperties();
openAdvancedProperties();
clearMetadata();
writeMetadata('{"color_scheme":"","label_colors":{}}');
applyChanges();
saveChanges();
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.first()
.should('have.css', 'fill', 'rgb(69, 78, 124)');
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.eq(1)
.should('have.css', 'fill', 'rgb(224, 67, 85)');
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.eq(2)
.should('have.css', 'fill', 'rgb(163, 143, 121)');
});
it('should show the same colors in Explore', () => {
openProperties();
openAdvancedProperties();
clearMetadata();
writeMetadata(
'{"color_scheme":"lyftColors","label_colors":{"Anthony":"red"}}',
);
applyChanges();
saveChanges();
// open nested tab
openTab(1, 1);
waitForChartLoad({
name: 'Top 10 California Names Timeseries',
viz: 'line',
});
// label Anthony
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.first()
.should('have.css', 'fill', 'rgb(255, 0, 0)');
// label Christopher
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.eq(1)
.should('have.css', 'fill', 'rgb(172, 32, 119)');
openExplore('Top 10 California Names Timeseries');
// label Anthony
cy.get('[data-test="chart-container"] .line .nv-legend-symbol')
.first()
.should('have.css', 'fill', 'rgb(255, 0, 0)');
// label Christopher
cy.get('[data-test="chart-container"] .line .nv-legend-symbol')
.eq(1)
.should('have.css', 'fill', 'rgb(172, 32, 119)');
});
it('should change color scheme multiple times', () => {
openProperties();
selectColorScheme('lyftColors');
applyChanges();
saveChanges();
// open nested tab
openTab(1, 1);
waitForChartLoad({
name: 'Top 10 California Names Timeseries',
viz: 'line',
});
// label Anthony
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.first()
.should('have.css', 'fill', 'rgb(51, 61, 71)');
// open 2nd main tab
openTab(0, 1);
waitForChartLoad({ name: 'Trends', viz: 'line' });
// label Anthony
cy.get('[data-test-chart-name="Trends"] .line .nv-legend-symbol')
.eq(2)
.should('have.css', 'fill', 'rgb(51, 61, 71)');
editDashboard();
openProperties();
selectColorScheme('bnbColors');
applyChanges();
saveChanges();
// label Anthony
cy.get('[data-test-chart-name="Trends"] .line .nv-legend-symbol')
.eq(2)
.should('have.css', 'fill', 'rgb(244, 176, 42)');
// open main tab and nested tab
openTab(0, 0);
openTab(1, 1);
// label Anthony
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.first()
.should('have.css', 'fill', 'rgb(244, 176, 42)');
});
it('should apply the color scheme across main tabs', () => {
openProperties();
selectColorScheme('lyftColors');
applyChanges();
saveChanges();
// go to second tab
openTab(0, 1);
waitForChartLoad({ name: 'Trends', viz: 'line' });
cy.get('[data-test-chart-name="Trends"] .line .nv-legend-symbol')
.first()
.should('have.css', 'fill', 'rgb(51, 61, 71)');
});
it('should apply the color scheme across main tabs for rendered charts', () => {
waitForChartLoad({ name: 'Treemap', viz: 'treemap_v2' });
openProperties();
selectColorScheme('bnbColors');
applyChanges();
saveChanges();
// go to second tab
openTab(0, 1);
waitForChartLoad({ name: 'Trends', viz: 'line' });
cy.get('[data-test-chart-name="Trends"] .line .nv-legend-symbol')
.first()
.should('have.css', 'fill', 'rgb(156, 52, 152)');
// change scheme now that charts are rendered across the main tabs
editDashboard();
openProperties();
selectColorScheme('lyftColors');
applyChanges();
saveChanges();
cy.get('[data-test-chart-name="Trends"] .line .nv-legend-symbol')
.first()
.should('have.css', 'fill', 'rgb(234, 11, 140)');
});
it('should apply the color scheme in nested tabs', () => {
openProperties();
selectColorScheme('lyftColors');
applyChanges();
saveChanges();
// open nested tab
openTab(1, 1);
waitForChartLoad({
name: 'Top 10 California Names Timeseries',
viz: 'line',
});
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.first()
.should('have.css', 'fill', 'rgb(51, 61, 71)');
// open another nested tab
openTab(2, 1);
waitForChartLoad({ name: 'Growth Rate', viz: 'line' });
cy.get('[data-test-chart-name="Growth Rate"] .line .nv-legend-symbol')
.first()
.should('have.css', 'fill', 'rgb(234, 11, 140)');
});
it('should apply a valid color scheme for rendered charts in nested tabs', () => {
// open the tab first time and let chart load
openTab(1, 1);
waitForChartLoad({
name: 'Top 10 California Names Timeseries',
viz: 'line',
});
// go to previous tab
openTab(1, 0);
openProperties();
selectColorScheme('lyftColors');
applyChanges();
saveChanges();
// re-open the tab
openTab(1, 1);
cy.get(
'[data-test-chart-name="Top 10 California Names Timeseries"] .line .nv-legend-symbol',
)
.first()
.should('have.css', 'fill', 'rgb(234, 11, 140)');
});
});
describe('Edit properties', () => {
before(() => {
visitEdit();
});
beforeEach(() => {
cy.createSampleDashboards([0]);
openProperties();
});
it('should accept a valid color scheme', () => {
openAdvancedProperties();
clearMetadata();
writeMetadata('{"color_scheme":"lyftColors"}');
applyChanges();
openProperties();
openAdvancedProperties();
assertMetadata('lyftColors');
applyChanges();
});
it('should overwrite the color scheme when advanced is closed', () => {
selectColorScheme('d3Category20b');
openAdvancedProperties();
assertMetadata('d3Category20b');
applyChanges();
});
it('should overwrite the color scheme when advanced is open', () => {
openAdvancedProperties();
selectColorScheme('googleCategory10c');
assertMetadata('googleCategory10c');
applyChanges();
});
it('should not accept an invalid color scheme', () => {
openAdvancedProperties();
clearMetadata();
// allow console error
cy.allowConsoleErrors(['Error: A valid color scheme is required']);
writeMetadata('{"color_scheme":"wrongcolorscheme"}');
applyChanges();
cy.get('.ant-modal-body')
.contains('A valid color scheme is required')
.should('be.visible');
});
it('should edit the title', () => {
cy.getBySel('dashboard-title-input').clear().type('Edited title');
applyChanges();
cy.getBySel('editable-title-input').should('have.value', 'Edited title');
});
});
describe('Edit mode', () => {
before(() => {
visitEdit();
});
beforeEach(() => {
cy.createSampleDashboards([0]);
discardChanges();
});
it('should enable edit mode', () => {
cy.getBySel('dashboard-builder-sidepane').should('be.visible');
});
it('should edit the title inline', () => {
cy.getBySel('editable-title-input').clear().type('Edited title{enter}');
cy.getBySel('header-save-button').should('be.enabled');
});
it('should filter charts', () => {
interceptCharts();
cy.get('[role="checkbox"]').click();
cy.getBySel('dashboard-charts-filter-search-input').type('Unicode');
cy.wait('@filtering');
cy.getBySel('chart-card')
.should('have.length', 1)
.contains('Unicode Cloud');
cy.getBySel('dashboard-charts-filter-search-input').clear();
});
// TODO fix this test! This was the #1 flaky test as of 4/21/23 according to cypress dashboard.
xit('should disable the Save button when undoing', () => {
cy.get('[role="checkbox"]').click();
dragComponent('Unicode Cloud', 'card-title', false);
cy.getBySel('header-save-button').should('be.enabled');
discardChanges();
cy.getBySel('header-save-button').should('be.disabled');
});
});
describe('Components', () => {
beforeEach(() => {
visitEdit();
});
it('should add charts', () => {
cy.get('[role="checkbox"]').click();
dragComponent();
cy.getBySel('dashboard-component-chart-holder').should('have.length', 1);
});
it('should remove added charts', () => {
cy.get('[role="checkbox"]').click();
dragComponent('Unicode Cloud');
cy.getBySel('dashboard-component-chart-holder').should('have.length', 1);
cy.getBySel('dashboard-delete-component-button').click();
cy.getBySel('dashboard-component-chart-holder').should('have.length', 0);
});
it('should add markdown component to dashboard', () => {
cy.getBySel('dashboard-builder-component-pane-tabs-navigation')
.find('#tabs-tab-2')
.click();
// add new markdown component
dragComponent('Text', 'new-component', false);
cy.getBySel('dashboard-markdown-editor')
.should(
'have.text',
'✨Header 1\n✨Header 2\n✨Header 3\n\nClick here to learn more about markdown formatting',
)
.click(10, 10);
cy.getBySel('dashboard-component-chart-holder').contains(
'Click here to learn more about [markdown formatting](https://bit.ly/1dQOfRK)',
);
cy.getBySel('dashboard-markdown-editor').click().type('Test resize');
resize(
'[data-test="dashboard-markdown-editor"] .resizable-container span div:last-child',
).to(500, 600);
cy.getBySel('dashboard-markdown-editor').contains('Test resize');
});
});
describe('Save', () => {
beforeEach(() => {
visitEdit();
});
it('should save', () => {
cy.get('[role="checkbox"]').click();
dragComponent();
cy.getBySel('header-save-button').should('be.enabled');
saveChanges();
cy.getBySel('dashboard-component-chart-holder').should('have.length', 1);
cy.getBySel('edit-dashboard-button').should('be.visible');
});
});
});
|
5,063 | 0 | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e | petrpan-code/apache/superset/superset-frontend/cypress-base/cypress/e2e/dashboard/load.test.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { WORLD_HEALTH_DASHBOARD } from 'cypress/utils/urls';
import { waitForChartLoad } from 'cypress/utils';
import { WORLD_HEALTH_CHARTS, interceptLog } from './utils';
describe('Dashboard load', () => {
it('should load dashboard', () => {
cy.visit(WORLD_HEALTH_DASHBOARD);
WORLD_HEALTH_CHARTS.forEach(waitForChartLoad);
});
it('should load in edit mode', () => {
cy.visit(`${WORLD_HEALTH_DASHBOARD}?edit=true&standalone=true`);
cy.getBySel('discard-changes-button').should('be.visible');
});
it('should load in standalone mode', () => {
cy.visit(`${WORLD_HEALTH_DASHBOARD}?edit=true&standalone=true`);
cy.get('#app-menu').should('not.exist');
});
it('should load in edit/standalone mode', () => {
cy.visit(`${WORLD_HEALTH_DASHBOARD}?edit=true&standalone=true`);
cy.getBySel('discard-changes-button').should('be.visible');
cy.get('#app-menu').should('not.exist');
});
// TODO flaky test. skipping to unblock CI
it.skip('should send log data', () => {
interceptLog();
cy.visit(WORLD_HEALTH_DASHBOARD);
cy.wait('@logs', { timeout: 15000 });
});
});
|