Best JavaScript code snippet using storybook-test-runner
test-storybook.js
Source: test-storybook.js
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};...
Using AI Code Generation
1const { coverageFolderE2E } = require('@storybook/addon-storyshots-puppeteer');2const { coverageFolderE2E } = require('@storybook/addon-storyshots-puppeteer');3const { coverageFolderE2E } = require('@storybook/addon-storyshots-puppeteer');4const { coverageFolderE2E } = require('@storybook/addon-storyshots-puppeteer');5const { coverageFolderE2E } = require('@storybook/addon-storyshots-puppeteer');6const { coverageFolderE2E } = require('@storybook/addon-storyshots-puppeteer');7const { coverageFolderE2E } = require('@storybook/addon-storyshots-puppeteer');8const { coverageFolderE2E } = require('@storybook/addon-storyshots-puppeteer');9const { coverageFolderE2E } = require('@storybook/addon-storyshots-puppeteer');10const { coverageFolderE2E } = require('@storybook/addon-storyshots-puppeteer');11const { coverageFolderE2E } = require('@storybook/addon-storyshots-puppeteer');12const { coverageFolderE2E } = require('@storybook/addon-storyshots-puppeteer');13const { coverageFolderE2E } = require('@storybook/addon-storyshots-puppeteer');14const { coverageFolderE2E } = require('@storybook/addon-storyshots-puppeteer');
Using AI Code Generation
1const { coverageFolderE2E } = require('storybook-test-runner');2const { coverageFolderE2E } = require('storybook-test-runner');3const { coverageFolderE2E } = require('storybook-test-runner');4const { coverageFolderE2E } = require('storybook-test-runner');5const { coverageFolderE2E } = require('storybook-test-runner');6const { coverageFolderE2E } = require('storybook-test-runner');7const { coverageFolderE2E } = require('storybook-test-runner');8const { coverageFolderE2E } = require('storybook-test-runner');9const { coverageFolderE2E } = require('storybook-test-runner');10const { coverageFolderE2E } = require('storybook-test-runner');11const { coverageFolderE2E } = require('storybook-test-runner');12const { coverageFolderE2E } = require('storybook-test-runner');13const { coverageFolderE2E } = require('storybook-test-runner');14const { coverageFolderE2E } = require('storybook-test-runner');
Using AI Code Generation
1const storybookTestRunner = require('storybook-test-runner');2storybookTestRunner.coverageFolderE2E('./.nyc_output');3const storybookTestRunner = require('storybook-test-runner');4storybookTestRunner.coverageFolderUnit('./.nyc_output');5const storybookTestRunner = require('storybook-test-runner');6storybookTestRunner.coverageThreshold(80);7const storybookTestRunner = require('storybook-test-runner');8storybookTestRunner.coverageThresholdError('Coverage threshold not met');9const storybookTestRunner = require('storybook-test-runner');10storybookTestRunner.coverageThresholdErrorType('error');
Using AI Code Generation
1const { coverageFolderE2E } = require('storybook-test-runner');2module.exports = async (config) => {3 config.set({4 coverageFolderE2E: coverageFolderE2E(__dirname),5 });6};7const { coverageFolderE2E } = require('storybook-test-runner');8module.exports = async (config) => {9 config.set({10 coverageFolderE2E: coverageFolderE2E(__dirname),11 });12};13const { coverageFolderE2E } = require('storybook-test-runner');14module.exports = async (config) => {15 config.set({16 coverageFolderE2E: coverageFolderE2E(__dirname),17 });18};19const { coverageFolderE2E } = require('storybook-test-runner');20module.exports = async (config) => {21 config.set({22 coverageFolderE2E: coverageFolderE2E(__dirname),23 });24};25const { coverageFolderE2E } = require('storybook-test-runner');26module.exports = async (config) => {27 config.set({28 coverageFolderE2E: coverageFolderE2E(__dirname),29 });30};31const { coverageFolderE2E } = require('storybook-test-runner');32module.exports = async (config) => {33 config.set({34 coverageFolderE2E: coverageFolderE2E(__dirname),35 });36};37const { coverageFolderE2E } = require('storybook-test-runner');38module.exports = async (config) => {39 config.set({40 coverageFolderE2E: coverageFolderE2E(__dirname),41 });42};
Using AI Code Generation
1const { coverageFolderE2E } = require('storybook-test-runner');2const { join } = require('path');3const storybookPath = join(__dirname, '..', 'storybook');4(async () => {5 const coverageFolder = await coverageFolderE2E(storybookPath);6 console.log(coverageFolder);7})();8"scripts": {9}10### `coverageFolderE2E(storybookPath, [options])`11Default: `{}`12Default: `{}`
Using AI Code Generation
1const { testRunner } = require('@storybook/csf-tools');2const { coverageFolderE2E } = testRunner;3coverageFolderE2E(4).then(() => {5 console.log('done testing');6});7const { testRunner } = require('@storybook/csf-tools');8const { coverageStoryE2E } = testRunner;9coverageStoryE2E(10).then(() => {11 console.log('done testing');12});13const { testRunner
Check out the latest blogs from LambdaTest on this topic:
Agile software development stems from a philosophy that being agile means creating and responding to change swiftly. Agile means having the ability to adapt and respond to change without dissolving into chaos. Being Agile involves teamwork built on diverse capabilities, skills, and talents. Team members include both the business and software development sides working together to produce working software that meets or exceeds customer expectations continuously.
The events over the past few years have allowed the world to break the barriers of traditional ways of working. This has led to the emergence of a huge adoption of remote working and companies diversifying their workforce to a global reach. Even prior to this many organizations had already had operations and teams geographically dispersed.
Web applications continue to evolve at an unbelievable pace, and the architecture surrounding web apps get more complicated all of the time. With the growth in complexity of the web application and the development process, web application testing also needs to keep pace with the ever-changing demands.
Even though several frameworks are available in the market for automation testing, Selenium is one of the most renowned open-source frameworks used by experts due to its numerous features and benefits.
In 2007, Steve Jobs launched the first iPhone, which revolutionized the world. But because of that, many businesses dealt with the problem of changing the layout of websites from desktop to mobile by delivering completely different mobile-compatible websites under the subdomain of ‘m’ (e.g., https://m.facebook.com). And we were all trying to figure out how to work in this new world of contending with mobile and desktop screen sizes.
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!