How to use indexJsonUrl 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

atom-shell.js

Source:atom-shell.js Github

copy

Full Screen

1'use strict';2var debug = require('debug')('mirrors:sync:atom-shell');3var urllib = require('urllib');4var util = require('util');5var Syncer = require('./syncer');6module.exports = AtomShellSyncer;7function AtomShellSyncer(options) {8 if (!(this instanceof AtomShellSyncer)) {9 return new AtomShellSyncer(options);10 }11 Syncer.call(this, options);12}13util.inherits(AtomShellSyncer, Syncer);14var proto = AtomShellSyncer.prototype;15proto.listdir = function* (fullname) {16 var PADDING = 'atom-shell/dist/';17 var prefix = PADDING + fullname.substring(1);18 var url = this.disturl + '/?max-keys=10000&delimiter=/&prefix=' + prefix;19 var res = yield urllib.request(url, {20 timeout: 60 * 1000,21 dataType: 'text',22 followRedirect: true,23 });24 debug('listdir %s got %s, %j', url, res.status, res.headers);25 var html = res.data || '';26 var items = [];27 // https://gh-contractor-zcbenz.s3.amazonaws.com/?max-keys=10000&delimiter=/&prefix=atom-shell/dist/28 // <CommonPrefixes><Prefix>atom-shell/dist/0.23.0/</Prefix></CommonPrefixes><CommonPrefixes><Prefix>atom-shell/dist/1.1.0/</Prefix></CommonPrefixes><CommonPrefixes><Prefix>atom-shell/dist/1.4.5/</Prefix></CommonPrefixes>29 // <CommonPrefixes>30 // <Prefix>atom-shell/dist/v1.6.3/</Prefix>31 // </CommonPrefixes>32 var dirRe = /<CommonPrefixes><Prefix>([^<]+)<\/Prefix><\/CommonPrefixes>/g;33 while (true) {34 var match = dirRe.exec(html);35 if (!match) {36 break;37 }38 var name = match[1].replace(PADDING, '');39 if (name[0] === '.' || name[0] !== 'v') {40 // <Prefix>0.23.0/</Prefix>41 // <Prefix>.tmp/</Prefix>42 continue;43 }44 if (!this.versionsMap) {45 // make sure version exists on https://gh-contractor-zcbenz.s3.amazonaws.com/atom-shell/dist/index.json46 var indexJSONUrl = 'https://gh-contractor-zcbenz.s3.amazonaws.com/atom-shell/dist/index.json';47 var versions = yield urllib.request(indexJSONUrl, {48 dataType: 'json',49 timeout: 20000,50 });51 this.versionsMap = {};52 for (var i = 0; i < versions.length; i++) {53 var item = versions[i];54 this.versionsMap[item.version] = item;55 }56 }57 // skip not finished version, wait for all files upload success58 var version = name.split('/')[0].substring(1);59 if (!this.versionsMap[version]) {60 continue;61 }62 if (name.indexOf('/x64/') > 0) {63 // <Prefix>v0.16.0/x64/</Prefix>64 name = 'x64/';65 } else if (name.indexOf('/win-x64/') > 0) {66 name = 'win-x64/';67 } else if (name.indexOf('/win-x86/') > 0) {68 name = 'win-x86/';69 }70 debug(name, fullname);71 items.push({72 name: name,73 date: '-',74 size: '-',75 type: 'dir',76 parent: fullname,77 });78 }79 // <Contents><Key>atom-shell/dist/index.json</Key><LastModified>2017-01-24T18:20:12.000Z</LastModified><ETag>&quot;baefa31b950a47a94980399566ecda77&quot;</ETag><Size>40810</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>atom-shell/dist/nan-1.6.1.tgz</Key><LastModified>2015-04-23T02:29:23.000Z</LastModified><ETag>&quot;13ddf39ad45e4371e92a0157db3b2e61&quot;</ETag><Size>36819</Size><StorageClass>STANDARD</StorageClass></Contents>80 var fileRe = /<Contents><Key>([^<]+)<\/Key><LastModified>([^<]+)<\/LastModified><ETag>([^<]+)<\/ETag><Size>(\d+)<\/Size><StorageClass>[^<]+<\/StorageClass><\/Contents>/g;81 while (true) {82 var match = fileRe.exec(html);83 if (!match) {84 break;85 }86 var names = match[1].split('/');87 var name = names[names.length - 1].trim();88 // <Key>atom-shell/dist/index.json</Key>89 if (!name) {90 continue;91 }92 var date = match[2];93 var size = Number(match[4]);94 // ignore file > 200MB95 if (size > 209715200) {96 continue;97 }98 debug(name, date, size, fullname);99 items.push({100 name: name,101 date: date,102 size: size,103 type: 'file',104 parent: fullname,105 downloadURL: this.disturl + '/atom-shell/dist' + fullname + name,106 });107 }108 return items;109};110proto.check = function (checksums, info) {111 if (!info.size) {112 return true;113 }114 return checksums.size === info.size;...

Full Screen

Full Screen

ArticlesList.js

Source:ArticlesList.js Github

copy

Full Screen

1import React, { useState, useRef, useEffect, createRef, useCallback } from "react";2import {DhsArticleLink} from "./TextLink"3import {4 useParams,5 useSearchParams6} from "react-router-dom";7import {Alert} from "react-bootstrap"8import {CenteredLayout} from "./Layout"9const NB_MAX_DISPLAYED_ARTICLES = 10010export function ArticlesListItem({articleTitle, dhsId}){11 return <div className="dhs-articles-list-item">12 <DhsArticleLink dhsId={dhsId}>13 <span className="dhs-articles-list-item-id">{dhsId+" "}</span>14 <span className="dhs-articles-list-item-title">{articleTitle}</span>15 </DhsArticleLink>16 </div>17}18export function searchInIndex(completeIndex, searchTerm){19 const lowerCaseSearchTerm = searchTerm.toLowerCase()20 return completeIndex.filter(aid => aid[1].toLowerCase().indexOf(lowerCaseSearchTerm)!=-1)21}22export function ArticlesList({baseurl=""}) {23 const { language } = useParams();24 25 const indexJsonUrl = baseurl+"/data/indices/"+language+".json"26 const [index, setIndex] = useState([])27 const [completeIndex, setCompleteIndex] = useState([])28 const [searchParams] = useSearchParams();29 const query = searchParams.get("q")30 console.log("------ ArticlesList.js language", language, " cIndex.l", completeIndex.length, " index.l", index.length, " ?q=", query, " ------")31 useEffect(() => {32 document.title = "The Linked HDS"33 }, []);34 // filter index based on URL get parameter ?q=XX35 useEffect(()=>{36 if(query){37 console.log("ArticlesList filtering based on query:", query)38 setIndex(searchInIndex(completeIndex, query))39 }else{40 setIndex(completeIndex) 41 }42 }, [query, completeIndex])43 // fetch index json44 useEffect(()=>{45 fetch(indexJsonUrl).then(x=>x.json()).then(loadedIndex=>{46 setCompleteIndex(loadedIndex)47 })48 }, [indexJsonUrl])49 //console.log("ArticlesList indexJsonUrl: ", indexJsonUrl, " index:", index)50 return (51 <CenteredLayout>52 <Alert className="dhs-article-info" variant="info">53 Using the search bar above you can search for articles.<br/>54 Search is only performed on articles' titles (exact match).<br/>55 </Alert>56 {57 completeIndex.length===0? "Loading articles index..." : (58 index.length>0 ?59 index.filter((a,i)=>i<NB_MAX_DISPLAYED_ARTICLES).map((item,i)=> <ArticlesListItem key={i} dhsId={item[0]} articleTitle={item[1]}/>) :60 'No articles with title matching "'+query+'".'61 )62 }63 </CenteredLayout>64 );65}66export default ArticlesList;67// <Form.Label>Search</Form.Label>68/*...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { indexJsonUrl } from 'storybook-test-runner';2import { indexJsonUrl } from 'storybook-test-runner';3import { indexJsonUrl } from 'storybook-test-runner';4import { indexJsonUrl } from 'storybook-test-runner';5import { indexJsonUrl } from 'storybook-test-runner';6import { indexJsonUrl } from 'storybook-test-runner';7import { indexJsonUrl } from 'storybook-test-runner';8import { indexJsonUrl } from 'storybook-test-runner';9import { indexJsonUrl } from 'storybook-test-runner';10import { indexJsonUrl } from 'storybook-test-runner';11import { indexJsonUrl } from 'storybook-test-runner';12import { indexJsonUrl } from 'storybook-test-runner';13import { indexJsonUrl } from 'storybook-test-runner';14import { indexJsonUrl } from 'storybook-test-runner';15import { indexJsonUrl } from 'storybook-test-runner';16import { indexJsonUrl } from 'storybook-test-runner';17import { indexJsonUrl } from 'storybook-test-runner';18import { indexJsonUrl } from 'storybook

Full Screen

Using AI Code Generation

copy

Full Screen

1const { indexJsonUrl } = require('storybook-test-runner');2const { indexJsonUrl } = require('storybook-test-runner');3const { indexJsonUrl } = require('storybook-test-runner');4const { indexJsonUrl } = require('storybook-test-runner');5const { indexJsonUrl } = require('storybook-test-runner');6const { indexJsonUrl } = require('storybook-test-runner');7const { indexJsonUrl } = require('storybook-test-runner');8const { indexJsonUrl } = require('storybook-test-runner');9const { indexJsonUrl } = require('storybook-test

Full Screen

Using AI Code Generation

copy

Full Screen

1import { indexJsonUrl } from 'storybook-test-runner';2import storybookTestRunner from 'storybook-test-runner';3storybookTestRunner();4{5 "scripts": {6 }7}8storybookTestRunner('Button');

Full Screen

Using AI Code Generation

copy

Full Screen

1import { indexJsonUrl } from 'storybook-test-runner'2import { run } from './index'3import { storiesOf } from '@storybook/react'4import { storiesOf as storiesOfM } from '@storybook/react-native'5 run({ storiesOf, storiesOfM })6})7import { storiesOf } from '@storybook/react'8import { storiesOf as storiesOfM } from '@storybook/react-native'9export function run({ storiesOf, storiesOfM }) {10 storiesOf('Welcome', module).add('to Storybook', () => <div>Hello</div>)11 storiesOfM('Welcome', module).add('to Storybook', () => <div>Hello</div>)12}13{14 {15 "parameters": {16 "options": {}17 }18 }19}20{21 "scripts": {22 },23 "devDependencies": {

Full Screen

Using AI Code Generation

copy

Full Screen

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

Full Screen

Using AI Code Generation

copy

Full Screen

1var storybookTestRunner = require('storybook-test-runner');2var path = require('path');3var testJsonUrl = path.join(__dirname, 'test.json');4storybookTestRunner.indexJsonUrl(testJsonUrl);5{6 {7 },8 {9 }10}11var storybookTestRunner = require('storybook-test-runner');12storybookTestRunner.indexJsonUrl(testJsonUrl);13{14 {

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