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

Respect stories defined in main.js #46

Merged
merged 8 commits into from
Feb 10, 2022
Merged
Show file tree
Hide file tree
Changes from 7 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
1 change: 1 addition & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
**/*.test.js
13 changes: 12 additions & 1 deletion .storybook/main.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
const { STRESS_TEST, STORY_STORE_V7, WITHOUT_DOCS } = process.env;

const stories = [
'../stories/docs/**/*.stories.mdx',
// default title prefix
{
directory: '../stories',
titlePrefix: 'Atoms',
directory: '../stories/atoms',
},
// defined title prefix
{
titlePrefix: 'Molecules',
directory: '../stories/molecules',
},
// general glob
'../stories/pages/**/*.stories.*',
];


if (STRESS_TEST) {
stories.push('../stories/stress-test/*.stories.@(js|jsx|ts|tsx)');
}
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed __snapshots__/example-header--logged-in-snap.png
Binary file not shown.
Binary file removed __snapshots__/example-header--logged-out-snap.png
Binary file not shown.
Binary file removed __snapshots__/example-page--logged-in-snap.png
Binary file not shown.
Binary file removed __snapshots__/example-page--logged-out-snap.png
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added __snapshots__/pages-page--logged-in-snap.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added __snapshots__/pages-page--logged-out-snap.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 4 additions & 3 deletions bin/test-storybook.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const fetch = require('node-fetch');
const fs = require('fs');
const path = require('path');
const tempy = require('tempy');
const { getCliOptions, getStorybookMain } = require('../dist/cjs/util/cli');
const { getCliOptions, getStorybookMetadata } = require('../dist/cjs/util');
const { transformPlaywrightJson } = require('../dist/cjs/playwright/transformPlaywrightJson');

// Do this as the first thing so that any code reading it knows the right env.
Expand Down Expand Up @@ -113,9 +113,10 @@ const main = async () => {
process.env.TEST_MATCH = '**/*.test.js';
}

// check if main.js exists, throw an error if not
getStorybookMain(runnerOptions.configDir);
process.env.STORYBOOK_CONFIG_DIR = runnerOptions.configDir;

const { storiesPaths } = getStorybookMetadata();
process.env.STORYBOOK_STORIES_PATTERN = storiesPaths;

await executeJestPlaywright(jestOptions);
};
Expand Down
23 changes: 7 additions & 16 deletions playwright/test-runner-jest.config.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,9 @@
const { TEST_ROOT, TEST_MATCH } = process.env;

const roots = TEST_ROOT ? [TEST_ROOT] : undefined;
const { getJestConfig } = require('@storybook/test-runner');

module.exports = {
yannbf marked this conversation as resolved.
Show resolved Hide resolved
cacheDirectory: 'node_modules/.cache/storybook/test-runner',
rootDir: process.cwd(),
roots,
testMatch: [TEST_MATCH || '**/*.stories.[jt]s?(x)'],
transform: {
'^.+\\.stories\\.[jt]sx?$': '@storybook/test-runner/playwright/transform',
'^.+\\.[jt]sx?$': 'babel-jest',
},
preset: 'jest-playwright-preset',
globalSetup: '@storybook/test-runner/playwright/global-setup.js',
globalTeardown: '@storybook/test-runner/playwright/global-teardown.js',
testEnvironment: '@storybook/test-runner/playwright/custom-environment.js',
};
// The default configuration comes from @storybook/test-runner
...getJestConfig()
/** Add your own overrides below
yannbf marked this conversation as resolved.
Show resolved Hide resolved
* @see https://jestjs.io/docs/configuration
*/
}
24 changes: 24 additions & 0 deletions src/config/jest-playwright.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export const getJestConfig = () => {
const { TEST_ROOT, TEST_MATCH, STORYBOOK_STORIES_PATTERN } = process.env;

let config = {
rootDir: process.cwd(),
roots: TEST_ROOT ? [TEST_ROOT] : undefined,
testMatch: STORYBOOK_STORIES_PATTERN && STORYBOOK_STORIES_PATTERN.split(';'),
transform: {
'^.+\\.stories\\.[jt]sx?$': '@storybook/test-runner/playwright/transform',
'^.+\\.[jt]sx?$': 'babel-jest',
},
preset: 'jest-playwright-preset',
globalSetup: '@storybook/test-runner/playwright/global-setup.js',
globalTeardown: '@storybook/test-runner/playwright/global-teardown.js',
testEnvironment: '@storybook/test-runner/playwright/custom-environment.js',
// @TODO: setupFilesAfterEnv: ['@storybook/test-runner/setup']
};

if (TEST_MATCH) {
config.testMatch = [TEST_MATCH];
}

return config;
};
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './playwright/hooks';
export * from './config/jest-playwright';
5 changes: 2 additions & 3 deletions src/playwright/transformPlaywright.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import dedent from 'ts-dedent';
import path from 'path';
import * as coreCommon from '@storybook/core-common';
import * as cli from '../util/cli';
import * as storybookMain from '../util/getStorybookMain';

