Skip to content

Commit

Permalink
Merge branch 'improve-types' into improve-test-runner
Browse files Browse the repository at this point in the history
  • Loading branch information
bryanjtc committed Nov 10, 2023
2 parents acb899a + dc692b4 commit 916c55a
Show file tree
Hide file tree
Showing 17 changed files with 89 additions and 97 deletions.
9 changes: 9 additions & 0 deletions src/csf/__snapshots__/transformCsf.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -1314,3 +1314,12 @@ if (!require.main) {
});
}"
`;
exports[`transformCsf returns empty result if there are no stories 1`] = `
"
export default {
title: 'Button',
};
"
`;
12 changes: 12 additions & 0 deletions src/csf/transformCsf.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,18 @@ describe('transformCsf', () => {
expect(result).toEqual(expectedCode);
});

it('returns empty result if there are no stories', () => {
const csfCode = `
export default {
title: 'Button',
};
`;

const result = transformCsf(csfCode, {});

expect(result).toMatchSnapshot();
});

it('calls the testPrefixer function for each test', () => {
const csfCode = `
export default {
Expand Down
6 changes: 3 additions & 3 deletions src/csf/transformCsf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const makePlayTest = (
return [
t.expressionStatement(
t.callExpression(t.identifier('it'), [
t.stringLiteral(!!metaOrStoryPlay ? 'play-test' : 'smoke-test'),
t.stringLiteral(metaOrStoryPlay ? 'play-test' : 'smoke-test'),
prefixFunction(key, title, metaOrStoryPlay as t.Expression, testPrefix),
])
),
Expand Down Expand Up @@ -100,9 +100,9 @@ export const transformCsf = (
beforeEachPrefixer,
insertTestIfEmpty,
makeTitle,
}: TransformOptions = {}
}: TransformOptions
) => {
const csf = loadCsf(code, { makeTitle: makeTitle || ((userTitle: string) => userTitle) });
const csf = loadCsf(code, { makeTitle: makeTitle ?? ((userTitle: string) => userTitle) });
csf.parse();

const storyExports = Object.keys(csf._stories);
Expand Down
4 changes: 2 additions & 2 deletions src/playwright/transformPlaywright.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ jest.mock('@storybook/core-common', () => ({
}));

expect.addSnapshotSerializer({
print: (val: any) => val.trim(),
test: (val: any) => true,
print: (val: unknown) => (typeof val === 'string' ? val.trim() : String(val)),
test: () => true,
});

describe('Playwright', () => {
Expand Down
2 changes: 1 addition & 1 deletion src/playwright/transformPlaywright.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export const testPrefixer: TestPrefixer = (context) => {

const makeTitleFactory = (filename: string) => {
const { workingDir, normalizedStoriesEntries } = getStorybookMetadata();
const filePath = './' + relative(workingDir, filename);
const filePath = `./${relative(workingDir, filename)}`;

return (userTitle: string) =>
userOrAutoTitle(filePath, normalizedStoriesEntries, userTitle) as string;
Expand Down
40 changes: 14 additions & 26 deletions src/playwright/transformPlaywrightJson.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import {
UnsupportedVersion,
V3StoriesIndex,
makeTest,
V4Index,
transformPlaywrightJson,
} from './transformPlaywrightJson';
import { type V4Index } from './transformPlaywrightJson';

describe('Playwright Json', () => {
describe('v4 indexes', () => {
Expand All @@ -16,22 +15,19 @@ describe('Playwright Json', () => {
id: 'example-header--logged-in',
title: 'Example/Header',
name: 'Logged In',
importPath: './stories/basic/Header.stories.js',
},
'example-header--logged-out': {
id: 'example-header--logged-out',
title: 'Example/Header',
name: 'Logged Out',
importPath: './stories/basic/Header.stories.js',
},
'example-page--logged-in': {
id: 'example-page--logged-in',
title: 'Example/Page',
name: 'Logged In',
importPath: './stories/basic/Page.stories.js',
},
},
};
} satisfies V4Index;
expect(transformPlaywrightJson(input)).toMatchInlineSnapshot(`
{
"example-header": "describe("Example/Header", () => {
Expand Down Expand Up @@ -213,16 +209,14 @@ describe('Playwright Json', () => {
id: 'example-introduction--page',
title: 'Example/Introduction',
name: 'Page',
importPath: './stories/basic/Introduction.stories.mdx',
},
'example-page--logged-in': {
id: 'example-page--logged-in',
title: 'Example/Page',
name: 'Logged In',
importPath: './stories/basic/Page.stories.js',
},
},
};
} satisfies V4Index;
expect(transformPlaywrightJson(input)).toMatchInlineSnapshot(`
{
"example-page": "describe("Example/Page", () => {
Expand Down Expand Up @@ -295,9 +289,6 @@ describe('Playwright Json', () => {
id: 'example-header--logged-in',
title: 'Example/Header',
name: 'Logged In',
importPath: './stories/basic/Header.stories.js',
kind: 'Example/Header',
story: 'Logged In',
parameters: {
__id: 'example-header--logged-in',
docsOnly: false,
Expand All @@ -308,9 +299,6 @@ describe('Playwright Json', () => {
id: 'example-header--logged-out',
title: 'Example/Header',
name: 'Logged Out',
importPath: './stories/basic/Header.stories.js',
kind: 'Example/Header',
story: 'Logged Out',
parameters: {
__id: 'example-header--logged-out',
docsOnly: false,
Expand All @@ -321,17 +309,14 @@ describe('Playwright Json', () => {
id: 'example-page--logged-in',
title: 'Example/Page',
name: 'Logged In',
importPath: './stories/basic/Page.stories.js',
kind: 'Example/Page',
story: 'Logged In',
parameters: {
__id: 'example-page--logged-in',
docsOnly: false,
fileName: './stories/basic/Page.stories.js',
},
},
},
};
} satisfies V3StoriesIndex;
expect(transformPlaywrightJson(input)).toMatchInlineSnapshot(`
{
"example-header": "describe("Example/Header", () => {
Expand Down Expand Up @@ -512,9 +497,6 @@ describe('Playwright Json', () => {
id: 'example-introduction--page',
title: 'Example/Introduction',
name: 'Page',
importPath: './stories/basic/Introduction.stories.mdx',
kind: 'Example/Introduction',
story: 'Page',
parameters: {
__id: 'example-introduction--page',
docsOnly: true,
Expand All @@ -525,17 +507,14 @@ describe('Playwright Json', () => {
id: 'example-page--logged-in',
title: 'Example/Page',
name: 'Logged In',
importPath: './stories/basic/Page.stories.js',
kind: 'Example/Page',
story: 'Logged In',
parameters: {
__id: 'example-page--logged-in',
docsOnly: false,
fileName: './stories/basic/Page.stories.js',
},
},
},
};
} satisfies V3StoriesIndex;
expect(transformPlaywrightJson(input)).toMatchInlineSnapshot(`
{
"example-page": "describe("Example/Page", () => {
Expand Down Expand Up @@ -608,3 +587,12 @@ describe('Playwright Json', () => {
});
});
});

describe('unsupported index', () => {
it('throws an error for unsupported versions', () => {
const unsupportedVersion = { v: 1 } satisfies UnsupportedVersion;
expect(() => transformPlaywrightJson(unsupportedVersion)).toThrowError(
`Unsupported version ${unsupportedVersion.v}`
);
});
});
29 changes: 11 additions & 18 deletions src/playwright/transformPlaywrightJson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@ import { ComponentTitle, StoryId, StoryName, toId } from '@storybook/csf';

import { testPrefixer } from './transformPlaywright';

export const makeTest = (entry: V4Entry): t.Statement => {
const makeTest = (entry: V4Entry): t.Statement => {
const result = testPrefixer({
name: t.stringLiteral(entry.name),
title: t.stringLiteral(entry.title),
id: t.stringLiteral(entry.id),
// FIXME
storyExport: t.identifier(entry.id),
});

const stmt = (result as Array<t.ExpressionStatement>)[1] as t.ExpressionStatement;
const stmt = (result as Array<t.ExpressionStatement>)[1];
return t.expressionStatement(
t.callExpression(t.identifier('it'), [t.stringLiteral('test'), stmt.expression])
);
Expand All @@ -28,13 +27,7 @@ const makeDescribe = (title: string, stmts: t.Statement[]) => {
);
};

export type V4Entry = {
type?: 'story' | 'docs';
id: StoryId;
name: StoryName;
title: ComponentTitle;
importPath?: string;
};
type V4Entry = { type?: 'story' | 'docs'; id: StoryId; name: StoryName; title: ComponentTitle };
export type V4Index = {
v: 4;
entries: Record<StoryId, V4Entry>;
Expand All @@ -46,10 +39,7 @@ type StoryParameters = {
fileName?: string;
};

export type V3Story = Omit<V4Entry, 'type'> & { parameters?: StoryParameters } & {
kind: string;
story: string;
};
type V3Story = Omit<V4Entry, 'type'> & { parameters?: StoryParameters };
export type V3StoriesIndex = {
v: 3;
stories: Record<StoryId, V3Story>;
Expand All @@ -63,10 +53,13 @@ function v3TitleMapToV4TitleMap(
return Object.fromEntries(
Object.entries(titleIdToStories).map(([id, stories]) => [
id,
stories.map(({ parameters, ...story }) => ({
type: isV3DocsOnly(stories) ? 'docs' : 'story',
...story,
})),
stories.map(
({ parameters, ...story }) =>
({
type: isV3DocsOnly(stories) ? 'docs' : 'story',
...story,
} satisfies V4Entry)
),
])
);
}
Expand Down
14 changes: 6 additions & 8 deletions src/setup-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const sanitizeURL = (url: string) => {
let finalURL = url;
// prepend URL protocol if not there
if (finalURL.indexOf('http://') === -1 && finalURL.indexOf('https://') === -1) {
finalURL = 'http://' + finalURL;
finalURL = `http://${finalURL}`;
}

// remove iframe.html if present
Expand All @@ -42,8 +42,8 @@ const sanitizeURL = (url: string) => {
finalURL = finalURL.replace(/index.html\s*$/, '');

// add forward slash at the end if not there
if (finalURL.slice(-1) !== '/') {
finalURL = finalURL + '/';
if (!finalURL.endsWith('/')) {
finalURL = `${finalURL}/`;
}

return finalURL;
Expand All @@ -53,7 +53,7 @@ export const setupPage = async (page: Page, browserContext: BrowserContext) => {
const targetURL = process.env.TARGET_URL;
const failOnConsole = process.env.TEST_CHECK_CONSOLE;

const viewMode = process.env.VIEW_MODE || 'story';
const viewMode = process.env.VIEW_MODE ?? 'story';
const renderedEvent = viewMode === 'docs' ? 'docsRendered' : 'storyRendered';
const { packageJson } = (await readPackageUp()) as NormalizedReadResult;
const { version: testRunnerVersion } = packageJson;
Expand All @@ -72,9 +72,7 @@ export const setupPage = async (page: Page, browserContext: BrowserContext) => {
const testRunnerConfig = getTestRunnerConfig();
if (testRunnerConfig?.prepare) {
await testRunnerConfig.prepare({ page, browserContext, testRunnerConfig });
} else {
if (testRunnerConfig) await defaultPrepare({ page, browserContext, testRunnerConfig });
}
} else if (testRunnerConfig) await defaultPrepare({ page, browserContext, testRunnerConfig });

// if we ever want to log something from the browser to node
await page.exposeBinding('logToPage', (_, message) => console.log(message));
Expand Down Expand Up @@ -247,7 +245,7 @@ export const setupPage = async (page: Page, browserContext: BrowserContext) => {
constructor(storyId, errorMessage, logs = []) {
super(errorMessage);
this.name = 'StorybookTestRunnerError';
const storyUrl = \`${referenceURL || targetURL}?path=/story/\${storyId}\`;
const storyUrl = \`${referenceURL ?? targetURL}?path=/story/\${storyId}\`;
const finalStoryUrl = \`\${storyUrl}&addonPanel=storybook/interactions/panel\`;
const separator = '\\n\\n--------------------------------------------------';
const extraLogs = logs.length > 0 ? separator + "\\n\\nBrowser logs:\\n\\n"+ logs.join('\\n\\n') : '';
Expand Down
Loading

0 comments on commit 916c55a

Please sign in to comment.