Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TestBuild: Add tests and rename to camelCase #24911

Merged
merged 6 commits into from
Nov 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions code/lib/core-common/src/utils/normalize-stories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export const getDirectoryFromWorkingDir = ({

export const normalizeStoriesEntry = (
entry: StoriesEntry,
{ configDir, workingDir, default_files_pattern = DEFAULT_FILES_PATTERN }: NormalizeOptions
{ configDir, workingDir, defaultFilesPattern = DEFAULT_FILES_PATTERN }: NormalizeOptions
): NormalizedStoriesSpecifier => {
let specifierWithoutMatcher: Omit<NormalizedStoriesSpecifier, 'importPathMatcher'>;

Expand All @@ -53,7 +53,7 @@ export const normalizeStoriesEntry = (
specifierWithoutMatcher = {
titlePrefix: DEFAULT_TITLE_PREFIX,
directory: entry,
files: default_files_pattern,
files: defaultFilesPattern,
};
} else {
specifierWithoutMatcher = {
Expand All @@ -65,7 +65,7 @@ export const normalizeStoriesEntry = (
} else {
specifierWithoutMatcher = {
titlePrefix: DEFAULT_TITLE_PREFIX,
files: default_files_pattern,
files: defaultFilesPattern,
...entry,
};
}
Expand Down Expand Up @@ -99,7 +99,7 @@ export const normalizeStoriesEntry = (
interface NormalizeOptions {
configDir: string;
workingDir: string;
default_files_pattern?: string;
defaultFilesPattern?: string;
}

export const normalizeStories = (entries: StoriesEntry[], options: NormalizeOptions) => {
Expand Down
57 changes: 3 additions & 54 deletions code/lib/core-server/src/presets/common-override-preset.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,5 @@
import type {
Options,
PresetProperty,
StoriesEntry,
StorybookConfig,
TestBuildFlags,
} from '@storybook/types';
import { normalizeStories, commonGlobOptions } from '@storybook/core-common';
import { isAbsolute, join, relative } from 'path';
import slash from 'slash';
import { glob } from 'glob';
import type { Options, PresetProperty, StorybookConfig, TestBuildFlags } from '@storybook/types';
import { removeMDXEntries } from '../utils/remove-mdx-entries';

export const framework: PresetProperty<'framework', StorybookConfig> = async (config) => {
// This will get called with the values from the user's main config, but before
Expand All @@ -25,49 +16,7 @@ export const framework: PresetProperty<'framework', StorybookConfig> = async (co

export const stories: PresetProperty<'stories', StorybookConfig> = async (entries, options) => {
if (options?.build?.test?.disableMDXEntries) {
const list = normalizeStories(entries, {
configDir: options.configDir,
workingDir: options.configDir,
default_files_pattern: '**/*.@(stories.@(js|jsx|mjs|ts|tsx))',
});
const result = (
await Promise.all(
list.map(async ({ directory, files, titlePrefix }) => {
const pattern = join(directory, files);
const absolutePattern = isAbsolute(pattern) ? pattern : join(options.configDir, pattern);
const absoluteDirectory = isAbsolute(directory)
? directory
: join(options.configDir, directory);

return {
files: (
await glob(slash(absolutePattern), {
...commonGlobOptions(absolutePattern),
follow: true,
})
).map((f) => relative(absoluteDirectory, f)),
directory,
titlePrefix,
};
})
)
).flatMap<StoriesEntry>((expanded, i) => {
const filteredEntries = expanded.files.filter((s) => !s.endsWith('.mdx'));
// only return the filtered entries when there is something to filter
// as webpack is faster with unexpanded globs
let items = [];
if (filteredEntries.length < expanded.files.length) {
items = filteredEntries.map((k) => ({
...expanded,
files: `**/${k}`,
}));
} else {
items = [list[i]];
}

return items;
});
return result;
Comment on lines -28 to -70
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extracted into a separate file: code/lib/core-server/src/utils/remove-mdx-entries.ts

return removeMDXEntries(entries, options);
}
return entries;
};
Expand Down
248 changes: 248 additions & 0 deletions code/lib/core-server/src/utils/__tests__/remove-mdx-stories.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
import { glob as globlOriginal } from 'glob';
import { type StoriesEntry } from '@storybook/types';
import { normalizeStoriesEntry } from '@storybook/core-common';
import { join } from 'path';
import slash from 'slash';
import { removeMDXEntries } from '../remove-mdx-entries';

const glob = globlOriginal as jest.MockedFunction<typeof globlOriginal>;

const configDir = '/configDir/';
const workingDir = '/';

jest.mock('glob', () => ({ glob: jest.fn() }));

const createList = (list: { entry: StoriesEntry; result: string[] }[]) => {
return list.reduce<Record<string, { result: string[]; entry: StoriesEntry }>>(
(acc, { entry, result }) => {
const { directory, files } = normalizeStoriesEntry(entry, {
configDir,
workingDir,
});
acc[slash(join('/', directory, files))] = { result, entry };
return acc;
},
{}
);
};

const createGlobMock = (input: ReturnType<typeof createList>) => {
return async (k: string | string[]) => {
if (Array.isArray(k)) {
throw new Error('do not pass an array to glob during tests');
}
if (input[slash(k)]) {
return input[slash(k)]?.result;
}

throw new Error('can not find key in input');
};
};

test('empty', async () => {
const list = createList([]);
glob.mockImplementation(createGlobMock(list));

await expect(() => removeMDXEntries(Object.keys(list), { configDir })).rejects
.toThrowErrorMatchingInlineSnapshot(`
"Storybook could not index your stories.
Your main configuration somehow does not contain a 'stories' field, or it resolved to an empty array.

Please check your main configuration file and make sure it exports a 'stories' field that is not an empty array.

More info: https://storybook.js.org/docs/react/faq#can-i-have-a-storybook-with-no-local-stories
"
`);
});

test('minimal', async () => {
const list = createList([{ entry: '*.js', result: [] }]);
glob.mockImplementation(createGlobMock(list));

const result = await removeMDXEntries(
Object.values(list).map((e) => e.entry),
{ configDir }
);

expect(result).toMatchInlineSnapshot(`
Array [
Object {
"directory": ".",
"files": "*.js",
"titlePrefix": "",
},
]
`);
});

test('multiple', async () => {
const list = createList([
{ entry: '*.ts', result: [] },
{ entry: '*.js', result: [] },
]);
glob.mockImplementation(createGlobMock(list));

const result = await removeMDXEntries(
Object.values(list).map((e) => e.entry),
{ configDir }
);

expect(result).toMatchInlineSnapshot(`
Array [
Object {
"directory": ".",
"files": "*.ts",
"titlePrefix": "",
},
Object {
"directory": ".",
"files": "*.js",
"titlePrefix": "",
},
]
`);
});

test('mdx but not matching any files', async () => {
const list = createList([
{ entry: '*.mdx', result: [] },
{ entry: '*.js', result: [] },
]);
glob.mockImplementation(createGlobMock(list));

const result = await removeMDXEntries(
Object.values(list).map((e) => e.entry),
{ configDir }
);

expect(result).toMatchInlineSnapshot(`
Array [
Object {
"directory": ".",
"files": "*.mdx",
"titlePrefix": "",
},
Object {
"directory": ".",
"files": "*.js",
"titlePrefix": "",
},
]
`);
});

test('removes entries that only yield mdx files', async () => {
const list = createList([
{ entry: '*.mdx', result: ['/configDir/my-file.mdx'] },
{ entry: '*.js', result: [] },
]);
glob.mockImplementation(createGlobMock(list));

const result = await removeMDXEntries(
Object.values(list).map((e) => e.entry),
{ configDir }
);

expect(result).toMatchInlineSnapshot(`
Array [
Object {
"directory": ".",
"files": "*.js",
"titlePrefix": "",
},
]
`);
});

test('expands entries that only yield mixed files', async () => {
const list = createList([
{ entry: '*.@(mdx|ts)', result: ['/configDir/my-file.mdx', '/configDir/my-file.ts'] },
{ entry: '*.js', result: [] },
]);
glob.mockImplementation(createGlobMock(list));

const result = await removeMDXEntries(
Object.values(list).map((e) => e.entry),
{ configDir }
);

expect(result).toMatchInlineSnapshot(`
Array [
Object {
"directory": ".",
"files": "**/my-file.ts",
"titlePrefix": "",
},
Object {
"directory": ".",
"files": "*.js",
"titlePrefix": "",
},
]
`);
});

test('passes titlePrefix', async () => {
const list = createList([
{
entry: { files: '*.@(mdx|ts)', directory: '.', titlePrefix: 'foo' },
result: ['/configDir/my-file.mdx', '/configDir/my-file.ts'],
},
]);
glob.mockImplementation(createGlobMock(list));

const result = await removeMDXEntries(
Object.values(list).map((e) => e.entry),
{ configDir }
);

expect(result).toMatchInlineSnapshot(`
Array [
Object {
"directory": ".",
"files": "**/my-file.ts",
"titlePrefix": "foo",
},
]
`);
});

test('expands to multiple entries', async () => {
const list = createList([
{
entry: { files: '*.@(mdx|ts)', directory: '.', titlePrefix: 'foo' },
result: [
'/configDir/my-file.mdx',
'/configDir/my-file1.ts',
'/configDir/my-file2.ts',
'/configDir/my-file3.ts',
],
},
]);
glob.mockImplementation(createGlobMock(list));

const result = await removeMDXEntries(
Object.values(list).map((e) => e.entry),
{ configDir }
);

expect(result).toMatchInlineSnapshot(`
Array [
Object {
"directory": ".",
"files": "**/my-file1.ts",
"titlePrefix": "foo",
},
Object {
"directory": ".",
"files": "**/my-file2.ts",
"titlePrefix": "foo",
},
Object {
"directory": ".",
"files": "**/my-file3.ts",
"titlePrefix": "foo",
},
]
`);
});
Loading