How to use titleIdToTest method in storybook-test-runner

Best JavaScript code snippet using storybook-test-runner

test-storybook.js

Source:test-storybook.js Github

copy

Full Screen

1#!/usr/bin/env node2//@ts-check3'use strict';4const { execSync } = require('child_process');5const fetch = require('node-fetch');6const canBindToHost = require('can-bind-to-host').default;7const fs = require('fs');8const dedent = require('ts-dedent').default;9const path = require('path');10const tempy = require('tempy');11const semver = require('semver');12const { getCliOptions, getStorybookMetadata } = require('../dist/cjs/util');13const { transformPlaywrightJson } = require('../dist/cjs/playwright/transformPlaywrightJson');14// Do this as the first thing so that any code reading it knows the right env.15process.env.BABEL_ENV = 'test';16process.env.NODE_ENV = 'test';17process.env.PUBLIC_URL = '';18// Makes the script crash on unhandled rejections instead of silently19// ignoring them. In the future, promise rejections that are not handled will20// terminate the Node.js process with a non-zero exit code.21process.on('unhandledRejection', (err) => {22 throw err;23});24const log = (message) => console.log(`[test-storybook] ${message}`);25const error = (message) => console.error(`[test-storybook] ${message}`);26// Clean up tmp files globally in case of control-c27let indexTmpDir;28const cleanup = () => {29 if (indexTmpDir) {30 log(`Cleaning up ${indexTmpDir}`);31 fs.rmSync(indexTmpDir, { recursive: true, force: true });32 }33};34let isWatchMode = false;35async function reportCoverage() {36 if (isWatchMode || process.env.STORYBOOK_COLLECT_COVERAGE !== 'true') {37 return;38 }39 const coverageFolderE2E = path.resolve(process.cwd(), '.nyc_output');40 const coverageFolder = path.resolve(process.cwd(), 'coverage/storybook');41 // in case something goes wrong and .nyc_output does not exist, bail42 if (!fs.existsSync(coverageFolderE2E)) {43 return;44 }45 // if there's no coverage folder, create one46 if (!fs.existsSync(coverageFolder)) {47 fs.mkdirSync(coverageFolder, { recursive: true });48 }49 // move the coverage files from .nyc_output folder (coming from jest-playwright) to coverage, then delete .nyc_output50 fs.renameSync(`${coverageFolderE2E}/coverage.json`, `${coverageFolder}/coverage-storybook.json`);51 fs.rmSync(coverageFolderE2E, { recursive: true });52 // --skip-full in case we only want to show not fully covered code53 // --check-coverage if we want to break if coverage reaches certain threshold54 // .nycrc will be respected for thresholds etc. https://www.npmjs.com/package/nyc#coverage-thresholds55 execSync(`npx nyc report --reporter=text -t ${coverageFolder} --report-dir ${coverageFolder}`, {56 stdio: 'inherit',57 });58}59const onProcessEnd = () => {60 cleanup();61 reportCoverage();62};63process.on('SIGINT', onProcessEnd);64process.on('exit', onProcessEnd);65function sanitizeURL(url) {66 let finalURL = url;67 // prepend URL protocol if not there68 if (finalURL.indexOf('http://') === -1 && finalURL.indexOf('https://') === -1) {69 finalURL = 'http://' + finalURL;70 }71 // remove iframe.html if present72 finalURL = finalURL.replace(/iframe.html\s*$/, '');73 // remove index.html if present74 finalURL = finalURL.replace(/index.html\s*$/, '');75 // add forward slash at the end if not there76 if (finalURL.slice(-1) !== '/') {77 finalURL = finalURL + '/';78 }79 return finalURL;80}81async function executeJestPlaywright(args) {82 // Always prefer jest installed via the test runner. If it's hoisted, it will get it from root node_modules83 const jestPath = path.dirname(84 require.resolve('jest', {85 paths: [path.join(__dirname, '../@storybook/test-runner/node_modules')],86 })87 );88 const jest = require(jestPath);89 let argv = args.slice(2);90 const jestConfigPath = fs.existsSync('test-runner-jest.config.js')91 ? 'test-runner-jest.config.js'92 : path.resolve(__dirname, '../playwright/test-runner-jest.config.js');93 argv.push('--config', jestConfigPath);94 await jest.run(argv);95}96async function checkStorybook(url) {97 try {98 const res = await fetch(url, { method: 'HEAD' });99 if (res.status !== 200) throw new Error(`Unxpected status: ${res.status}`);100 } catch (e) {101 console.error(102 dedent`[test-storybook] It seems that your Storybook instance is not running at: ${url}. Are you sure it's running?103 104 If you're not running Storybook on the default 6006 port or want to run the tests against any custom URL, you can pass the --url flag like so:105 106 yarn test-storybook --url http://localhost:9009107 108 More info at https://github.com/storybookjs/test-runner#getting-started`109 );110 process.exit(1);111 }112}113async function getIndexJson(url) {114 const indexJsonUrl = new URL('index.json', url).toString();115 const storiesJsonUrl = new URL('stories.json', url).toString();116 const [indexRes, storiesRes] = await Promise.all([fetch(indexJsonUrl), fetch(storiesJsonUrl)]);117 if (indexRes.ok) {118 try {119 const json = await indexRes.text();120 return JSON.parse(json);121 } catch (err) {}122 }123 if (storiesRes.ok) {124 try {125 const json = await storiesRes.text();126 return JSON.parse(json);127 } catch (err) {}128 }129 throw new Error(dedent`130 Failed to fetch index data from the project.131 Make sure that either of these URLs are available with valid data in your Storybook:132 ${133 // TODO: switch order once index.json becomes more common than stories.json134 storiesJsonUrl135 }136 ${indexJsonUrl}137 More info: https://github.com/storybookjs/test-runner/blob/main/README.md#indexjson-mode138 `);139}140async function getIndexTempDir(url) {141 let tmpDir;142 try {143 const indexJson = await getIndexJson(url);144 const titleIdToTest = transformPlaywrightJson(indexJson);145 tmpDir = tempy.directory();146 Object.entries(titleIdToTest).forEach(([titleId, test]) => {147 const tmpFile = path.join(tmpDir, `${titleId}.test.js`);148 fs.writeFileSync(tmpFile, test);149 });150 } catch (err) {151 error(err);152 process.exit(1);153 }154 return tmpDir;155}156function ejectConfiguration() {157 const origin = path.resolve(__dirname, '../playwright/test-runner-jest.config.js');158 const destination = path.resolve('test-runner-jest.config.js');159 const fileAlreadyExists = fs.existsSync(destination);160 if (fileAlreadyExists) {161 throw new Error(dedent`Found existing file at:162 163 ${destination}164 165 Please delete it and rerun this command.166 \n`);167 }168 fs.copyFileSync(origin, destination);169 log('Configuration file successfully copied as test-runner-jest.config.js');170}171const main = async () => {172 const { jestOptions, runnerOptions } = getCliOptions();173 if (runnerOptions.eject) {174 ejectConfiguration();175 process.exit(0);176 }177 // set this flag to skip reporting coverage in watch mode178 isWatchMode = jestOptions.watch || jestOptions.watchAll;179 const rawTargetURL = process.env.TARGET_URL || runnerOptions.url || 'http://localhost:6006';180 await checkStorybook(rawTargetURL);181 const targetURL = sanitizeURL(rawTargetURL);182 process.env.TARGET_URL = targetURL;183 if (runnerOptions.coverage) {184 process.env.STORYBOOK_COLLECT_COVERAGE = 'true';185 }186 if (runnerOptions.junit) {187 process.env.STORYBOOK_JUNIT = 'true';188 }189 if (process.env.REFERENCE_URL) {190 process.env.REFERENCE_URL = sanitizeURL(process.env.REFERENCE_URL);191 }192 // Use TEST_BROWSERS if set, otherwise get from --browser option193 if (!process.env.TEST_BROWSERS && runnerOptions.browsers) {194 process.env.TEST_BROWSERS = runnerOptions.browsers.join(',');195 }196 const { hostname } = new URL(targetURL);197 const isLocalStorybookIp = await canBindToHost(hostname);198 const shouldRunIndexJson = runnerOptions.indexJson !== false && !isLocalStorybookIp;199 if (shouldRunIndexJson) {200 log(201 'Detected a remote Storybook URL, running in index json mode. To disable this, run the command again with --no-index-json\n'202 );203 }204 if (runnerOptions.indexJson || shouldRunIndexJson) {205 indexTmpDir = await getIndexTempDir(targetURL);206 process.env.TEST_ROOT = indexTmpDir;207 process.env.TEST_MATCH = '**/*.test.js';208 }209 process.env.STORYBOOK_CONFIG_DIR = runnerOptions.configDir;210 const { storiesPaths, lazyCompilation } = getStorybookMetadata();211 process.env.STORYBOOK_STORIES_PATTERN = storiesPaths;212 if (lazyCompilation && isLocalStorybookIp) {213 log(214 `You're running Storybook with lazy compilation enabled, and will likely cause issues with the test runner locally. Consider disabling 'lazyCompilation' in ${runnerOptions.configDir}/main.js when running 'test-storybook' locally.`215 );216 }217 await executeJestPlaywright(jestOptions);218};...

