Best JavaScript code snippet using ng-mocks
index.ts
Source:index.ts
1import * as webpack from 'webpack';2import * as CommentCompilationWarning from 'webpack/lib/CommentCompilationWarning';3import * as ConstDependency from 'webpack/lib/dependencies/ConstDependency';4import { ConcatSource } from 'webpack-sources';5import { generate } from 'astring';6/**7 * Moves static import in webpack bundle to top level by using special comment webpackIgnore: true8 */9export class StaticImportWebpackPlugin implements webpack.Plugin {10 readonly name = this.constructor.name;11 private readonly imports = new Map<string, string[]>();12 apply(compiler: webpack.Compiler) {13 compiler.hooks.thisCompilation.tap(this.name, this.thisCompilationTap);14 }15 private readonly thisCompilationTap = (compilation, { normalModuleFactory }) => {16 compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());17 ['javascript/auto', 'javascript/dynamic', 'javascript/esm'].forEach(type => {18 normalModuleFactory.hooks.parser.for(type).tap(this.name, (parser) => {19 const boundImportTap = this.importTap.bind(this, parser);20 parser.hooks.import.tap(this.name, boundImportTap);21 parser.hooks.importSpecifier.tap(this.name, boundImportTap);22 });23 });24 compilation.hooks.optimizeChunkAssets.tap(this.name, (chunks) => {25 this.compilationOptimizeChunkAssetsTap(compilation, chunks);26 });27 }28 private readonly importTap = (parser, statement, source, specifier, name) => {29 const { options, errors } = parser.parseCommentOptions(statement.range);30 if (errors) {31 const warnings = errors.map(error => {32 return new CommentCompilationWarning(33 `Compilation error while processing comment(-s): /*${error.comment.value}*/: ${error.message}`,34 parser.state.module,35 error.comment.loc,36 );37 });38 if (warnings.length > 0) {39 parser.state.module.warnings.push(...warnings);40 }41 }42 if (options && options.webpackIgnore) {43 const module = parser.state.module;44 let entryModule = module;45 while (entryModule.issuer != undefined) {46 entryModule = entryModule.issuer;47 }48 const moduleId = entryModule.debugId;49 const declarations: string[] = this.imports.get(moduleId) || [];50 const declaration = generate(statement);51 if (!declarations.includes(declaration)) {52 declarations.push(declaration);53 this.imports.set(moduleId, declarations);54 }55 module.dependencies56 .filter(this.isHarmonyImportDependency)57 .forEach(dependency => module.removeDependency(dependency));58 const emptyDependency = module.dependencies.find(d => d.expression === '' && d.range && d.range[0] === statement.range[0] && d.range[1] === statement.range[1]);59 if (!emptyDependency) {60 module.addDependency(new ConstDependency('', statement.range));61 }62 return false;63 }64 }65 private readonly compilationOptimizeChunkAssetsTap = (compilation, chunks: any[]) => {66 chunks.forEach(chunk => {67 if (chunk.entryModule.constructor.name === 'MultiModule') {68 chunk.entryModule.dependencies.forEach(dependency => {69 this.addImports(compilation, chunk, dependency.module);70 });71 } else if (chunk.entryModule.constructor.name === 'ConcatenatedModule') {72 this.addImports(compilation, chunk, chunk.entryModule.rootModule);73 } else {74 this.addImports(compilation, chunk, chunk.entryModule);75 }76 });77 }78 private readonly addImports = (compilation, chunk, entryModule) => {79 if (!this.imports.has(entryModule.debugId)) {80 return;81 }82 chunk.files.forEach(fileName => {83 const importsForModule = this.imports.get(entryModule.debugId)!84 .join('\n');85 compilation.assets[fileName] = new ConcatSource(86 importsForModule,87 '\n\n',88 compilation.assets[fileName],89 );90 });91 }92 private isHarmonyImportDependency(dependency: { constructor: { name: string } }) {93 return [94 'HarmonyImportSpecifierDependency',95 // 'HarmonyCompatibilityDependency',96 // 'HarmonyInitDependency',97 // 'HarmonyImportSideEffectDependency',98 ].includes(dependency.constructor.name);99 }...
babel-loader.js
Source:babel-loader.js
1const {2 parse3} = require('@babel/parser')4const traverse = require('@babel/traverse').default5const generate = require('@babel/generator').default6const { isFileExist } = require('../util')7const fs = require('fs')8const {9 dealExpression,10 dealWithImport,11 dealWithExport,12 getExportVariable13} = require('../dealAST')14const {15 argvTemlate,16 importTemplate,17 importSingleTemplate,18} = require('../template')19function traverseCode(loaderConfig, callback) {20 const {21 ENTRY_PATH,22 parseModule,23 entryModule,24 modules,25 preTransformEntry26 } = loaderConfig27 // console.log(12313, entryModule);28 if (isFileExist(ENTRY_PATH)) {29 const content = fs.readFileSync(ENTRY_PATH, 'utf-8')30 31 const ast = parse(content, {32 sourceType: 'module'33 })34 // console.log('modules', modules);35 // entryModule[preTransformEntry] = {36 // path: loaderEntry, 37 // originPath: preTransformEntry,38 // absoltePath: ENTRY_PATH,39 // modules: [],40 // exports: [],41 // ...isIndex && {isIndex}42 // }43 traverse(ast, {44 Program(path) {45 assembleContent(modules, entryModule, content, path.node, preTransformEntry, parseModule, callback)46 }47 })48 } else {49 console.log(colors.red(`${ENTRY_PATH} is no Exist`))50 }51 return entryModule52}53function assembleContent(modules, entryModule, content, astTree, ENTRY_PATH, parseModule, callback) {54 const {55 body = []56 } = astTree57 let transformTemplate = argvTemlate58 let importTree = {}59 body.forEach(ast => {60 switch (ast.type) {61 case 'ImportDeclaration':62 const template = importSingleTemplate(ast.specifiers[0].local.name, ast.source.value)63 64 importTree = {65 path: ast.source.value,66 beforeVar: ast.specifiers[0].local.name,67 afterVar: template.variable,68 importContent: template.content69 }70 entryModule.modules.push(importTree)71 transformTemplate = importTemplate72 break;73 case 'ExportDefaultDeclaration':74 const exportTree = {75 name: [],76 value: ast.declaration.extra ? ast.declaration.extra.raw : undefined77 }78 if (entryModule.path === './src/index.js') {79 console.log(ast);80 }81 exportTree.name = getExportVariable(ast, exportTree, entryModule.modules, content),82 entryModule.exports.push({default: exportTree})83 content = generate(astTree, {}, content).code84 break;85 case 'ExportNamedDeclaration':86 const exported = ast.specifiers.ExportSpecifier.local.name87 entryModule.exports.push({[exported]: exported})88 break;89 case 'ExpressionStatement':90 if (dealExpression(ast, entryModule.modules, content)) {91 content = generate(astTree, {}, content).code92 }93 break;94 default:95 break96 }97 })98 content = dealWithImport(entryModule.modules, content, parseModule.parseModule, entryModule.absoltePath)99 content = dealWithExport(entryModule.exports, content)100 entryModule.content = content101 entryModule.transformTemplate = transformTemplate102 if (entryModule.isIndex) {103 generateCode(modules[entryModule.path], entryModule, transformTemplate)104 }105}106/**107 * @description æ ¹æ®ç°æçASTæ çæ代ç 并è¾åºæ件108 * @param {*} astTree 109 * @param {*} content 110 * @param {*} ENTRY_PATH 111 * @param {*} transformTemplate 112 */113function generateCode(modules, entryModule, transformTemplate) {114 const content = Object.values(modules.modules).reduce((prev, next) => {115 return `${transformTemplate(JSON.stringify(next.content || '').replace(/^["|'](.*)["|']$/g, '$1'), next.originPath)},` + prev116 }, '')117 // console.log(content);118 modules.content = content119}...
import-path.js
Source:import-path.js
1const entryModuleToFlatten = [2 'BottomNavigation',3 'BottomNavigationAction',4 'Card',5 'CardActions',6 'CardContent',7 'CardHeader',8 'CardMedia',9 'CircularProgress',10 'ClickAwayListener',11 'Collapse',12 'Dialog',13 'DialogActions',14 'DialogContent',15 'DialogContentText',16 'DialogTitle',17 'ExpansionPanel',18 'ExpansionPanelActions',19 'ExpansionPanelDetails',20 'ExpansionPanelSummary',21 'Fade',22 'Form',23 'FormControl',24 'FormControlLabel',25 'FormGroup',26 'FormHelperText',27 'FormLabel',28 'GridList',29 'GridListTile',30 'Grow',31 'Input',32 'InputLabel',33 'LinearProgress',34 'List',35 'ListItem',36 'ListItemAvatar',37 'ListItemIcon',38 'ListItemSecondaryAction',39 'ListItemText',40 'ListSubheader',41 'Menu',42 'MenuItem',43 'Progress',44 'Radio',45 'RadioGroup',46 'Slide',47 'Step',48 'StepButton',49 'StepContent',50 'Stepper',51 'Stepper',52 'Tab',53 'Table',54 'TableBody',55 'TableCell',56 'TableFooter',57 'TableHead',58 'TablePagination',59 'TableRow',60 'Tabs',61 'withWidth',62 'Zoom',63];64const keepSpecifiers = ['withWidth'];65export default function transformer(fileInfo, api, options) {66 const j = api.jscodeshift;67 let hasModifications = false;68 const printOptions = options.printOptions || {69 quote: 'single',70 trailingComma: true,71 };72 const importModule = options.importModule || '@material-ui/core';73 const targetModule = options.targetModule || '@material-ui/core';74 const root = j(fileInfo.source);75 const importRegExp = new RegExp(`^${importModule}/(.+)$`);76 root.find(j.ImportDeclaration).forEach((path) => {77 const importPath = path.value.source.value;78 let entryModule = importPath.match(importRegExp);79 // Remove non-Material-UI imports80 if (!entryModule) {81 return;82 }83 entryModule = entryModule[1].split('/');84 entryModule = entryModule[entryModule.length - 1];85 // No need to flatten86 if (!entryModuleToFlatten.includes(entryModule)) {87 return;88 }89 hasModifications = true;90 if (keepSpecifiers.includes(entryModule)) {91 path.value.source.value = `${targetModule}/${entryModule}`;92 return;93 }94 path.node.specifiers.forEach((specifier) => {95 const localName = specifier.local.name;96 const importedName = specifier.imported ? specifier.imported.name : null;97 if (!importedName) {98 const importStatement = j.importDeclaration(99 [j.importDefaultSpecifier(j.identifier(localName))],100 j.literal(`${targetModule}/${entryModule}`),101 );102 j(path).insertBefore(importStatement);103 } else {104 const importStatement = j.importDeclaration(105 [j.importDefaultSpecifier(j.identifier(localName))],106 j.literal(`${targetModule}/${importedName}`),107 );108 j(path).insertBefore(importStatement);109 }110 });111 path.prune();112 });113 return hasModifications ? root.toSource(printOptions) : null;...
Using AI Code Generation
1import { entryModule } from 'ng-mocks';2import { entryComponent } from 'ng-mocks';3import { entryDirective } from 'ng-mocks';4import { entryPipe } from 'ng-mocks';5import { entryProvider } from 'ng-mocks';6import { entryToken } from 'ng-mocks';7import { entryValue } from 'ng-mocks';8import { entryMock } from 'ng-mocks';9import { mockComponent } from 'ng-mocks';10import { mockDirective } from 'ng-mocks';11import { mockPipe } from 'ng-mocks';12import { mockProvider } from 'ng-mocks';13import { mockToken } from 'ng-mocks';14import { mockValue } from 'ng-mocks';15import { mockInstance } from 'ng-mocks';16import { mockReset } from 'ng-mocks';17import { mockClear } from 'ng-mocks';18import { mockDeep } from 'ng-mocks';19import { mockDeepReset } from 'ng-mocks';20import { mockDeepClear } from 'ng-mocks';21import { mockConsole } from 'ng-mocks';22import { mockConsoleClear } from 'ng-mocks
Using AI Code Generation
1import { entryModule } from 'ng-mocks';2import { AppModule } from './app.module';3import { entryComponent } from 'ng-mocks';4import { AppComponent } from './app.component';5import { entryComponents } from 'ng-mocks';6import { AppComponent } from './app.component';7import { App2Component } from './app2.component';8import { entryDirective } from 'ng-mocks';9import { AppDirective } from './app.directive';10import { entryPipe } from 'ng-mocks';11import { AppPipe } from './app.pipe';12import { entryService } from 'ng-mocks';13import { AppService } from './app.service';14import { entryProvider } from 'ng-mocks';15import { AppProvider } from './app.provider';16import { entryImport } from 'ng-mocks';17import { AppImport } from './app.import';18import { entryImports } from 'ng-mocks';19import { AppImport } from './app.import';20import { App2Import } from './app2.import';21import { entryDeclaration } from 'ng-mocks';22import { AppDeclaration } from './app.declaration';23import { entryDeclarations } from 'ng-mocks';24import { AppDeclaration } from './app.declaration';25import { App2Declaration } from './app2.declaration';26import { entryExport } from 'ng-mocks';27import { AppExport } from './app.export';28import { entryExports } from 'ng-mocks';29import { AppExport } from './app.export';30import { App2Export } from './app2.export';31import { entryBootstrap } from 'ng-mocks';32import { AppBootstrap } from './app.bootstrap
Using AI Code Generation
1import { entryModule } from 'ng-mocks';2import { AppModule } from './app.module';3describe('AppModule', () => {4 it('should be created', () => {5 const module = entryModule(AppModule);6 expect(module).toBeTruthy();7 });8});9import { NgModule } from '@angular/core';10import { BrowserModule } from '@angular/platform-browser';11import { AppComponent } from './app.component';12@NgModule({13 imports: [BrowserModule],14})15export class AppModule {}16import { Component } from '@angular/core';17@Component({18})19export class AppComponent {}20import { entryModule } from 'ng-mocks';21import { AppModule } from './app.module';22describe('AppModule', () => {23 it('should be created', () => {24 const module = entryModule(AppModule);25 expect(module).toBeTruthy();26 });27});28import { entryModule } from 'ng-mocks';29import { AppModule } from './app.module';30describe('AppModule', () => {31 it('should be created', () => {32 const module = entryModule(AppModule);33 expect(module).toBeTruthy();34 });35});36import { entryModule } from 'ng-mocks';37import { AppModule } from './app.module';38describe('AppModule', () => {39 it('should be created', () => {40 const module = entryModule(AppModule);41 expect(module).toBeTruthy();42 });43});44import { NgModule } from '@angular/core';45import { BrowserModule } from '@angular/platform-browser';46import { AppComponent } from './app.component';47@NgModule({48 imports: [BrowserModule],49})50export class AppModule {}
Using AI Code Generation
1import { entryModule } from 'ng-mocks';2import { AppModule } from './app.module';3entryModule(AppModule);4import { entryModule } from 'ng-mocks';5import { AppModule } from './app.module';6entryModule(AppModule);7import { entryComponent } from 'ng-mocks';8import { AppComponent } from './app.component';9entryComponent(AppComponent);10import { entryComponent } from 'ng-mocks';11import { AppComponent } from './app.component';12entryComponent(AppComponent);13import { entryComponent } from 'ng-mocks';14import { AppComponent } from './app.component';15entryComponent(AppComponent);16import { entryComponent } from 'ng-mocks';17import { AppComponent } from './app.component';18entryComponent(AppComponent);19import { entryComponent } from 'ng-mocks';20import { AppComponent } from './app.component';21entryComponent(AppComponent);22import { entryComponent } from 'ng-mocks';23import { AppComponent } from './app.component';24entryComponent(AppComponent);25import { entryComponent } from 'ng-mocks';26import { AppComponent } from './app.component';27entryComponent(AppComponent);28import { entryComponent } from 'ng-mocks';29import { AppComponent } from './app.component';30entryComponent(AppComponent);31import { entryComponent } from 'ng-mocks';32import { AppComponent } from './app.component';33entryComponent(AppComponent);34import { entryComponent } from
Using AI Code Generation
1import { entryModule } from 'ng-mocks';2entryModule(TestModule);3import { entryComponent } from 'ng-mocks';4entryComponent(TestComponent);5import { entryComponent } from 'ng-mocks';6entryComponent(TestComponent);7import { entryModule } from 'ng-mocks';8entryModule(TestModule);9import { entryComponent } from 'ng-mocks';10entryComponent(TestComponent);11import { entryComponent } from 'ng-mocks';12entryComponent(TestComponent);13import { entryModule } from 'ng-mocks';14entryModule(TestModule);15import { entryComponent } from 'ng-mocks';16entryComponent(TestComponent);17import { entryComponent } from 'ng-mocks';18entryComponent(TestComponent);19import { entryModule } from 'ng-mocks';20entryModule(TestModule);21import { entryComponent } from 'ng-mocks';22entryComponent(TestComponent);23import { entryComponent } from 'ng-mocks';24entryComponent(TestComponent);25import { entryModule } from 'ng-mocks';26entryModule(TestModule);27import { entryComponent } from 'ng-mocks';28entryComponent(TestComponent);29import { entryComponent } from 'ng-mocks';30entryComponent(TestComponent);31import { entryModule } from 'ng-mocks';32entryModule(TestModule);33import { entryComponent
Using AI Code Generation
1import { entryModule } from 'ng-mocks';2entryModule( AppModule );3describe('AppComponent', () => {4 it('should create the app', () => {5 const fixture = TestBed.createComponent(AppComponent);6 const app = fixture.debugElement.componentInstance;7 expect(app).toBeTruthy();8 });9});10import { entryComponent } from 'ng-mocks';11entryComponent( AppComponent );12describe('AppComponent', () => {13 it('should create the app', () => {14 const fixture = TestBed.createComponent(AppComponent);15 const app = fixture.debugElement.componentInstance;16 expect(app).toBeTruthy();17 });18});19import { Component, OnInit } from '@angular/core';20import { DataService } from '../data.service';21@Component({22})23export class TestComponent implements OnInit {24 data: any;25 constructor(private dataService: DataService) { }26 ngOnInit() {27 this.data = this.dataService.getData();28 }29}30import { NgModule } from '@angular/core';31import { CommonModule } from '@angular/common';32import { TestComponent } from './test.component';33import { DataService } from '../data.service';34@NgModule({35 imports: [36})37export class TestModule { }38import { NgModule } from '@angular/core';39import { CommonModule } from '@angular/common';40import { TestComponent } from './test.component';41import { DataService } from '../data.service';42@NgModule({
Using AI Code Generation
1import { entryModule } from 'ng-mocks';2import { AppModule } from './app.module';3import { AppComponent } from './app.component';4import { AppComponent } from './app.component';5import { TestBed } from '@angular/core/testing';6describe('AppComponent', () => {7 beforeEach(async () => {8 await TestBed.configureTestingModule({9 imports: [10 })11 .overrideModule(AppModule, entryModule(AppComponent))12 .compileComponents();13 });14 it('should create the app', () => {15 const fixture = TestBed.createComponent(AppComponent);16 const app = fixture.componentInstance;17 expect(app).toBeTruthy();18 });19 it(`should have as title 'ng-mocks-test'`, () => {20 const fixture = TestBed.createComponent(AppComponent);21 const app = fixture.componentInstance;22 expect(app.title).toEqual('ng-mocks-test');23 });24 it('should render title', () => {25 const fixture = TestBed.createComponent(AppComponent);26 fixture.detectChanges();27 const compiled = fixture.nativeElement;28 expect(compiled.querySelector('.content span').textContent).toContain('ng-mocks-test app is running!');29 });30});31import { Component } from '@angular/core';32@Component({33 Welcome to {{ title }}!34 :host {35 font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";36 font-size: 14px;37 color: #333;38 box-sizing: border-box;39 -webkit-font-smoothing: antialiased;40 -moz-osx-font-smoothing: grayscale;41 }42 h1 {
Using AI Code Generation
1import { entryModule } from 'ng-mocks';2describe('TestModule', () => {3 entryModule(TestModule);4});5import { entryModule } from 'ng-mocks';6describe('TestModule', () => {7 entryModule(TestModule);8});
Using AI Code Generation
1import { entryModule } from 'ng-mocks';2import { AppModule } from './app.module';3const testBed = entryModule(AppModule);4const component = testBed.createComponent(MyComponent);5describe('MyComponent', () => {6 it('should create an instance', () => {7 expect(component).toBeTruthy();8 });9});10describe('MyComponent', () => {11 it('should create an instance', () => {12 expect(component).toBeTruthy();13 });14});15describe('MyComponent', () => {16 it('should render the template', () => {17 const element = component.debugElement.nativeElement;18 expect(element.querySelector('h1').textContent).toEqual('Hello World');19 });20});
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!!