import { transformPlaywright } from './transformPlaywright';

jest.mock('@storybook/core-common');
jest.mock('../util/cli');

expect.addSnapshotSerializer({
print: (val: any) => val.trim(),
Expand All @@ -17,7 +16,7 @@ describe('Playwright', () => {
beforeEach(() => {
const relativeSpy = jest.spyOn(path, 'relative');
relativeSpy.mockReturnValueOnce('stories/basic/Header.stories.js');
jest.spyOn(cli, 'getStorybookMain').mockImplementation(() => ({
jest.spyOn(storybookMain, 'getStorybookMain').mockImplementation(() => ({
stories: [
{
directory: '../stories/basic',
Expand Down
19 changes: 3 additions & 16 deletions src/playwright/transformPlaywright.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { resolve, relative } from 'path';
import { relative } from 'path';
import template from '@babel/template';
import { normalizeStories } from '@storybook/core-common';
import { autoTitle } from '@storybook/store';

import { getStorybookMain } from '../util/cli';
import { getStorybookMetadata } from '../util';
import { transformCsf } from '../csf/transformCsf';

const filePrefixer = template(`
Expand Down Expand Up @@ -41,19 +40,7 @@ export const testPrefixer = template(
);

const getDefaultTitle = (filename: string) => {
const workingDir = resolve();
const configDir = process.env.STORYBOOK_CONFIG_DIR;

const main = getStorybookMain(configDir);

const normalizedStoriesEntries = normalizeStories(main.stories, {
configDir,
workingDir,
}).map((specifier) => ({
...specifier,
importPathMatcher: new RegExp(specifier.importPathMatcher),
}));

const { workingDir, normalizedStoriesEntries } = getStorybookMetadata();
const filePath = './' + relative(workingDir, filename);

return autoTitle(filePath, normalizedStoriesEntries);
Expand Down
44 changes: 0 additions & 44 deletions src/util/cli.test.ts

This file was deleted.

16 changes: 16 additions & 0 deletions src/util/getCliOptions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { defaultRunnerOptions, getCliOptions } from './getCliOptions';
import * as cliHelper from './getParsedCliOptions';

describe('getCliOptions', () => {
it('returns default options if no extra option is passed', () => {
const opts = getCliOptions();
expect(opts.runnerOptions).toMatchObject(defaultRunnerOptions);
});

it('returns custom options if passed', () => {
const customConfig = { configDir: 'custom', storiesJson: true };
jest.spyOn(cliHelper, 'getParsedCliOptions').mockReturnValue(customConfig);
const opts = getCliOptions();
expect(opts.runnerOptions).toMatchObject(customConfig);
});
});
21 changes: 1 addition & 20 deletions src/util/cli.ts → src/util/getCliOptions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { join, resolve } from 'path';
import { serverRequire, StorybookConfig } from '@storybook/core-common';
import { getParsedCliOptions } from './helpers';
import { getParsedCliOptions } from './getParsedCliOptions';

type CliOptions = {
runnerOptions: {
Expand All @@ -19,8 +17,6 @@ export const defaultRunnerOptions: CliOptions['runnerOptions'] = {
storiesJson: false,
};

let storybookMainConfig: StorybookConfig;

export const getCliOptions = () => {
const allOptions = getParsedCliOptions();

Expand All @@ -46,18 +42,3 @@ export const getCliOptions = () => {
return acc;
}, defaultOptions);
};

export const getStorybookMain = (configDir: string) => {
if (storybookMainConfig) {
return storybookMainConfig;
}

storybookMainConfig = serverRequire(join(resolve(configDir), 'main'));
if (!storybookMainConfig) {
throw new Error(
`Could not load main.js in ${configDir}. Is the config directory correct? You can change it by using --config-dir <path-to-dir>`
);
}

return storybookMainConfig;
};
File renamed without changes.
26 changes: 26 additions & 0 deletions src/util/getStorybookMain.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { getStorybookMain } from './getStorybookMain';
import * as coreCommon from '@storybook/core-common';

jest.mock('@storybook/core-common');

describe('getStorybookMain', () => {
it('should throw an error if no configuration is found', () => {
expect(() => getStorybookMain('.storybook')).toThrow();
});

it('should return mainjs', () => {
const mockedMain = {
stories: [
{
directory: '../stories/basic',
titlePrefix: 'Example',
},
],
};

jest.spyOn(coreCommon, 'serverRequire').mockImplementation(() => mockedMain);

const res = getStorybookMain('.storybook');
expect(res).toMatchObject(mockedMain);
});
});
20 changes: 20 additions & 0 deletions src/util/getStorybookMain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { join, resolve } from 'path';
import { serverRequire } from '@storybook/core-common';
import type { StorybookConfig } from '@storybook/core-common';

let storybookMainConfig: StorybookConfig;

export const getStorybookMain = (configDir: string) => {
if (storybookMainConfig) {
return storybookMainConfig;
}

storybookMainConfig = serverRequire(join(resolve(configDir), 'main'));
if (!storybookMainConfig) {
throw new Error(
`Could not load main.js in ${configDir}. Is the config directory correct? You can change it by using --config-dir <path-to-dir>`
);
}

return storybookMainConfig;
};
68 changes: 68 additions & 0 deletions src/util/getStorybookMetadata.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import * as storybookMain from './getStorybookMain';

import { getStorybookMetadata } from './getStorybookMetadata';

describe.only('getStorybookMetadata', () => {
afterAll(() => {
process.env.STORYBOOK_CONFIG_DIR = undefined;
});

it('should return configDir coming from environment variable', () => {
const mockedMain = {
stories: [],
};

jest.spyOn(storybookMain, 'getStorybookMain').mockReturnValueOnce(mockedMain);
process.env.STORYBOOK_CONFIG_DIR = '.storybook';
const { configDir } = getStorybookMetadata();
expect(configDir).toEqual(process.env.STORYBOOK_CONFIG_DIR);
});

it('should return storiesPath with default glob from CSF3 style config', () => {
const mockedMain = {
stories: [
{
directory: '../stories/basic',
titlePrefix: 'Example',
},
],
};

jest.spyOn(storybookMain, 'getStorybookMain').mockReturnValueOnce(mockedMain);
process.env.STORYBOOK_CONFIG_DIR = '.storybook';
const { storiesPaths } = getStorybookMetadata();
expect(storiesPaths).toMatchInlineSnapshot(
`"<rootDir>/stories/basic/**/*.stories.@(mdx|tsx|ts|jsx|js)"`
);
});

it('should return storiesPath with glob defined in CSF2 style config', () => {
const mockedMain = {
stories: ['../**/stories/*.stories.@(js|ts)'],
};

jest.spyOn(storybookMain, 'getStorybookMain').mockReturnValueOnce(mockedMain);
process.env.STORYBOOK_CONFIG_DIR = '.storybook';
const { storiesPaths } = getStorybookMetadata();
expect(storiesPaths).toMatchInlineSnapshot(`"<rootDir>/**/stories/*.stories.@(js|ts)"`);
});

it('should return storiesPath from mixed CSF2 and CSF3 style config', () => {
const mockedMain = {
stories: [
{
directory: '../stories/basic',
titlePrefix: 'Example',
},
'../stories/complex/*.stories.@(js|ts)',
],
};

jest.spyOn(storybookMain, 'getStorybookMain').mockReturnValueOnce(mockedMain);
process.env.STORYBOOK_CONFIG_DIR = '.storybook';
const { storiesPaths } = getStorybookMetadata();
expect(storiesPaths).toMatchInlineSnapshot(
`"<rootDir>/stories/basic/**/*.stories.@(mdx|tsx|ts|jsx|js);<rootDir>/stories/complex/*.stories.@(js|ts)"`
);
});
});
Loading