Full Screen

Full Screen

transformPlaywrightJson.ts

Source:transformPlaywrightJson.ts Github

copy

Full Screen

1import * as t from '@babel/types';2import generate from '@babel/generator';3import { ComponentTitle, StoryId, StoryName, toId } from '@storybook/csf';4import { testPrefixer } from './transformPlaywright';5const makeTest = (entry: V4Entry): t.Statement => {6 const result: any = testPrefixer({7 name: t.stringLiteral(entry.name),8 title: t.stringLiteral(entry.title),9 id: t.stringLiteral(entry.id),10 // FIXME11 storyExport: t.identifier(entry.id),12 });13 const stmt = result[1] as t.ExpressionStatement;14 return t.expressionStatement(15 t.callExpression(t.identifier('it'), [t.stringLiteral('test'), stmt.expression])16 );17};18const makeDescribe = (title: string, stmts: t.Statement[]) => {19 return t.expressionStatement(20 t.callExpression(t.identifier('describe'), [21 t.stringLiteral(title),22 t.arrowFunctionExpression([], t.blockStatement(stmts)),23 ])24 );25};26type V4Entry = { type?: 'story' | 'docs'; id: StoryId; name: StoryName; title: ComponentTitle };27type V4Index = {28 v: 4;29 entries: Record<StoryId, V4Entry>;30};31type V3Story = Omit<V4Entry, 'type'> & { parameters?: Record<string, any> };32type V3StoriesIndex = {33 v: 3;34 stories: Record<StoryId, V3Story>;35};36const isV3DocsOnly = (stories: V3Story[]) => stories.length === 1 && stories[0].name === 'Page';37function v3TitleMapToV4TitleMap(titleIdToStories: Record<string, V3Story[]>) {38 return Object.fromEntries(39 Object.entries(titleIdToStories).map(([id, stories]) => [40 id,41 stories.map(42 ({ parameters, ...story }) =>43 ({44 type: isV3DocsOnly(stories) ? 'docs' : 'story',45 ...story,46 } as V4Entry)47 ),48 ])49 );50}51function groupByTitleId<T extends { title: ComponentTitle }>(entries: T[]) {52 return entries.reduce((acc, entry) => {53 const titleId = toId(entry.title);54 acc[titleId] = acc[titleId] || [];55 acc[titleId].push(entry);56 return acc;57 }, {} as { [key: string]: T[] });58}59/**60 * Generate one test file per component so that Jest can61 * run them in parallel.62 */63export const transformPlaywrightJson = (index: Record<string, any>) => {64 let titleIdToEntries: Record<string, V4Entry[]>;65 if (index.v === 3) {66 const titleIdToStories = groupByTitleId<V3Story>(67 Object.values((index as V3StoriesIndex).stories)68 );69 titleIdToEntries = v3TitleMapToV4TitleMap(titleIdToStories);70 } else if (index.v === 4) {71 titleIdToEntries = groupByTitleId<V4Entry>(Object.values((index as V4Index).entries));72 } else {73 throw new Error(`Unsupported version ${index.v}`);74 }75 const titleIdToTest = Object.entries(titleIdToEntries).reduce((acc, [titleId, entries]) => {76 const stories = entries.filter((s) => s.type !== 'docs');77 if (stories.length) {78 const storyTests = stories.map((story) => makeDescribe(story.name, [makeTest(story)]));79 const program = t.program([makeDescribe(stories[0].title, storyTests)]);80 const { code } = generate(program, {});81 acc[titleId] = code;82 }83 return acc;84 }, {} as { [key: string]: string });85 return titleIdToTest;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { titleIdToTest } from 'storybook-test-runner';2describe('test', () => {3 it('test', () => {4 titleIdToTest('Button', 'Button');5 });6});7import React from 'react';8import { storiesOf } from '@storybook/react';9import Button from './Button';10storiesOf('Button', module).add('Button', () => <Button />);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { titleIdToTest } = require('storybook-test-runner');2const { storiesOf } = require('@storybook/react');3const myStory = storiesOf('MyStory', module);4myStory.add('Story 1', () => <div>Story 1</div>);5myStory.add('Story 2', () => <div>Story 2</div>);6const { storyIdToTest } = require('storybook-test-runner');7const { storiesOf } = require('@storybook/react');8const myStory = storiesOf('MyStory', module);9myStory.add('Story 1', () => <div>Story 1</div>);10myStory.add('Story 2', () => <div>Story 2</div>);11const { storyIdToTest } = require('storybook-test-runner');12const { storiesOf } = require('@storybook/react');13const myStory = storiesOf('MyStory', module);14myStory.add('Story 1', () => <div>Story 1</div>);15myStory.add('Story 2', () => <div>Story 2</div>);16const { getStorybook } = require('storybook-test-runner');17const { storiesOf } = require('@storybook/react');18const myStory = storiesOf('MyStory', module);19myStory.add('Story 1', () => <div>Story 1</div>);20myStory.add('Story 2', () => <div>Story 2</div>);21const { getStorybook } = require('storybook-test-runner');22const { storiesOf } = require('@storybook/react');23const myStory = storiesOf('MyStory', module);24myStory.add('Story

Full Screen

Using AI Code Generation

copy

Full Screen

1const {titleIdToTest} = require('storybook-test-runner');2const title = titleIdToTest('Button');3const {titleIdToTest} = require('storybook-test-runner');4const title = titleIdToTest('Button');5const {titleIdToTest} = require('storybook-test-runner');6const title = titleIdToTest('Button');7const {titleIdToTest} = require('storybook-test-runner');8const title = titleIdToTest('Button');9const {titleIdToTest} = require('storybook-test-runner');10const title = titleIdToTest('Button');11const {titleIdToTest} = require('storybook-test-runner');12const title = titleIdToTest('Button');13const {titleIdToTest} = require('storybook-test-runner');14const title = titleIdToTest('Button');15const {titleIdToTest} = require('storybook-test-runner');16const title = titleIdToTest('Button');17const {titleIdToTest} = require('storybook-test-runner');18const title = titleIdToTest('Button');19const {titleIdToTest} = require('storybook-test-runner');20const title = titleIdToTest('Button');

Full Screen

Using AI Code Generation

copy

Full Screen

1import { titleIdToTest } from 'storybook-test-runner';2import { storiesOf } from '@storybook/react';3storiesOf('Test', module).add('test story', () => {4 return <h1>Test</h1>;5});6titleIdToTest('Test', 'test story');7import { titleToTest } from 'storybook-test-runner';8import { storiesOf } from '@storybook/react';9storiesOf('Test', module).add('test story', () => {10 return <h1>Test</h1>;11});12titleToTest('Test');13import { storybookTestRunner } from 'storybook-test-runner';14import { storiesOf } from '@storybook/react';15storiesOf('Test', module).add('test story', () => {16 return <h1>Test</h1>;17});18storybookTestRunner();19import { storybookTestRunner } from 'storybook-test-runner';20import { storiesOf } from '@storybook/react';21storiesOf('Test', module).add('test story', () => {22 return <h1>Test</h1>;23});24storybookTestRunner({25 stories: {26 Test: {27 'test story': {28 }29 }30 }31});32import { storybookTestRunner } from 'storybook-test-runner';33import { storiesOf } from '@storybook/react';34storiesOf('Test', module).add('test story', () => {35 return <h1>Test</h1>;36});37storybookTestRunner({38 stories: {39 Test: {40 'test story': {41 }42 }43 },44});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { titleIdToTest } from 'storybook-test-runner';2import Title from './Title';3titleIdToTest(1, Title);4import { titleIdToTest } from 'storybook-test-runner';5titleIdToTest(1, Title);6import { titleIdToTest } from 'storybook-test-runner';7titleIdToTest(1, Title);8import { titleIdToTest } from 'storybook-test-runner';9titleIdToTest(1, Title);10import { titleIdToTest } from 'storybook-test-runner';11titleIdToTest(1, Title);12import { titleIdToTest } from 'storybook-test-runner';13titleIdToTest(1, Title);14import { titleIdToTest } from 'storybook-test-runner';15titleIdToTest(1, Title);16import { titleIdToTest } from 'storybook-test-runner';17titleIdToTest(1, Title);18import { titleIdToTest } from 'storybook-test-runner';19titleIdToTest(1, Title);20import { titleIdToTest } from 'storybook-test-runner';21titleIdToTest(1, Title);22import { titleIdToTest } from 'storybook-test-runner';

Full Screen

Using AI Code Generation

copy

Full Screen

1import { titleIdToTest } from 'storybook-test-runner';2import { stories } from './stories';3titleIdToTest(stories, 'component', 'component-id');4titleIdToTest(stories, 'component', 'component-id', {customProps: 'customValue'});5titleIdToTest(stories, 'component', 'component-id', {customProps: 'customValue'}, {customState: 'customValue'});6titleIdToTest(stories, 'component', 'component-id', {}, {customState: 'customValue'});7titleIdToTest(stories, 'component', 'component-id', {customProps: 'customValue'}, {customState: 'customValue'}, {customContext: 'customValue'});8titleIdToTest(stories, 'component', 'component-id', {customProps: 'customValue'}, {}, {customContext: 'customValue'});9titleIdToTest(stories, 'component', 'component-id', {}, {customState: 'customValue'}, {customContext: 'customValue'});10titleIdToTest(stories, 'component', 'component-id', {customProps: 'customValue'}, {customState: 'customValue'}, {customContext: 'customValue'}, {customContextTypes: 'customValue'});11titleIdToTest(stories, 'component', 'component-id', {customProps: 'customValue'}, {}, {customContext: 'customValue'}, {customContextTypes: 'customValue'});12titleIdToTest(stories, 'component', 'component-id', {}, {customState: 'customValue'}, {customContext: 'customValue'}, {customContextTypes: 'customValue'});13titleIdToTest(stories, 'component', 'component-id', {customProps: 'customValue'}, {customState

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-test-runner automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful