Best JavaScript code snippet using storybook-root
normalize-stories.test.ts
Source:normalize-stories.test.ts
1import dedent from 'ts-dedent';2import { normalizeStoriesEntry } from '../normalize-stories';3expect.addSnapshotSerializer({4 print: (val: any) => JSON.stringify(val, null, 2),5 test: (val) => typeof val !== 'string',6});7expect.extend({8 toMatchPaths(regex: RegExp, paths: string[]) {9 const matched = paths.map((p) => !!p.match(regex));10 const pass = matched.every(Boolean);11 const failures = paths.filter((_, i) => (pass ? matched[i] : !matched[i]));12 const message = () => dedent`Expected ${regex} to ${pass ? 'not ' : ''}match all strings.13 14 Failures:${['', ...failures].join('\n - ')}`;15 return {16 pass,17 message,18 };19 },20});21jest.mock('fs', () => {22 const mockStat = (23 path: string,24 options: Record<string, any>,25 cb: (error?: Error, stats?: Record<string, any>) => void26 ) => {27 cb(undefined, {28 isDirectory: () => !path.match(/\.[a-z]+$/),29 });30 };31 return {32 access: (path: string, mode: number, cb: (err?: Error) => void): void => undefined,33 lstatSync: (path: string) => ({34 isDirectory: () => !path.match(/\.[a-z]+$/),35 }),36 stat: mockStat,37 lstat: mockStat,38 };39});40describe('normalizeStoriesEntry', () => {41 const options = {42 configDir: '/path/to/project/.storybook',43 workingDir: '/path/to/project',44 };45 it('direct file path', () => {46 const specifier = normalizeStoriesEntry('../path/to/file.stories.mdx', options);47 expect(specifier).toMatchInlineSnapshot(`48 {49 "titlePrefix": "",50 "directory": "./path/to",51 "files": "file.stories.mdx",52 "importPathMatcher": {}53 }54 `);55 expect(specifier.importPathMatcher).toMatchPaths(['./path/to/file.stories.mdx']);56 expect(specifier.importPathMatcher).not.toMatchPaths([57 './path/to/file.stories.js',58 './file.stories.mdx',59 '../file.stories.mdx',60 ]);61 });62 it('story in config dir', () => {63 const specifier = normalizeStoriesEntry('./file.stories.mdx', options);64 expect(specifier).toMatchInlineSnapshot(`65 {66 "titlePrefix": "",67 "directory": "./.storybook",68 "files": "file.stories.mdx",69 "importPathMatcher": {}70 }71 `);72 expect(specifier.importPathMatcher).toMatchPaths(['./.storybook/file.stories.mdx']);73 expect(specifier.importPathMatcher).not.toMatchPaths([74 '.storybook/file.stories.mdx',75 './file.stories.mdx',76 '../file.stories.mdx',77 ]);78 });79 it('non-recursive files glob', () => {80 const specifier = normalizeStoriesEntry('../*/*.stories.mdx', options);81 expect(specifier).toMatchInlineSnapshot(`82 {83 "titlePrefix": "",84 "directory": ".",85 "files": "*/*.stories.mdx",86 "importPathMatcher": {}87 }88 `);89 expect(specifier.importPathMatcher).toMatchPaths([90 './path/file.stories.mdx',91 './second-path/file.stories.mdx',92 ]);93 expect(specifier.importPathMatcher).not.toMatchPaths([94 './path/file.stories.js',95 './path/to/file.stories.mdx',96 './file.stories.mdx',97 '../file.stories.mdx',98 ]);99 });100 it('double non-recursive directory/files glob', () => {101 const specifier = normalizeStoriesEntry('../*/*/*.stories.mdx', options);102 expect(specifier).toMatchInlineSnapshot(`103 {104 "titlePrefix": "",105 "directory": ".",106 "files": "*/*/*.stories.mdx",107 "importPathMatcher": {}108 }109 `);110 expect(specifier.importPathMatcher).toMatchPaths([111 './path/to/file.stories.mdx',112 './second-path/to/file.stories.mdx',113 ]);114 expect(specifier.importPathMatcher).not.toMatchPaths([115 './file.stories.mdx',116 './path/file.stories.mdx',117 './path/to/third/file.stories.mdx',118 './path/to/file.stories.js',119 '../file.stories.mdx',120 ]);121 });122 it('directory/files glob', () => {123 const specifier = normalizeStoriesEntry('../**/*.stories.mdx', options);124 expect(specifier).toMatchInlineSnapshot(`125 {126 "titlePrefix": "",127 "directory": ".",128 "files": "**/*.stories.mdx",129 "importPathMatcher": {}130 }131 `);132 expect(specifier.importPathMatcher).toMatchPaths([133 './file.stories.mdx',134 './path/file.stories.mdx',135 './path/to/file.stories.mdx',136 './path/to/third/file.stories.mdx',137 ]);138 expect(specifier.importPathMatcher).not.toMatchPaths([139 './file.stories.js',140 '../file.stories.mdx',141 ]);142 });143 it('double stars glob', () => {144 const specifier = normalizeStoriesEntry('../**/foo/**/*.stories.mdx', options);145 expect(specifier).toMatchInlineSnapshot(`146 {147 "titlePrefix": "",148 "directory": ".",149 "files": "**/foo/**/*.stories.mdx",150 "importPathMatcher": {}151 }152 `);153 expect(specifier.importPathMatcher).toMatchPaths([154 './foo/file.stories.mdx',155 './path/to/foo/file.stories.mdx',156 './path/to/foo/third/fourth/file.stories.mdx',157 ]);158 expect(specifier.importPathMatcher).not.toMatchPaths([159 './file.stories.mdx',160 './file.stories.js',161 '../file.stories.mdx',162 ]);163 });164 it('intermediate directory glob', () => {165 const specifier = normalizeStoriesEntry('../**/foo/*.stories.mdx', options);166 expect(specifier).toMatchInlineSnapshot(`167 {168 "titlePrefix": "",169 "directory": ".",170 "files": "**/foo/*.stories.mdx",171 "importPathMatcher": {}172 }173 `);174 expect(specifier.importPathMatcher).toMatchPaths([175 './path/to/foo/file.stories.mdx',176 './foo/file.stories.mdx',177 ]);178 expect(specifier.importPathMatcher).not.toMatchPaths([179 './file.stories.mdx',180 './file.stories.js',181 './path/to/foo/third/fourth/file.stories.mdx',182 '../file.stories.mdx',183 ]);184 });185 it('directory outside of working dir', () => {186 const specifier = normalizeStoriesEntry('../../src/*.stories.mdx', options);187 expect(specifier).toMatchInlineSnapshot(`188 {189 "titlePrefix": "",190 "directory": "../src",191 "files": "*.stories.mdx",192 "importPathMatcher": {}193 }194 `);195 expect(specifier.importPathMatcher).toMatchPaths(['../src/file.stories.mdx']);196 expect(specifier.importPathMatcher).not.toMatchPaths([197 './src/file.stories.mdx',198 '../src/file.stories.js',199 ]);200 });201 it('directory', () => {202 const specifier = normalizeStoriesEntry('..', options);203 expect(specifier).toMatchInlineSnapshot(`204 {205 "titlePrefix": "",206 "directory": ".",207 "files": "**/*.stories.@(mdx|tsx|ts|jsx|js)",208 "importPathMatcher": {}209 }210 `);211 });212 it('directory specifier', () => {213 const specifier = normalizeStoriesEntry({ directory: '..' }, options);214 expect(specifier).toMatchInlineSnapshot(`215 {216 "titlePrefix": "",217 "files": "**/*.stories.@(mdx|tsx|ts|jsx|js)",218 "directory": ".",219 "importPathMatcher": {}220 }221 `);222 });223 it('directory/files specifier', () => {224 const specifier = normalizeStoriesEntry({ directory: '..', files: '*.stories.mdx' }, options);225 expect(specifier).toMatchInlineSnapshot(`226 {227 "titlePrefix": "",228 "files": "*.stories.mdx",229 "directory": ".",230 "importPathMatcher": {}231 }232 `);233 });234 it('directory/titlePrefix specifier', () => {235 const specifier = normalizeStoriesEntry({ directory: '..', titlePrefix: 'atoms' }, options);236 expect(specifier).toMatchInlineSnapshot(`237 {238 "titlePrefix": "atoms",239 "files": "**/*.stories.@(mdx|tsx|ts|jsx|js)",240 "directory": ".",241 "importPathMatcher": {}242 }243 `);244 });245 it('directory/titlePrefix/files specifier', () => {246 const specifier = normalizeStoriesEntry(247 { directory: '..', titlePrefix: 'atoms', files: '*.stories.mdx' },248 options249 );250 expect(specifier).toMatchInlineSnapshot(`251 {252 "titlePrefix": "atoms",253 "files": "*.stories.mdx",254 "directory": ".",255 "importPathMatcher": {}256 }257 `);258 });259 it('globs with negation', () => {260 const specifier = normalizeStoriesEntry('../!(negation)/*.stories.mdx', options);261 expect(specifier).toMatchInlineSnapshot(`262 {263 "titlePrefix": "",264 "directory": ".",265 "files": "!(negation)/*.stories.mdx",266 "importPathMatcher": {}267 }268 `);269 expect(specifier.importPathMatcher).toMatchPaths([270 './path/file.stories.mdx',271 './second-path/file.stories.mdx',272 ]);273 expect(specifier.importPathMatcher).not.toMatchPaths([274 './path/file.stories.js',275 './path/to/file.stories.mdx',276 './file.stories.mdx',277 '../file.stories.mdx',278 ]);279 });...
import-name-after-predefined-name.js
Source:import-name-after-predefined-name.js
1const _ = require('lodash')2module.exports = {3 meta: {4 deprecated: true,5 replacedBy: ['levitate/import-convention'],6 type: 'suggestion',7 docs: {8 description: 'enforce naming an imported identifier after the user-defined list, for example given `["error", { "classnames": "cx" }]` then `import cx from "classnames"`',9 },10 schema: [11 { type: 'object' }12 ],13 },14 create: function (context) {15 const ruleList = []16 if (context.options.length > 0 && _.isObject(context.options[0])) {17 _.forEach(context.options[0], function (importPath, variableName) {18 let importPathMatcher19 if (importPath.startsWith('/')) {20 importPathMatcher = new RegExp(importPath.substring(1, importPath.lastIndexOf('/'), importPath.substring(importPath.lastIndexOf('/') + 1)))21 } else {22 importPathMatcher = new RegExp('^' + _.escapeRegExp(importPath) + '$')23 }24 ruleList.push([importPathMatcher, variableName])25 })26 }27 return {28 ImportDeclaration: function (root) {29 if (!root.specifiers || root.specifiers.length === 0) {30 return31 }32 const workPath = root.source.value33 const workNode = root.specifiers.find(node => node.type === 'ImportNamespaceSpecifier' || node.type === 'ImportDefaultSpecifier')34 if (!workNode) {35 return36 }37 for (const rule of ruleList) {38 const [importPathMatcher, variableName] = rule39 if (importPathMatcher.test(workPath)) {40 if (workNode.local.name !== variableName) {41 context.report({42 node: workNode.local,43 message: `Expected "${workNode.local.name}" to be "${variableName}".`,44 })45 }46 break47 }48 }49 }50 }51 },52 tests: {53 valid: [54 {55 code: `import AAA from 'aaa'`,56 options: [{ AAA: 'aaa' }],57 parserOptions: { ecmaVersion: 6, sourceType: 'module' },58 },59 {60 code: `import XXX from './aaa'`,61 options: [{ AAA: 'aaa' }],62 parserOptions: { ecmaVersion: 6, sourceType: 'module' },63 },64 {65 code: `import XXX from './xxx'`,66 options: [{ AAA: 'aaa' }],67 parserOptions: { ecmaVersion: 6, sourceType: 'module' },68 },69 {70 code: `import AAA from './aaa'`,71 options: [{ 'AAA': '//aaa$/' }],72 parserOptions: { ecmaVersion: 6, sourceType: 'module' },73 },74 {75 code: `import AAA from './aaa'`,76 options: [{ 'AAA': '//aaa$/' }],77 parserOptions: { ecmaVersion: 6, sourceType: 'module' },78 },79 {80 code: `import AAA from 'aaa123'`,81 options: [{ 'AAA$1': '/aaa(\d+)/' }],82 parserOptions: { ecmaVersion: 6, sourceType: 'module' },83 },84 {85 code: `import XXX from 'AAA'`,86 options: [{ 'XXX': '/aaa/i' }],87 parserOptions: { ecmaVersion: 6, sourceType: 'module' },88 },89 {90 code: `import { AAA } from 'aaa'`,91 options: [{ AAA: 'aaa' }],92 parserOptions: { ecmaVersion: 6, sourceType: 'module' },93 },94 ],95 invalid: [96 {97 code: `import XXX from 'aaa'`,98 options: [{ AAA: 'aaa' }],99 parserOptions: { ecmaVersion: 6, sourceType: 'module' },100 errors: [{ message: 'Expected "XXX" to be "AAA".' }],101 },102 ]103 }...
index.js
Source:index.js
1import {isStringMatching} from '../../general';2/**3 * Determines if given importNode matches against given importPathMatcher.4 * Returns false on unsupported values.5 * @param {RegExp|string} importPathMatcher6 * @param {Node} importNode7 * @returns {boolean}8 */9export const isImportMatchedByImportPath = (importPathMatcher, importNode) => {10 const pathString = importNode?.source?.value;11 return (12 importNode13 ? isStringMatching(pathString, importPathMatcher)14 : false15 );...
Using AI Code Generation
1import { importPathMatcher } from 'storybook-root-alias';2import { configure } from '@storybook/react';3const req = importPathMatcher('src/stories');4function loadStories() {5 req.keys().forEach(filename => req(filename));6}7configure(loadStories, module);8import { importPathMatcher } from 'storybook-root-alias';9const req = importPathMatcher('src/stories');10export default req;11{12 "scripts": {13 },14 "devDependencies": {15 }16}17import React from 'react';18import { storiesOf } from '@storybook/react';19import { Button } from 'semantic-ui-react';20const req = importPathMatcher('src/stories');21storiesOf('Button', module)22 .add('with text', () => (23 <Button onClick={req('Button').handleClick}>Hello Button</Button>24 .add('with some emoji', () => (25 <Button onClick={req('Button').handleClick}>😀 😎
Using AI Code Generation
1import { importPathMatcher } from 'storybook-root-alias';2const { importPathMatcher } = require('storybook-root-alias');3const { importPathMatcher } = require('storybook-root-alias');4const { importPathMatcher } = require('storybook-root-alias');5const { importPathMatcher } = require('storybook-root-alias');6const { importPathMatcher } = require('storybook-root-alias');7const { importPathMatcher } = require('storybook-root-alias');8const { importPathMatcher } = require('storybook-root-alias');9const { importPathMatcher } = require('storybook-root-alias');10const { importPathMatcher } = require('storybook-root-alias');
Using AI Code Generation
1const rootImportOptions = {2};3addDecorator(importPathMatcher(rootImportOptions));4addDecorator(5 withInfo({6 })7);8addDecorator(withKnobs);9addDecorator(10 withOptions({
Using AI Code Generation
1import { importPathMatcher } from 'storybook-root-import';2const rootPath = path.resolve(__dirname, '../');3module.exports = {4 webpackFinal: async config => {5 config.module.rules.push({6 test: /\.(ts|tsx)$/,7 loader: require.resolve('babel-loader'),8 options: {9 presets: [['react-app', { flow: false, typescript: true }]],10 },11 });12 config.resolve.extensions.push('.ts', '.tsx');13 config.resolve.alias = {14 '@src': path.resolve(__dirname, '../src/'),15 '@components': path.resolve(__dirname, '../src/components/'),16 '@containers': path.resolve(__dirname, '../src/containers/'),17 '@utils': path.resolve(__dirname, '../src/utils/'),18 '@styles': path.resolve(__dirname, '../src/styles/'),19 '@images': path.resolve(__dirname, '../src/images/'),20 '@store': path.resolve(__dirname, '../src/store/'),21 '@hooks': path.resolve(__dirname, '../src/hooks/'),22 '@types': path.resolve(__dirname, '../src/types/'),23 '@pages': path.resolve(__dirname, '../src/pages/'),24 };25 return config;26 },27};28const importPathMatcher = require('storybook-root-import').importPathMatcher;29const rootPath = path.resolve(__dirname, '../');30module.exports = {
Using AI Code Generation
1import { importPathMatcher } from 'storybook-root-import';2import { addWebpackAlias } from '@storybook/react';3import { resolve } from 'path';4import config from '@storybook/react';5import { addDecorator } from '@storybook/react';6import { withInfo } from '@storybook/addon-info';7import { addParameters } from '@storybook/react';8import { withKnobs } from '@storybook/addon-knobs';9import { withA11y } from '@storybook/addon-a11y';10import { configure } from '@storybook/react';11import { addDecorator } from '@storybook/react';12import { withInfo } from '@storybook/addon-info';13import { addParameters } from '@storybook/react';14import { withKnobs } from '@storybook/addon-knobs';15import { withA11y } from '@storybook/addon-a11y';16import { configure } from '@storybook/react';17import { addDecorator } from '@storybook/react';18import { withInfo } from '@storybook/addon-info';19import { addParameters } from '@storybook/react';20import { withKnobs } from '@storybook/addon-knobs';
Using AI Code Generation
1import { importPathMatcher } from 'storybook-root-alias';2const path = require('path');3const rootPath = path.resolve(__dirname, '../..');4const importPathMatcher = (importPath) => {5 const isRelative = importPath.startsWith('.');6 const isAbsolute = importPath.startsWith(rootPath);7 return isRelative || isAbsolute;8};9module.exports = (baseConfig, env, config) => {10 config.module.rules.push({11 {12 loader: require.resolve('@storybook/addon-storysource/loader'),13 options: {14 prettierConfig: {15 },16 },17 },18 });19 config.module.rules.push({20 {21 loader: require.resolve('@storybook/source-loader'),22 options: {23 prettierConfig: {24 },25 },26 },27 });28 config.module.rules.push({29 loaders: [require.resolve('@storybook/addon-storysource/loader')],30 });31 config.module.rules.push({32 loaders: [require.resolve('@storybook/source-loader')],33 });34 config.module.rules.push({35 loaders: [require.resolve('@storybook/source-loader')],36 });37 config.module.rules.push({38 {39 loader: require.resolve('@storybook/source-loader'),40 options: { parser: 'javascript' },41 },42 });43 config.module.rules.push({44 {45 loader: require.resolve('@storybook/source-loader'),46 options: { prettierConfig: { printWidth: 80, singleQuote: false } },47 },48 });49 config.module.rules.push({50 {
Using AI Code Generation
1import { importPathMatcher } from 'storybook-root-alias';2const rootAlias = importPathMatcher(['@storybook']);3module.exports = {4 webpackFinal: async (config, { configType }) => {5 config.resolve.alias = {6 };7 return config;8 },9};10const path = require('path');11const rootAlias = require('storybook-root-alias');12module.exports = ({ config, mode }) => {13 config.resolve.alias = {14 };15 return config;16};17const path = require('path');18const rootAlias = require('storybook-root-alias');19module.exports = ({ config, mode }) => {20 config.resolve.alias = {21 };22 return config;23};24const path = require('path');25const rootAlias = require('storybook-root-alias');26module.exports = ({ config, mode }) => {27 config.resolve.alias = {28 };29 return config;30};31const path = require('path');32const rootAlias = require('storybook-root-alias');33module.exports = ({ config, mode }) => {34 config.resolve.alias = {35 };36 return config;37};38const path = require('path');39const rootAlias = require('storybook-root-alias');40module.exports = ({ config, mode }) => {41 config.resolve.alias = {42 };43 return config;44};45const path = require('path');46const rootAlias = require('storybook-root-alias');47module.exports = ({ config, mode }) => {48 config.resolve.alias = {49 };50 return config;51};
Using AI Code Generation
1import { importPathMatcher } from 'storybook-root-alias';2import { configure } from '@storybook/react';3configure(importPathMatcher(require.context('../src', true, /\.stories\.js$/)), module);4import { configure } from '@storybook/react';5configure(require.context('../src', true, /\.stories\.js$/), module);6const path = require('path');7const rootAlias = require('storybook-root-alias');8module.exports = (baseConfig, env, config) => {9 config.resolve.alias = Object.assign(rootAlias.resolveAlias(), config.resolve.alias);10 return config;11};12import 'storybook-root-alias/register';13import 'storybook-root-alias/register';
Using AI Code Generation
1import importPathMatcher from 'storybook-root-alias/importPathMatcher';2import { configure } from '@storybook/react';3const req = importPathMatcher(require.context('../src', true, /\.stories\.js$/));4function loadStories() {5 req.keys().forEach(filename => req(filename));6}7configure(loadStories, module);8{9 "scripts": {10 },11 "devDependencies": {12 }13}
Using AI Code Generation
1import { importPathMatcher } from 'storybook-root-dirs';2config.module.rules.push({3 test: /\.(ts|tsx)$/,4 include: importPathMatcher,5 {6 loader: require.resolve('awesome-typescript-loader'),7 options: {8 configFileName: path.resolve(__dirname, '../tsconfig.json'),9 },10 },11 { loader: require.resolve('react-docgen-typescript-loader') },12});13config.module.rules.push({14 loaders: [require.resolve('@storybook/source-loader')],15});16import { configure } from '@storybook/vue';17import { setOptions } from '@storybook/addon-options';18import { addDecorator } from '@storybook/vue';19import { withKnobs } from '@storybook/addon-knobs/vue';20import { withInfo } from 'storybook-addon-vue-info';21import '../src/assets/css/main.css';22setOptions({
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!!