Best JavaScript code snippet using ng-mocks
definition.test.ts
Source:definition.test.ts
1import pth from 'path';2import fse from 'fs-extra';3import globby from 'globby';4import { pathsDefs, defsFileCount, outputInheritedDefs } from './utils.test';5import { ExtractorEventEmitter, ExtractorEventListener } from './extractor-event-emitter';6import { parseXML, saveXML } from './xml';7import { DefsElementMap, DefinitionExtractor } from './definition';8import { cloneObject } from './object';9describe('definition', () => {10 const emitter = new ExtractorEventEmitter();11 const definitionExtractor = new DefinitionExtractor(emitter);12 let defMaps: DefsElementMap[];13 beforeAll(async () => {14 defMaps = await Promise.all(pathsDefs.map(path => definitionExtractor.load(path)));15 });16 test('load', async () => {17 expect(Object.keys(defMaps[0]).length).toBe(defsFileCount);18 });19 test('resolveInheritance', async () => {20 // core21 definitionExtractor.resolveInheritance(defMaps);22 const core = defMaps[0];23 await fse.remove(outputInheritedDefs);24 for (const [path, root] of Object.entries(core)) {25 await saveXML(pth.join(outputInheritedDefs, path), root, false);26 }27 expect(Object.keys(core).length).toBe(defsFileCount);28 });29 test('resolveInheritance arguments error', async () => {30 // arguments error31 try {32 await definitionExtractor.resolveInheritance([]);33 } catch (error) {34 expect(error).toBeTruthy();35 }36 });37 test('resolveInheritance parent not found', async () => {38 // parent not found39 let errorEmitted = false;40 let listener: ExtractorEventListener<string> = (event, error) => {41 expect(event).toBe('error');42 errorEmitted = true;43 expect(error.includes('not found')).toBe(true);44 expect(error.includes('MockDef')).toBe(true);45 expect(error.includes('undefined')).toBe(true);46 expect(error.includes('MockX')).toBe(true);47 };48 emitter.addListener('error', listener);49 await definitionExtractor.resolveInheritance([50 {51 'test.xml': parseXML(`52 <Defs>53 <MockDef ParentName="MockX"></MockDef>54 </Defs>`),55 },56 ]);57 emitter.removeListener('error', listener);58 listener = (event, error) => {59 expect(error.includes('MockDefABC'));60 };61 await definitionExtractor.resolveInheritance([62 {63 'test.xml': parseXML(`64 <Defs>65 <MockDef ParentName="MockX">66 <defName>MockDefABC</defName>67 </MockDef>68 </Defs>`),69 },70 ]);71 emitter.removeListener('error', listener);72 expect(errorEmitted).toBe(true);73 });74 test('resolveInheritanceNodeRecursively & resolveXmlNodeFor', async () => {75 const root = parseXML(`76 <Defs>77 <MockDef Name="Mock0">78 <Some>79 <A></A>80 <B></B>81 </Some>82 </MockDef>83 <MockDef ParentName="Mock0">84 <Some>C</Some>85 </MockDef>86 </Defs>`);87 const {88 elements: [mock0, mock1],89 } = root;90 await expect(() =>91 definitionExtractor.resolveInheritanceNodeRecursively({92 root,93 def: mock1,94 resolvedDef: mock1,95 parent: {96 root,97 def: mock0,98 resolvedDef: mock0,99 children: [],100 },101 children: [],102 }),103 ).toThrowError(/cyclic/);104 await expect(() =>105 definitionExtractor.resolveXmlNodeFor({106 root,107 def: mock1,108 parent: {109 root,110 def: mock0,111 children: [],112 },113 children: [],114 }),115 ).toThrowError(/not been resolved yet/);116 });117 test('recursiveNodeCopyOverwriteElements', () => {118 const root = parseXML(`119 <Defs>120 <MockDef Name="Mock0">121 <Some>122 <A></A>123 <B></B>124 </Some>125 </MockDef>126 <MockDef ParentName="Mock0">127 <Some>128 <C></C>129 </Some>130 </MockDef>131 <MockDef2>132 <Some></Some>133 </MockDef2>134 <MockDef3>X</MockDef3>135 </Defs>136 `);137 const {138 elements: [mock0, mock1, mock2, mock3],139 } = root;140 const child = cloneObject(mock1);141 const current = cloneObject(mock0);142 definitionExtractor.recursiveNodeCopyOverwriteElements(child, current);143 expect(current.elements[0].elements.length).toBe(3);144 definitionExtractor.recursiveNodeCopyOverwriteElements(mock3, mock2);145 });...
xml.test.ts
Source:xml.test.ts
1import pth from 'path';2import fse from 'fs-extra';3import globby from 'globby';4import { pathCore, pathTestMods, resolvePath, TEMP } from './utils.test';5import {6 loadXML,7 parseXML,8 defaultXmlPrettierOptions,9 resolveXmlPrettierOptions,10 saveXML,11} from './xml';12describe('xml', () => {13 test('load', async () => {14 const ids = await globby(['*'], { cwd: pathTestMods, onlyDirectories: true });15 await Promise.all(16 ids.slice(0, 10).map(async id => {17 const pathDefs = pth.join(pathTestMods, id, 'Defs');18 if (await fse.pathExists(pathDefs)) {19 const defFiles = await globby(['**/*.xml'], {20 cwd: pathDefs,21 caseSensitiveMatch: false,22 onlyFiles: true,23 });24 Promise.all(25 defFiles.map(async file => {26 const root = await loadXML(pth.join(pathDefs, file));27 expect(root.nodeType).toBe('element');28 }),29 );30 }31 }),32 );33 });34 test('parse', () => {35 const rootData = parseXML(`36 <Defs>37 <!---->38 <MockDef Name="MockBase"><defName>Mock_0</defName></MockDef>39 <MockDef ParentName="MockBase">40 <defName>Mock_1</defName>41 </MockDef>42 <MockDef disabled="">43 <defName></defName>44 </MockDef>45 <![CDATA[]]>46 </Defs>47 `);48 expect(rootData.childNodes.length).toBe(10);49 expect(rootData.elements.length).toBe(3);50 expect(rootData.elements[0].attributes.Name).toBe('MockBase');51 expect(rootData.elements[0].childNodes.length).toBe(1);52 expect(rootData.elements[1].attributes.ParentName).toBe('MockBase');53 expect(rootData.elements[1].childNodes.length).toBe(3);54 });55 test('prettier options', () => {56 {57 const { resolvedOptions } = resolveXmlPrettierOptions();58 expect(resolvedOptions).toEqual(defaultXmlPrettierOptions());59 }60 {61 const { tab, indent, eol, newline } = resolveXmlPrettierOptions();62 expect(tab).toBe(' ');63 expect(indent.value).toBe(' ');64 expect(eol).toBe('\n');65 expect(newline.value).toBe('\n');66 }67 {68 const { tab, indent } = resolveXmlPrettierOptions({69 tabWidth: 3,70 });71 expect(tab).toBe(' ');72 expect(indent.value).toBe(' ');73 }74 {75 const { tab, indent } = resolveXmlPrettierOptions({76 tabWidth: 4,77 });78 expect(tab).toBe(' ');79 expect(indent.value).toBe(' ');80 }81 {82 const { tab, indent } = resolveXmlPrettierOptions({83 tabWidth: 4,84 useTabs: true,85 });86 expect(tab).toBe('\t');87 expect(indent.value).toBe('\t');88 }89 {90 const { eol, newline } = resolveXmlPrettierOptions({91 endOfLine: 'cr',92 });93 expect(eol).toBe('\r');94 expect(newline.value).toBe('\r');95 }96 {97 const { eol, newline } = resolveXmlPrettierOptions({98 endOfLine: 'crlf',99 });100 expect(eol).toBe('\r\n');101 expect(newline.value).toBe('\r\n');102 }103 {104 const { eol, newline } = resolveXmlPrettierOptions({105 endOfLine: 'lf',106 });107 expect(eol).toBe('\n');108 expect(newline.value).toBe('\n');109 }110 });111 test('save', async () => {112 const rootData = parseXML(`113 <Defs>114 <!---->115 <MockDef Name="MockBase"><defName>Mock_0</defName></MockDef>116 <MockDef ParentName="MockBase">117 <defName>Mock_1</defName>118 </MockDef>119 <MockDef disabled="">120 <defName></defName>121 </MockDef>122 </Defs>123 `);124 await Promise.all([125 saveXML(resolvePath(TEMP, 'xml', '0.xml'), rootData, false),126 saveXML(resolvePath(TEMP, 'xml', '1.xml'), rootData, true),127 saveXML(resolvePath(TEMP, 'xml', '2.xml'), rootData, true, {128 printWidth: 120,129 }),130 saveXML(resolvePath(TEMP, 'xml', '3.xml'), rootData, true, {131 tabWidth: 4,132 endOfLine: 'cr',133 }),134 saveXML(resolvePath(TEMP, 'xml', '4.xml'), rootData, true, {135 useTabs: true,136 endOfLine: 'crlf',137 }),138 ]);139 });...
ClassGenerator.ts
Source:ClassGenerator.ts
1/**2 * Copyright (c) Samsung, Inc. and its affiliates.3 *4 * This source code is licensed under the MIT license found in the5 * LICENSE file in the root directory of this source tree.6 */7import stringify from "json-stable-stringify";8import path from "path";9import { SourceFile } from "ts-simple-ast";10import { IClassSnapData, IClassSnapshot, ISnapshot } from "../contracts";11import { ClassSnapshotTag } from "../matchers/ClassMockMatcher";12import { MockGenerator } from "./base";13export class ClassGenerator extends MockGenerator {14 private mockDef: any = {};15 generate(16 getFile: (fileName: string) => SourceFile,17 allSnapshots: ISnapshot[]18 ) {19 const snapshots = allSnapshots.filter(snap =>20 snap.key.includes(ClassSnapshotTag)21 ) as IClassSnapshot[];22 snapshots.forEach(snap =>23 this.parseSingleMock(snap.data, snap.packageName)24 );25 const classNames = Object.keys(this.mockDef);26 classNames.forEach(className => {27 const mockClassName = this.getMockClassName(className);28 const myClassFile = getFile(`${className}.ts`);29 const classDeclaration = myClassFile.addClass({30 name: mockClassName31 });32 classDeclaration.setIsExported(true);33 const methods = this.mockDef[className];34 const methodNames = Object.keys(methods);35 methodNames.forEach(methodName => {36 const mocks = methods[methodName];37 const mockNames = Object.keys(mocks);38 const mockTypes = mockNames.map(value => {39 return `"${value}"`;40 });41 const types = mockTypes.join(" | ");42 const method = classDeclaration.addMethod({43 isStatic: true,44 parameters: [{ name: "mock", type: types }],45 name: methodName,46 returnType: "any"47 });48 method.setBodyText(writer =>49 writer.write("switch (mock)").block(() => {50 mockNames.forEach(mockName => {51 writer.write(`case "${mockName}":`).indentBlock(() => {52 writer.write(53 `return ${stringify(mocks[mockName], { space: " " })}`54 );55 });56 });57 writer.write(`default:`).indentBlock(() => {58 writer.write(`throw Error("Unknown mock: "+mock);`);59 });60 })61 );62 });63 });64 }65 private parseSingleMock(66 snapshot: IClassSnapData,67 packageName?: string68 ): void {69 const fullClassName = this.getFullClassName(70 snapshot.className,71 packageName72 );73 let classDef = this.mockDef[fullClassName];74 if (!classDef) {75 classDef = {};76 this.mockDef[fullClassName] = classDef;77 }78 let methodDef = classDef[snapshot.methodName];79 if (!methodDef) {80 methodDef = {};81 classDef[snapshot.methodName] = methodDef;82 }83 const mockName = methodDef[snapshot.mockName];84 if (!mockName) {85 methodDef[snapshot.mockName] = snapshot.mock;86 } else {87 throw Error(88 `Duplicate mock name on class: ${fullClassName} for method ` +89 snapshot.methodName +90 ": " +91 snapshot.mockName92 );93 }94 }95 private getFullClassName(className: string, packageName?: string): string {96 return packageName ? path.join(packageName, className) : className;97 }98 private getMockClassName(fullClassName: string): string {99 return `${path.basename(fullClassName)}Mocks`;100 }...
Using AI Code Generation
1import { mockDef } from 'ng-mocks';2import { MyComponent } from './my.component';3describe('MyComponent', () => {4 it('should create', () => {5 const fixture = mockDef(MyComponent);6 expect(fixture).toBeTruthy();7 });8});
Using AI Code Generation
1import { mockDef } from 'ng-mocks';2import { componentDef } from 'ng-mocks';3import { mockProvider } from 'ng-mocks';4import { mockPipe } from 'ng-mocks';5import { mockDirective } from 'ng-mocks';6import { mockComponent } from 'ng-mocks';7import { mockModule } from 'ng-mocks';8import { mockRender } from 'ng-mocks';9import { mockInstance } from 'ng-mocks';10import { mockProvider } from 'ng-mocks';11import { mockPipe } from 'ng-mocks';12import { mockDirective } from 'ng-mocks';13import { mockComponent } from 'ng-mocks';14import { mockModule } from 'ng-mocks';15import { mockRender } from 'ng-mocks';16import { mockInstance } from 'ng-mocks';17import { mockProvider } from 'ng-mocks';18import { mockPipe } from 'ng-mocks';19import { mockDirective } from 'ng-mocks';20import { mockComponent } from 'ng-mocks';21import { mockModule } from 'ng-mocks';22import { mockRender } from 'ng-mocks';
Using AI Code Generation
1import { mockDef } from 'ng-mocks';2import { mockDef } from 'ng-mocks';3describe('TestComponent', () => {4 let component: TestComponent;5 let fixture: ComponentFixture<TestComponent>;6 beforeEach(async(() => {7 TestBed.configureTestingModule({8 })9 .compileComponents();10 }));11 beforeEach(() => {12 fixture = TestBed.createComponent(TestComponent);13 component = fixture.componentInstance;14 fixture.detectChanges();15 });16 it('should create', () => {17 expect(component).toBeTruthy();18 });19});20import { Component, OnInit } from '@angular/core';21@Component({22})23export class TestComponent implements OnInit {24 constructor() { }25 ngOnInit() {26 }27}
Using AI Code Generation
1import { mockDef } from 'ng-mocks';2describe('TestComponent', () => {3 it('should create', () => {4 const component = mockDef(TestComponent);5 expect(component).toBeTruthy();6 });7});8import { mockDef } from 'ng-mocks';9describe('TestComponent', () => {10 it('should create', () => {11 const component = mockDef(TestComponent);12 expect(component).toBeTruthy();13 });14});15<ng-container *ngIf="mockDef(TestComponent); else elseBlock">16<ng-container *ngIf="mockDef(TestComponent); else elseBlock">17<ng-container *ngIf="mockDef(TestComponent); else elseBlock">18<ng-container *ngIf="mockDef(TestComponent); else elseBlock">19<ng-container *ngIf="mockDef(TestComponent); else elseBlock">
Using AI Code Generation
1import { mockDef } from 'ng-mocks';2@Component({3 template: `Hello {{name}}`4})5class HelloComponent {6 @Input() public name: string;7}8describe('HelloComponent', () => {9 let fixture: ComponentFixture<HelloComponent>;10 let component: HelloComponent;11 beforeEach(() => {12 fixture = mockDef(HelloComponent);13 component = fixture.componentInstance;14 });15 it('should render', () => {16 component.name = 'Test';17 fixture.detectChanges();18 expect(fixture.nativeElement.innerHTML).toEqual('Hello Test');19 });20});21import { ngMocks } from 'ng-mocks';22import { HelloComponent } from './hello.component';23describe('HelloComponent', () => {24 let fixture: ComponentFixture<HelloComponent>;25 let component: HelloComponent;26 beforeEach(() => {27 fixture = ngMocks.guts(HelloComponent);28 component = fixture.componentInstance;29 });30 it('should render', () => {31 component.name = 'Test';32 fixture.detectChanges();33 expect(fixture.nativeElement.innerHTML).toEqual('Hello Test');34 });35});36import { mockDef } from 'ng-mocks';37@Component({38 template: `Hello {{name}}`39})40class HelloComponent {41 @Input() public name: string;42}43describe('HelloComponent', () => {44 let fixture: ComponentFixture<HelloComponent>;45 let component: HelloComponent;46 beforeEach(() => {47 fixture = mockDef(HelloComponent);48 component = fixture.componentInstance;49 });50 it('should render', () => {51 component.name = 'Test';52 fixture.detectChanges();53 expect(fixture.nativeElement.innerHTML).toEqual('Hello Test');54 });55});56import { ngMocks } from 'ng-mocks';57import { HelloComponent } from './hello.component';58describe('HelloComponent', () => {59 let fixture: ComponentFixture<HelloComponent>;60 let component: HelloComponent;61 beforeEach(() => {62 fixture = ngMocks.guts(HelloComponent);63 component = fixture.componentInstance;64 });65 it('should render', ()
Using AI Code Generation
1describe('Test', () => {2 beforeEach(() => {3 TestBed.configureTestingModule({4 imports: [HttpClientTestingModule],5 {6 useValue: {7 get: () => {8 return of({data: {foo: 'bar'}});9 },10 },11 },12 });13 });14 it('should call mockDef', () => {15 const mockDef = TestBed.get('mockDef');16 const spy = spyOn(mockDef, 'get').and.callThrough();17 mockDef.get();18 expect(spy).toHaveBeenCalled();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!!