Best JavaScript code snippet using storybook-test-runner
test-storybook.js
Source:test-storybook.js
...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 { executeJestPlaywright } = require('storybook-test-runner');2const { join } = require('path');3executeJestPlaywright({4 storybookConfigDir: join(__dirname, '../.storybook'),5});6import { getStoryUrl, takeScreenShot } from 'storybook-test-runner';7describe('Button', () => {8 it('should render button', async () => {9 const storyUrl = getStoryUrl('Button', 'Primary');10 await page.goto(storyUrl);11 const image = await takeScreenShot(page, 'Button');12 expect(image).toMatchImageSnapshot();13 });14});15describe('Button', () => {16 it('should render button', async () => {17 const storyUrl = getStoryUrl('Button', 'Primary');18 await page.goto(storyUrl);19 const image = await takeScreenShot(page, 'Button');20 expect(image).toMatchImageSnapshot();21 });22});
Using AI Code Generation
1const { executeJestPlaywright } = require('storybook-test-runner');2executeJestPlaywright();3import { toMatchImageSnapshot } from 'jest-image-snapshot';4expect.extend({ toMatchImageSnapshot });5import { getStorybook, configureToMatchImageSnapshot } from 'storybook-test-runner';6const toMatchImageSnapshot = configureToMatchImageSnapshot({7 customDiffConfig: { threshold: 0.1 },8});9const storybook = getStorybook(['./stories']);10describe('Image snapshot', () => {11 storybook.forEach((story) => {12 story.stories.forEach((s) => {13 it(`should match image snapshot for ${s.name}`, async () => {14 const page = await global.__BROWSER__.newPage();15 await page.goto(s.url);16 const image = await page.screenshot();17 expect(image).toMatchImageSnapshot();18 });19 });20 });21});22"scripts": {23}
Using AI Code Generation
1import { executeJestPlaywright } from 'storybook-test-runner';2executeJestPlaywright({3});4module.exports = {5 testEnvironmentOptions: {6 'jest-playwright': {7 },8 },9};10{11 "scripts": {12 },13 "devDependencies": {14 }15}16module.exports = {17 stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],18 jest: async (options) => {19 options.preset = require.resolve('jest-playwright-preset/jest-preset.js');20 return options;21 },22};23import { setConsoleOptions } from '@storybook/addon-console';24import { addParameters } from '@storybook/react';25import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport';26setConsoleOptions({27});28addParameters({29 viewport: {30 },31});32import { addons } from '@storybook/addons';33import { themes } from '@storybook/theming';34addons.setConfig({35});
Using AI Code Generation
1const { executeJestPlaywright } = require("storybook-test-runner");2executeJestPlaywright();3const { configureToMatchImageSnapshot } = require("jest-image-snapshot");4const path = require("path");5const toMatchImageSnapshot = configureToMatchImageSnapshot({6 customDiffDir: path.join(__dirname, "image-diff"),7 customSnapshotsDir: path.join(__dirname, "image-snapshots"),8 customDiffConfig: { threshold: 0.1 },9});10expect.extend({ toMatchImageSnapshot });11module.exports = {12 launchOptions: {13 },14 contextOptions: {15 },16 serverOptions: {17 },18};19"scripts": {20 }21}
Using AI Code Generation
1import { executeJestPlaywright } from 'storybook-test-runner';2executeJestPlaywright({3 storybookLaunchOptions: {4 },5 coverageConfig: {6 '**/src/**/*.{js,jsx,ts,tsx}',7 '!**/src/**/*.stories.{js,jsx,ts,tsx}',8 coverageThreshold: {9 global: {10 },11 },12 },13});14module.exports = {15 serverOptions: {16 },17};18{19 "scripts": {20 },21 "devDependencies": {22 }23}24module.exports = {25};
Using AI Code Generation
1const { executeJestPlaywright } = require('storybook-test-runner');2executeJestPlaywright({3 config: {4 launch: {5 },6 context: {7 },8 page: {9 },10 },11});
Using AI Code Generation
1const { executeJestPlaywright } = require('storybook-test-runner');2const path = require('path');3const storybookConfig = require('./.storybook/main.js');4const storybookPath = path.resolve(__dirname, './.storybook');5const storybookPort = 6006;6const jestConfig = require('./jest.config.js');7const testRunner = async () => {8 await executeJestPlaywright({9 });10};11testRunner();
Using AI Code Generation
1const { executeJestPlaywright } = require('storybook-test-runner');2executeJestPlaywright({3});4module.exports = {5 testEnvironmentOptions: {6 'jest-playwright': {7 },8 },9};10const { executeJestPlaywright } = require('storybook-test-runner');11executeJestPlaywright({12});13module.exports = {14 testEnvironmentOptions: {15 'jest-playwright': {16 },17 },18};19const { executeJestPlaywright } = require('storybook-test-runner');20executeJestPlaywright({21});22module.exports = {
Using AI Code Generation
1const { executeJestPlaywright } = require('storybook-test-runner');2executeJestPlaywright({3});4const { testStory } = require('storybook-test-runner');5describe('Example', () => {6 testStory('Example', 'Default', async ({ page }) => {7 await page.waitForSelector('button');8 await page.click('button');9 const text = await page.textContent('button');10 expect(text).toBe('Clicked');11 });12});13const { testStory } = require('storybook-test-runner');14describe('AnotherExample', () => {15 testStory('AnotherExample', 'Default', async ({ page }) => {16 await page.waitForSelector('button');17 await page.click('button');18 const text = await page.textContent('button');19 expect(text).toBe('Clicked');20 });21});22const { executeJestPlaywright } = require('storybook-test-runner');23executeJestPlaywright({24});
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!!