Skip to content

Commit

Permalink
Enable strict mode
Browse files Browse the repository at this point in the history
  • Loading branch information
bryanjtc committed Nov 8, 2023
1 parent 33f2385 commit cdcc12f
Show file tree
Hide file tree
Showing 11 changed files with 88 additions and 41 deletions.
19 changes: 19 additions & 0 deletions .github/workflows/typecheck.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
on: [push, pull_request]

jobs:
typecheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2

- name: Use Node.js 18.x
uses: actions/setup-node@v1
with:
node-version: '18.x'

- name: Install dependencies
uses: bahmutov/npm-install@v1

- name: Type check
run: yarn tsc

2 changes: 1 addition & 1 deletion src/config/jest-playwright.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export const getJestConfig = () => {
snapshotSerializers: [jestSerializerHtmlPath],
testEnvironmentOptions: {
'jest-playwright': {
browsers: TEST_BROWSERS.split(',')
browsers: TEST_BROWSERS?.split(',')
.map((p) => p.trim().toLowerCase())
.filter(Boolean),
collectCoverage: STORYBOOK_COLLECT_COVERAGE === 'true',
Expand Down
31 changes: 22 additions & 9 deletions src/csf/transformCsf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,20 @@ const prefixFunction = (
id: t.stringLiteral(toId(title, name)),
};

const result = makeArray(testPrefixer(context));
const stmt = result[1] as t.ExpressionStatement;
return stmt.expression;
let result = input;
if (testPrefixer) {
const prefixResult = makeArray(testPrefixer(context));
const stmt = prefixResult[1] as t.ExpressionStatement;
if (stmt) {
result = stmt.expression;
}
}

if (!result) {
result = t.nullLiteral();

Check warning on line 50 in src/csf/transformCsf.ts

View check run for this annotation

Codecov / codecov/patch

src/csf/transformCsf.ts#L50

Added line #L50 was not covered by tests
}

return result;
};

const makePlayTest = (
Expand Down Expand Up @@ -91,11 +102,11 @@ export const transformCsf = (
makeTitle,
}: TransformOptions = {}
) => {
const csf = loadCsf(code, { makeTitle });
const csf = loadCsf(code, { makeTitle: makeTitle || ((userTitle: string) => userTitle) });
csf.parse();

const storyExports = Object.keys(csf._stories);
const title = csf.meta.title;
const title = csf.meta?.title;

const storyPlays = storyExports.reduce((acc, key) => {
const annotations = csf._storyAnnotations[key];
Expand All @@ -107,14 +118,16 @@ export const transformCsf = (
const playTests = storyExports
.map((key: string) => {
let tests: t.Statement[] = [];
tests = [...tests, ...makePlayTest(key, title, storyPlays[key], testPrefixer)];
if (title) {
tests = [...tests, ...makePlayTest(key, title, storyPlays[key], testPrefixer)];
}

if (tests.length) {
return makeDescribe(key, tests);
}
return null;
})
.filter(Boolean);
.filter(Boolean) as babel.types.Statement[];

const allTests = playTests;

Expand All @@ -123,7 +136,7 @@ export const transformCsf = (
if (!clearBody) result = `${result}${code}\n`;
if (allTests.length) {
const describe = makeDescribe(
csf.meta.title,
csf.meta?.title as string,
allTests,
beforeEachPrefixer ? makeBeforeEach(beforeEachPrefixer) : undefined
) as babel.types.Node;
Expand All @@ -135,7 +148,7 @@ export const transformCsf = (
}
`;
} else if (insertTestIfEmpty) {
result = `describe('${csf.meta.title}', () => { it('no-op', () => {}) });`;
result = `describe('${csf.meta?.title}', () => { it('no-op', () => {}) });`;

Check warning on line 151 in src/csf/transformCsf.ts

View check run for this annotation

Codecov / codecov/patch

src/csf/transformCsf.ts#L151

Added line #L151 was not covered by tests
}
return result;
};
3 changes: 2 additions & 1 deletion src/playwright/transformPlaywright.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ const makeTitleFactory = (filename: string) => {
const { workingDir, normalizedStoriesEntries } = getStorybookMetadata();
const filePath = './' + relative(workingDir, filename);

return (userTitle: string) => userOrAutoTitle(filePath, normalizedStoriesEntries, userTitle);
return (userTitle: string) =>
userOrAutoTitle(filePath, normalizedStoriesEntries, userTitle) as string;
};

export const transformPlaywright = (src: string, filename: string) => {
Expand Down
6 changes: 3 additions & 3 deletions src/setup-page.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Page, BrowserContext } from 'playwright';
import readPackageUp from 'read-pkg-up';
import readPackageUp, { NormalizedReadResult } from 'read-pkg-up';
import { PrepareContext } from './playwright/hooks';
import { getTestRunnerConfig } from './util';

Expand Down Expand Up @@ -55,7 +55,7 @@ export const setupPage = async (page: Page, browserContext: BrowserContext) => {

const viewMode = process.env.VIEW_MODE || 'story';
const renderedEvent = viewMode === 'docs' ? 'docsRendered' : 'storyRendered';
const { packageJson } = await readPackageUp();
const { packageJson } = (await readPackageUp()) as NormalizedReadResult;
const { version: testRunnerVersion } = packageJson;

const referenceURL = process.env.REFERENCE_URL && sanitizeURL(process.env.REFERENCE_URL);
Expand All @@ -73,7 +73,7 @@ export const setupPage = async (page: Page, browserContext: BrowserContext) => {
if (testRunnerConfig?.prepare) {
await testRunnerConfig.prepare({ page, browserContext, testRunnerConfig });
} else {
await defaultPrepare({ page, browserContext, testRunnerConfig });
if (testRunnerConfig) await defaultPrepare({ page, browserContext, testRunnerConfig });
}

// if we ever want to log something from the browser to node
Expand Down
7 changes: 5 additions & 2 deletions src/test-storybook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ process.on('unhandledRejection', (err) => {
});

const log = (message: string) => console.log(`[test-storybook] ${message}`);
const error = (err: { message: any; stack: any }) => {
const error = (err: Error) => {
if (err instanceof Error) {
console.error(`\x1b[31m[test-storybook]\x1b[0m ${err.message} \n\n${err.stack}`);
} else {
Expand Down Expand Up @@ -250,7 +250,10 @@ async function getIndexTempDir(url: string) {
fs.writeFileSync(tmpFile, test as string);
});
} catch (err) {
error(err);
const errorMessage = err instanceof Error ? err.message : String(err);
const errorObject = new Error(errorMessage);
errorObject.stack = err instanceof Error ? err.stack : undefined;
error(errorObject);
process.exit(1);
}
return tmpDir;
Expand Down
16 changes: 10 additions & 6 deletions src/util/getCliOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,20 @@ export const getCliOptions = (): CliOptions => {
jestOptions: process.argv.splice(0, 2),
};

const finalOptions = Object.keys(allOptions).reduce((acc, key: StorybookRunnerCommand) => {
if (STORYBOOK_RUNNER_COMMANDS.includes(key)) {
copyOption(acc.runnerOptions, key, allOptions[key]);
const finalOptions = Object.keys(allOptions).reduce((acc: CliOptions, key: string) => {
if (STORYBOOK_RUNNER_COMMANDS.includes(key as StorybookRunnerCommand)) {
copyOption(
acc.runnerOptions,
key as StorybookRunnerCommand,
allOptions[key as StorybookRunnerCommand]
);
} else {
if (allOptions[key] === true) {
if (allOptions[key as StorybookRunnerCommand] === true) {
acc.jestOptions.push(`--${key}`);
} else if (allOptions[key] === false) {
} else if (allOptions[key as StorybookRunnerCommand] === false) {
acc.jestOptions.push(`--no-${key}`);
} else {
acc.jestOptions.push(`--${key}`, allOptions[key] as string);
acc.jestOptions.push(`--${key}="${allOptions[key as StorybookRunnerCommand]}"`);

Check warning on line 64 in src/util/getCliOptions.ts

View check run for this annotation

Codecov / codecov/patch

src/util/getCliOptions.ts#L64

Added line #L64 was not covered by tests
}
}

Expand Down
34 changes: 19 additions & 15 deletions src/util/getParsedCliOptions.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { CliOptions } from './getCliOptions';
import { program } from 'commander';
import { CommanderError, program } from 'commander';

type ParsedCliOptions = {
options: CliOptions['runnerOptions'];
Expand Down Expand Up @@ -82,23 +82,27 @@ export const getParsedCliOptions = (): ParsedCliOptions => {

try {
program.parse();
} catch (err) {
switch (err.code) {
case 'commander.unknownOption': {
program.outputHelp();
console.warn(
`\nIf you'd like this option to be supported, please open an issue at https://github.com/storybookjs/test-runner/issues/new\n`
);
process.exit(1);
}
} catch (err: unknown) {
if (err instanceof CommanderError) {
switch (err.code) {
case 'commander.unknownOption': {
program.outputHelp();
console.warn(

Check warning on line 90 in src/util/getParsedCliOptions.ts

View check run for this annotation

Codecov / codecov/patch

src/util/getParsedCliOptions.ts#L88-L90

Added lines #L88 - L90 were not covered by tests
`\nIf you'd like this option to be supported, please open an issue at https://github.com/storybookjs/test-runner/issues/new\n`
);
process.exit(1);

Check warning on line 93 in src/util/getParsedCliOptions.ts

View check run for this annotation

Codecov / codecov/patch

src/util/getParsedCliOptions.ts#L93

Added line #L93 was not covered by tests
}

case 'commander.helpDisplayed': {
process.exit(0);
}
case 'commander.helpDisplayed': {
process.exit(0);

Check warning on line 97 in src/util/getParsedCliOptions.ts

View check run for this annotation

Codecov / codecov/patch

src/util/getParsedCliOptions.ts#L96-L97

Added lines #L96 - L97 were not covered by tests
}

default: {
throw err;
default: {
throw err;

Check warning on line 101 in src/util/getParsedCliOptions.ts

View check run for this annotation

Codecov / codecov/patch

src/util/getParsedCliOptions.ts#L100-L101

Added lines #L100 - L101 were not covered by tests
}
}
} else {
throw err;

Check warning on line 105 in src/util/getParsedCliOptions.ts

View check run for this annotation

Codecov / codecov/patch

src/util/getParsedCliOptions.ts#L104-L105

Added lines #L104 - L105 were not covered by tests
}
}

Expand Down
5 changes: 3 additions & 2 deletions src/util/getStorybookMetadata.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { join } from 'path';
import { normalizeStories, getProjectRoot } from '@storybook/core-common';
import { getStorybookMain } from './getStorybookMain';
import { StoriesEntry } from '@storybook/types';

export const getStorybookMetadata = () => {
const workingDir = getProjectRoot();
const configDir = process.env.STORYBOOK_CONFIG_DIR;
const configDir = process.env.STORYBOOK_CONFIG_DIR || '';

const main = getStorybookMain(configDir);
const normalizedStoriesEntries = normalizeStories(main.stories, {
const normalizedStoriesEntries = normalizeStories(main?.stories as StoriesEntry[], {
configDir,
workingDir,
}).map((specifier) => ({
Expand Down
2 changes: 1 addition & 1 deletion src/util/getTestRunnerConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ let testRunnerConfig: TestRunnerConfig;
let loaded = false;

export const getTestRunnerConfig = (
configDir: string = process.env.STORYBOOK_CONFIG_DIR
configDir = process.env.STORYBOOK_CONFIG_DIR || ''
): TestRunnerConfig | undefined => {
// testRunnerConfig can be undefined
if (loaded) {
Expand Down
4 changes: 3 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
"skipLibCheck": true,
"target": "es2020",
"types": ["jest", "node"],
"moduleResolution": "node"
"moduleResolution": "node",
"strict": true,
"noEmit": true,
},
"include": ["src/**/*.ts"],
"exclude": ["src/**/*.test.ts"]
Expand Down

0 comments on commit cdcc12f

Please sign in to comment.