Best JavaScript code snippet using storybook-root
index.ts
Source:index.ts
1import axios from 'axios';2export type ModuleId = string;3export type ModuleDef = any;4export type ModuleDefs = { [s : string] : ModuleDef }5export type ModuleDefsForCompile = { [s : string] : ModuleDef }6export type ModuleExports = { [s : string] : any };7export type ModuleMetadata = {8 id : ModuleId;9 deps : ModuleId[];10 factory : Function;11 resolved : boolean;12 instance : any;13 exports?: ModuleExports;14};15export type ModuleMetadatas = { [s : string] : ModuleMetadata }16const depFilter = (dep : string) => dep !== 'exports';17const resolveModule = (moduleId : ModuleId, moduleMetadatas : ModuleMetadatas, initiateOrder : string[], resolvingSet : Set<ModuleId> = new Set()) => {18 const moduleMetadata = moduleMetadatas[moduleId];19 if (!moduleMetadata) {20 throw new Error(`Module not found :${moduleId}`);21 }22 if (moduleMetadata.resolved) {23 return;24 }25 if (resolvingSet.has(moduleId)) {26 throw new Error(`Circular dependencies occured :${moduleId}`);27 }28 moduleMetadata.resolved = true;29 resolvingSet.add(moduleId);30 moduleMetadata.deps.filter(depFilter).forEach((dep : ModuleId) => {31 resolveModule(dep, moduleMetadatas, initiateOrder, resolvingSet);32 });33 initiateOrder.push(moduleId);34 resolvingSet.delete(moduleId);35};36const compileModule = (moduleId : ModuleId, moduleMetadatas : ModuleMetadatas) => {37 const moduleMetadata = moduleMetadatas[moduleId];38 moduleMetadata.exports = {};39 const args : any[] = [];40 moduleMetadata.deps.forEach((dep) => {41 if (dep === 'exports') {42 args.push(moduleMetadata.exports);43 } else {44 args.push(moduleMetadatas[dep].exports);45 }46 });47 moduleMetadata.factory(...args);48};49export class Env {50 moduleDefs : ModuleDefs;51 moduleMetadatas : ModuleMetadatas;52 initiateOrder : ModuleId[];53 constructor(moduleDefs? : ModuleDefs) {54 this.moduleDefs = moduleDefs || {};55 this.moduleMetadatas = {};56 this.initiateOrder = [];57 }58 _toFileName(moduleId : ModuleId) : string {59 return `/${moduleId}.ts`;60 }61 _fromFileName(fileName : any) : ModuleId {62 let moduleId = fileName;63 if (moduleId.startsWith('/')) {64 moduleId = moduleId.substr(1);65 }66 if (moduleId.endsWith('.ts')) {67 moduleId = moduleId.substr(0, moduleId.length - 3);68 }69 return moduleId;70 }71 _toModuleDefsForCompile() : ModuleDefsForCompile {72 return Object.keys(this.moduleDefs)73 .reduce((map : ModuleDefsForCompile, k : ModuleId ) => {74 return {75 ...map,76 [this._toFileName(k)]: this.moduleDefs[k],77 };78 }, {});79 }80 _compiledCodeToModuleMetadata(moduleId : ModuleId, code : string) : ModuleMetadata {81 const define = new Function('define', code);82 let deps : string[] = [];83 let factory : any;84 define((_deps : string[], _factory : Function) => {85 deps = _deps;86 factory = _factory;87 });88 return {89 id: moduleId,90 deps,91 factory,92 resolved: false,93 instance: null,94 };95 }96 _fromModuleDefsForCompile(moduleDefsForCompile : ModuleDefsForCompile) {97 const moduleIds : ModuleId[] = [];98 this.moduleMetadatas = Object.keys(moduleDefsForCompile)99 .reduce((map : ModuleMetadatas, k : ModuleId) => {100 const moduleId = this._fromFileName(k);101 moduleIds.push(moduleId);102 return {103 ...map,104 [moduleId]: this._compiledCodeToModuleMetadata(moduleId, moduleDefsForCompile[k]),105 };106 }, {});107 return moduleIds;108 }109 _compile(moduleIds : ModuleId[] = []) {110 this.initiateOrder = [];111 moduleIds.forEach(112 moduleId => resolveModule(moduleId, this.moduleMetadatas, this.initiateOrder)113 );114 this.initiateOrder.forEach(115 moduleId => compileModule(moduleId, this.moduleMetadatas)116 );117 }118 getExports(moduleId : ModuleId) {119 const moduleMetadata = this.moduleMetadatas[moduleId];120 return moduleMetadata.exports;121 }122 build() {123 return axios({124 method: 'post',125 url: 'api/compile',126 data: {127 modules: this._toModuleDefsForCompile(),128 },129 })130 .then(({ data: m }) => {131 // console.log('m :', m);132 const moduleIds = this._fromModuleDefsForCompile(m);133 this._compile(moduleIds);134 });135 }136}137export const createEnv = (moduleDefs? : ModuleDefs) => {138 return new Env(moduleDefs);...
test-context.ts
Source:test-context.ts
1///<reference path="../../../node_modules/@types/jasmine/index.d.ts"/>2import {Type} from '@angular/core';3import {ComponentFixture, TestBed, TestModuleMetadata} from '@angular/core/testing';4import {CommonFunctionService} from '../shared/service/common-function.service';5import {TestConfigModuleMetadata} from './test-dependency/test-config-module-metadata';6export class TestContext<H> {7 fixture: ComponentFixture<H>;8 component: H;9 detectChanges(): void {10 this.fixture.detectChanges();11 }12}13export function initContext<H>(hostType: Type<H>, moduleMetadata: TestModuleMetadata = {}) {14 beforeEach(function (this: TestContext<H>) {15 /*16 * Jasmine creates plain objects17 * and modifying their prototype is definitely a bad idea18 */19 Object.assign(this, TestContext.prototype);20 initModuleMetadata();21 TestBed.configureTestingModule({...moduleMetadata});22 this.fixture = TestBed.createComponent(hostType);23 this.component = this.fixture.componentInstance;24 });25 afterEach(function (this: TestContext<H>) {26 if (this.fixture) {27 this.fixture.destroy();28 this.fixture.nativeElement.remove();29 }30 TestBed.resetTestingModule();31 });32 function initModuleMetadata() {33 if (CommonFunctionService.isNullOrUndefined(moduleMetadata.imports)) {34 moduleMetadata.imports = [];35 }36 if (CommonFunctionService.isNullOrUndefined(moduleMetadata.declarations)) {37 moduleMetadata.declarations = [];38 }39 if (CommonFunctionService.isNullOrUndefined(moduleMetadata.providers)) {40 moduleMetadata.providers = [];41 }42 if (CommonFunctionService.isNullOrUndefined(moduleMetadata.schemas)) {43 moduleMetadata.schemas = [];44 }45 moduleMetadata.imports.push(TestConfigModuleMetadata.imports);46 moduleMetadata.declarations.push(hostType, TestConfigModuleMetadata.declarations);47 moduleMetadata.providers.push(hostType, TestConfigModuleMetadata.providers);48 moduleMetadata.schemas.push(TestConfigModuleMetadata.schemas);49 }...
module.ts
Source:module.ts
1import { isFunction } from 'util';2import { Test, TestingModule } from '@nestjs/testing';3import { createSbServer } from '@pebula/nesbus';4import { ModuleMetadata, Provider } from '@nestjs/common/interfaces';5import { NestBusSharedModule, createServiceBusModule } from '../server';6export class TestModuleFactory {7 static create(): Pick<TestModuleFactory, 'addServiceBusModule' | 'addMetadata'> {8 return new TestModuleFactory();9 }10 private moduleMetadata: ModuleMetadata = {11 imports: [ NestBusSharedModule ],12 controllers: [],13 providers: [ ],14 exports: [],15 };16 private fn?: (testingModule: TestingModule) => {};17 private constructor() { }18 addServiceBusModule(...providers: Provider[]): Pick<TestModuleFactory, 'compile' | 'addMetadata'> {19 const serviceBusModule = createServiceBusModule(...providers);20 this.moduleMetadata.imports.push(serviceBusModule);21 return this;22 }23 addMetadata(moduleMetadata: ModuleMetadata, overwrite = false): this {24 for (const [key, value] of Object.entries(moduleMetadata)) {25 if (overwrite) {26 this.moduleMetadata[key as keyof ModuleMetadata] = value;27 } else {28 this.moduleMetadata[key as keyof ModuleMetadata].push(...value);29 }30 }31 return this;32 }33 compile(fn?: (testingModule: TestingModule) => {}): Pick<TestModuleFactory, 'init'> {34 this.fn = fn;35 return this;36 }37 async init(port = 4000) {38 const moduleBuilder = Test.createTestingModule(this.moduleMetadata);39 const testingModule = await moduleBuilder.compile();40 if (isFunction(this.fn)) {41 this.fn(testingModule);42 }43 const app = testingModule.createNestApplication();44 app.connectMicroservice({ strategy: createSbServer() });45 await app.startAllMicroservicesAsync();46 await app.listenAsync(port);47 // app = moduleFixture.createNestMicroservice({ strategy: createSbServer() });48 // await app.listenAsync();49 return app;50 }...
Using AI Code Generation
1import { moduleMetadata } from '@storybook/angular';2import { Meta, Story } from '@storybook/angular/types-6-0';3import { ButtonComponent } from './button.component';4import { CommonModule } from '@angular/common';5export default {6 moduleMetadata({7 imports: [CommonModule],8 }),9} as Meta;10const Template: Story<ButtonComponent> = (args: ButtonComponent) => ({11});12export const Primary = Template.bind({});13Primary.args = {14};15export const Secondary = Template.bind({});16Secondary.args = {17};18export const Large = Template.bind({});19Large.args = {20};21export const Small = Template.bind({});22Small.args = {23};24import { Component, OnInit, Input } from '@angular/core';25@Component({26 [ngClass]="{ 'storybook-button--primary': !secondary, 'storybook-button--secondary': secondary }"27 [ngStyle]="{ 'font-size': size }"28 {{ text }}29 button {30 border: 0;31 border-radius: 3em;32 cursor: pointer;33 padding: 0.5em 1em;34 }35 .storybook-button--primary {36 color: white;37 background-color: #1ea7fd;38 }39 .storybook-button--secondary {40 color: #333;41 background-color: transparent;42 box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 0px 1px inset;43 }44})45export class ButtonComponent implements OnInit {46 @Input() primary = false;47 @Input() backgroundColor?: string;48 @Input() size: 'small' | 'medium' | 'large'
Using AI Code Generation
1import { moduleMetadata } from '@storybook/angular';2import { Meta } from '@storybook/angular/types-6-0';3import { CommonModule } from '@angular/common';4import { ButtonComponent } from './button.component';5export default {6 moduleMetadata({7 imports: [CommonModule],8 }),9} as Meta;10export const primary = () => ({11 props: {12 },13});14export const secondary = () => ({15 props: {16 },17});18export const primaryDisabled = () => ({19 props: {20 },21});22export const secondaryDisabled = () => ({23 props: {24 },25});26import { Component, OnInit, Input } from '@angular/core';27@Component({28 [ngClass]="{ 'storybook-button--primary': primary }"29})30export class ButtonComponent implements OnInit {31 @Input()32 disabled = false;33 @Input()34 primary = false;35 constructor() {}36 ngOnInit(): void {}37}38@import '~@storybook/theming';39@import '~@storybook/theming/dist/typography';40:root {41 --storybook-button--font-size: 14px;42 --storybook-button--font-weight: 600;43 --storybook-button--line-height: 20px;44 --storybook-button--padding: 8px 16px;45 --storybook-button--border-radius: 3px;46}47.storybook-button {48 font-family: var(--storybook-font-family-base);49 font-size: var(--storybook-button--font-size);50 font-weight: var(--storybook-button--font-weight);51 line-height: var(--storybook-button--line-height);52 padding: var(--storybook-button--padding);53 border-radius: var(--storybook-button--border-radius);
Using AI Code Generation
1import { moduleMetadata } from '@storybook/angular';2import { MatCardModule } from '@angular/material/card';3import { MatIconModule } from '@angular/material/icon';4import { MatListModule } from '@angular/material/list';5import { MatMenuModule } from '@angular/material/menu';6import { MatToolbarModule } from '@angular/material/toolbar';7export default {8 moduleMetadata({9 imports: [10 }),11};12@Component({13})14export class MyComponent {}15import { MyComponent } from './my.component';16export const myComponent = () => ({17});18import { myComponent } from './my.component.stories.ts';19export default {
Using AI Code Generation
1import { moduleMetadata } from '@storybook/angular';2export default {3 moduleMetadata({4 imports: [CommonModule],5 }),6};7import { storiesOf } from '@storybook/angular';8storiesOf('My Button', module)9 .addDecorator(10 moduleMetadata({11 imports: [CommonModule],12 }),13 .add('with text', () => ({14 props: {15 },16 }));17import { moduleMetadata } from '@storybook/angular';18export default {19 moduleMetadata({20 imports: [CommonModule],21 }),22};23import { storiesOf } from '@storybook/angular';24storiesOf('My Button', module)25 .addDecorator(26 moduleMetadata({27 imports: [CommonModule],28 }),29 .add('with text', () => ({30 props: {31 },32 }));33import { moduleMetadata } from '@storybook/angular';34export default {35 moduleMetadata({36 imports: [CommonModule],37 }),38};39import { storiesOf } from '@storybook/angular';40storiesOf('My Button', module)41 .addDecorator(42 moduleMetadata({43 imports: [CommonModule],44 }),45 .add('with text', () => ({46 props: {47 },48 }));
Using AI Code Generation
1import { moduleMetadata } from '@storybook/angular';2import { CommonModule } from '@angular/common';3import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';4import { withKnobs } from '@storybook/addon-knobs';5import { withA11y } from '@storybook/addon-a11y';6import { withNotes } from '@storybook/addon-notes';7import { withTests } from '@storybook/addon-jest';8import { StorybookModule } from 'storybook-module';9import { StorybookModuleOptions } from 'storybook-module';10import { StorybookModuleMetadata } from 'storybook-module';11import { StorybookModuleMetadataOptions } from 'storybook-module';12import { StorybookModuleMetadataSchema } from 'storybook-module';13import { component } from '@storybook/angular';14import { StorybookComponent } from 'storybook-module';15import { StorybookComponentOptions } from 'storybook-module';16import { StorybookComponentMetadata } from 'storybook-module';17import { StorybookComponentMetadataOptions } from 'storybook-module';18import { StorybookComponentMetadataSchema } from 'storybook-module';19import { directive } from '@storybook/angular';20import { StorybookDirective } from 'storybook-module';21import { StorybookDirectiveOptions } from 'storybook-module';22import { StorybookDirectiveMetadata } from 'storybook-module';23import { StorybookDirectiveMetadataOptions } from 'storybook-module';24import { StorybookDirectiveMetadataSchema } from 'storybook-module';25import { pipe } from '@storybook/angular';26import { StorybookPipe } from 'storybook-module';27import { StorybookPipeOptions } from 'storybook-module';28import { StorybookPipeMetadata } from 'storybook-module';29import { StorybookPipeMetadataOptions } from 'storybook-module';30import { StorybookPipeMetadataSchema } from 'storybook-module';31import { decorator } from '@storybook/angular';32import { StorybookDecorator } from 'storybook-module';33import { StorybookDecoratorOptions } from 'storybook-module';34import { StorybookDecoratorMetadata } from 'storybook-module';35import { StorybookDecoratorMetadataOptions } from 'storybook-module';36import { StorybookDecoratorMetadataSchema } from 'storybook-module';37import { module } from '@storybook/angular';38import {
Using AI Code Generation
1import { moduleMetadata } from '@storybook/angular';2import { AppComponent } from '../app.component';3import { Meta, Story, moduleMetadata } from '@storybook/angular';4import { AppComponent } from '../app.component';5import { AppModule } from '../app.module';6import { CommonModule } from '@angular/common';7import { FormsModule } from '@angular/forms';8import { Meta, Story } from '@storybook/angular';9import { MyComponent } from './my.component';10import { MyModule } from './my.module';11export default {12 moduleMetadata({13 imports: [MyModule],14 }),15} as Meta;16const Template: Story<MyComponent> = (args: MyComponent) => ({17 moduleMetadata: {18 imports: [MyModule],19 },20});21export const Primary = Template.bind({});22Primary.args = {23};24import { Component, Input } from '@angular/core';25@Component({26})27export class MyComponent {28 @Input() myProperty: string;29}30import { NgModule } from '@angular/core';31import { CommonModule } from '@angular/common';32import { MyComponent } from './my.component';33@NgModule({34 imports: [CommonModule],35})36export class MyModule {}37import { NgModule } from '@angular/core';38import { BrowserModule } from '@angular/platform-browser';39import { AppComponent } from './app.component';40import { MyModule } from './my.module';41@NgModule({42 imports: [BrowserModule, MyModule],43})44export class AppModule {}45import { Component } from '@angular/core';46@Component({47})48export class AppComponent {49 myProperty = 'myValue';50}51import
Using AI Code Generation
1import { moduleMetadata } from '@storybook/angular';2import { TestModule } from './test.module';3export default {4 moduleMetadata({5 imports: [TestModule],6 }),7};8export const test = () => ({9});10import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';11import { CommonModule } from '@angular/common';12import { TestComponent } from './test.component';13@NgModule({14 imports: [CommonModule],15})16export class TestModule {}17import { Component } from '@angular/core';18@Component({19})20export class TestComponent {}21import { ComponentFixture, TestBed } from '@angular/core/testing';22import { TestComponent } from './test.component';23describe('TestComponent', () => {24 let component: TestComponent;25 let fixture: ComponentFixture<TestComponent>;26 beforeEach(async () => {27 await TestBed.configureTestingModule({28 }).compileComponents();29 });30 beforeEach(() => {31 fixture = TestBed.createComponent(TestComponent);32 component = fixture.componentInstance;33 fixture.detectChanges();34 });35 it('should create', () => {36 expect(component).toBeTruthy();37 });38});39import { test } from './test';40export default {41};42export const testStory = test.bind({});43testStory.story = {44};45import { test } from './test';46export default {47};48export const testStory = test.bind({});49testStory.story = {50};51import { test } from './test';52export default {53};54export const testStory = test.bind({});55testStory.story = {56};
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!!