Best JavaScript code snippet using ng-mocks
debug_element.ts
Source:debug_element.ts
1import {Type, isPresent, isBlank} from 'angular2/src/core/facade/lang';2import {ListWrapper, MapWrapper, Predicate} from 'angular2/src/core/facade/collection';3import {DOM} from 'angular2/src/core/dom/dom_adapter';4import {ElementInjector} from 'angular2/src/core/linker/element_injector';5import {AppView} from 'angular2/src/core/linker/view';6import {internalView} from 'angular2/src/core/linker/view_ref';7import {ElementRef} from 'angular2/src/core/linker/element_ref';8/**9 * A DebugElement contains information from the Angular compiler about an10 * element and provides access to the corresponding ElementInjector and11 * underlying DOM Element, as well as a way to query for children.12 */13export class DebugElement {14 _elementInjector: ElementInjector;15 /**16 * @private17 */18 constructor(private _parentView: AppView, private _boundElementIndex: number) {19 this._elementInjector = this._parentView.elementInjectors[this._boundElementIndex];20 }21 get componentInstance(): any {22 if (!isPresent(this._elementInjector)) {23 return null;24 }25 return this._elementInjector.getComponent();26 }27 get nativeElement(): any { return this.elementRef.nativeElement; }28 get elementRef(): ElementRef { return this._parentView.elementRefs[this._boundElementIndex]; }29 getDirectiveInstance(directiveIndex: number): any {30 return this._elementInjector.getDirectiveAtIndex(directiveIndex);31 }32 /**33 * Get child DebugElements from within the Light DOM.34 *35 * @return {DebugElement[]}36 */37 get children(): DebugElement[] {38 return this._getChildElements(this._parentView, this._boundElementIndex);39 }40 /**41 * Get the root DebugElement children of a component. Returns an empty42 * list if the current DebugElement is not a component root.43 *44 * @return {DebugElement[]}45 */46 get componentViewChildren(): DebugElement[] {47 var shadowView = this._parentView.getNestedView(this._boundElementIndex);48 if (!isPresent(shadowView)) {49 // The current element is not a component.50 return [];51 }52 return this._getChildElements(shadowView, null);53 }54 triggerEventHandler(eventName: string, eventObj: Event): void {55 this._parentView.triggerEventHandlers(eventName, eventObj, this._boundElementIndex);56 }57 hasDirective(type: Type): boolean {58 if (!isPresent(this._elementInjector)) {59 return false;60 }61 return this._elementInjector.hasDirective(type);62 }63 inject(type: Type): any {64 if (!isPresent(this._elementInjector)) {65 return null;66 }67 return this._elementInjector.get(type);68 }69 getLocal(name: string): any { return this._parentView.locals.get(name); }70 /**71 * Return the first descendant TestElement matching the given predicate72 * and scope.73 *74 * @param {Function: boolean} predicate75 * @param {Scope} scope76 *77 * @return {DebugElement}78 */79 query(predicate: Predicate<DebugElement>, scope: Function = Scope.all): DebugElement {80 var results = this.queryAll(predicate, scope);81 return results.length > 0 ? results[0] : null;82 }83 /**84 * Return descendant TestElememts matching the given predicate85 * and scope.86 *87 * @param {Function: boolean} predicate88 * @param {Scope} scope89 *90 * @return {DebugElement[]}91 */92 queryAll(predicate: Predicate<DebugElement>, scope: Function = Scope.all): DebugElement[] {93 var elementsInScope = scope(this);94 return ListWrapper.filter(elementsInScope, predicate);95 }96 _getChildElements(view: AppView, parentBoundElementIndex: number): DebugElement[] {97 var els = [];98 var parentElementBinder = null;99 if (isPresent(parentBoundElementIndex)) {100 parentElementBinder = view.proto.elementBinders[parentBoundElementIndex - view.elementOffset];101 }102 for (var i = 0; i < view.proto.elementBinders.length; ++i) {103 var binder = view.proto.elementBinders[i];104 if (binder.parent == parentElementBinder) {105 els.push(new DebugElement(view, view.elementOffset + i));106 var views = view.viewContainers[view.elementOffset + i];107 if (isPresent(views)) {108 ListWrapper.forEach(views.views, (nextView) => {109 els = els.concat(this._getChildElements(nextView, null));110 });111 }112 }113 }114 return els;115 }116}117/**118 * Returns a DebugElement for a ElementRef.119 *120 * @param {ElementRef}: elementRef121 * @return {DebugElement}122 */123export function inspectElement(elementRef: ElementRef): DebugElement {124 return new DebugElement(internalView(elementRef.parentView), elementRef.boundElementIndex);125}126export function asNativeElements(arr: DebugElement[]): any[] {127 return arr.map((debugEl) => debugEl.nativeElement);128}129export class Scope {130 static all(debugElement: DebugElement): DebugElement[] {131 var scope = [];132 scope.push(debugElement);133 ListWrapper.forEach(debugElement.children,134 (child) => { scope = scope.concat(Scope.all(child)); });135 ListWrapper.forEach(debugElement.componentViewChildren,136 (child) => { scope = scope.concat(Scope.all(child)); });137 return scope;138 }139 static light(debugElement: DebugElement): DebugElement[] {140 var scope = [];141 ListWrapper.forEach(debugElement.children, (child) => {142 scope.push(child);143 scope = scope.concat(Scope.light(child));144 });145 return scope;146 }147 static view(debugElement: DebugElement): DebugElement[] {148 var scope = [];149 ListWrapper.forEach(debugElement.componentViewChildren, (child) => {150 scope.push(child);151 scope = scope.concat(Scope.light(child));152 });153 return scope;154 }155}156export class By {157 static all(): Function { return (debugElement) => true; }158 static css(selector: string): Predicate<DebugElement> {159 return (debugElement) => {160 return isPresent(debugElement.nativeElement) ?161 DOM.elementMatches(debugElement.nativeElement, selector) :162 false;163 };164 }165 static directive(type: Type): Predicate<DebugElement> {166 return (debugElement) => { return debugElement.hasDirective(type); };167 }...
chapter-01.component.spec.ts
Source:chapter-01.component.spec.ts
1import { async, ComponentFixture, TestBed } from '@angular/core/testing';2import { Chapter01Component } from './chapter-01.component';3import { ReactiveFormsModule } from '@angular/forms';4import { DebugElement } from '@angular/core';5import { By } from '@angular/platform-browser';6function changeTextValue(input: DebugElement, value: string): void {7 input.nativeElement.value = value;8 input.triggerEventHandler('input', { target: { value } });9}10function changeRadioButtonValue(inputs: Array<DebugElement>, value: string): void {11 const input: DebugElement = inputs12 .filter((field: DebugElement) => field.nativeElement.value === value)13 .reduce((acc: DebugElement, field: DebugElement) => field, null);14 if (input) {15 input.nativeElement.click();16 }17}18function changeCheckboxStatus(input: DebugElement, checked: boolean): void {19 input.nativeElement.checked = checked;20 input.nativeElement.dispatchEvent(new Event('change'));21}22function changeSelectValue(input: DebugElement, value: string): void {23 input.nativeElement.selectedIndex = input.nativeElement.selectedIndex = input.queryAll(By.css('option'))24 .findIndex((option: DebugElement) => option.nativeElement.value === value);25 input.nativeElement.dispatchEvent(new Event('change'));26}27function submitFormByClick(button: DebugElement): void {28 button.nativeElement.click();29}30describe('Chapter01Component', () => {31 let component: Chapter01Component;32 let fixture: ComponentFixture<Chapter01Component>;33 const mockedData: any = {34 name: 'John Smith',35 email: 'john.smith@mail.com',36 issue: '0',37 agreements: {38 newsletter: true,39 rules: true40 },41 steps: [42 'step 1', 'step 2', 'step 3', 'step 4'43 ],44 description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'45 };46 beforeEach(async(() => {47 TestBed.configureTestingModule({48 imports: [ ReactiveFormsModule ],49 declarations: [ Chapter01Component ]50 })51 .compileComponents();52 }));53 beforeEach(() => {54 fixture = TestBed.createComponent(Chapter01Component);55 component = fixture.componentInstance;56 fixture.detectChanges();57 });58 it('should create', () => {59 expect(component).toBeTruthy();60 });61 describe('when user complete form and click send button', () => {62 let submitMethod;63 beforeEach(() => {64 submitMethod = spyOn(component, 'submit');65 changeTextValue(fixture.debugElement.query(By.css('input[formControlName="name"]')), mockedData.name);66 changeTextValue(fixture.debugElement.query(By.css('input[formControlName="email"]')), mockedData.email);67 changeSelectValue(fixture.debugElement.query(By.css('select[formControlName="issue"]')), mockedData.issue);68 changeCheckboxStatus(69 fixture.debugElement.query(By.css('input[formControlName="newsletter"]')),70 mockedData.agreements.newsletter71 );72 changeCheckboxStatus(73 fixture.debugElement.query(By.css('input[formControlName="rules"]')),74 mockedData.agreements.rules75 );76 mockedData.steps.forEach((value: string, key: number) => {77 changeTextValue(78 fixture.debugElement.queryAll(By.css('div[formArrayName="steps"] .step'))[key],79 mockedData.steps[key]80 );81 });82 changeTextValue(83 fixture.debugElement.query(By.css('textarea[formControlName="description"]')),84 mockedData.description85 );86 submitFormByClick(fixture.debugElement.query(By.css('.submit')));87 fixture.detectChanges();88 });89 it('should call submit method with data', () => {90 expect(submitMethod).toHaveBeenCalledWith(mockedData);91 });92 });93 describe('when user click "Set form values" button', () => {94 beforeEach(() => {95 fixture.debugElement.query(By.css('.set-values')).nativeElement.click();96 fixture.detectChanges();97 });98 it('should be set the form values', () => {99 expect(component.form.value).toEqual(mockedData);100 });101 });102 describe('when user click "Set name and email values" button', () => {103 beforeEach(() => {104 fixture.debugElement.query(By.css('.set-name-email-values')).nativeElement.click();105 fixture.detectChanges();106 });107 it('should be set name and email values', () => {108 expect(component.form.value).toEqual({109 name: 'John Smith',110 email: 'john.smith@mail.com',111 issue: '',112 agreements: {113 newsletter: false,114 rules: false115 },116 steps: [ '', '', '', '' ],117 description: ''118 });119 });120 });...
chapter-02.component.spec.ts
Source:chapter-02.component.spec.ts
1import { async, ComponentFixture, TestBed } from '@angular/core/testing';2import { Chapter02Component } from './chapter-02.component';3import { DebugElement } from '@angular/core';4import { By } from '@angular/platform-browser';5import { ReactiveFormsModule } from '@angular/forms';6function changeTextValue(input: DebugElement, value: string): void {7 input.nativeElement.value = value;8 input.triggerEventHandler('input', { target: { value } });9}10function changeRadioButtonValue(inputs: Array<DebugElement>, value: string): void {11 const input: DebugElement = inputs12 .filter((field: DebugElement) => field.nativeElement.value === value)13 .reduce((acc: DebugElement, field: DebugElement) => field, null);14 if (input) {15 input.nativeElement.click();16 }17}18function changeCheckboxStatus(input: DebugElement, checked: boolean): void {19 input.nativeElement.checked = checked;20 input.nativeElement.dispatchEvent(new Event('change'));21}22function changeSelectValue(input: DebugElement, value: string): void {23 input.nativeElement.selectedIndex = input.nativeElement.selectedIndex = input.queryAll(By.css('option'))24 .findIndex((option: DebugElement) => option.nativeElement.value === value);25 input.nativeElement.dispatchEvent(new Event('change'));26}27function submitFormByClick(button: DebugElement): void {28 button.nativeElement.click();29}30describe('Chapter02Component', () => {31 let component: Chapter02Component;32 let fixture: ComponentFixture<Chapter02Component>;33 const mockedData: any = {34 name: 'John Smith',35 email: 'john.smith@mail.com',36 issue: '0',37 agreements: {38 newsletter: true,39 rules: true40 },41 steps: [42 'step 1', 'step 2', 'step 3', 'step 4'43 ],44 description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'45 };46 beforeEach(async(() => {47 TestBed.configureTestingModule({48 imports: [ ReactiveFormsModule ],49 declarations: [ Chapter02Component ]50 })51 .compileComponents();52 }));53 beforeEach(() => {54 fixture = TestBed.createComponent(Chapter02Component);55 component = fixture.componentInstance;56 fixture.detectChanges();57 });58 it('should create', () => {59 expect(component).toBeTruthy();60 });61 describe('when user complete form and click send button', () => {62 let submitMethod;63 beforeEach(() => {64 submitMethod = spyOn(component, 'submit');65 changeTextValue(fixture.debugElement.query(By.css('input[formControlName="name"]')), mockedData.name);66 changeTextValue(fixture.debugElement.query(By.css('input[formControlName="email"]')), mockedData.email);67 changeSelectValue(fixture.debugElement.query(By.css('select[formControlName="issue"]')), mockedData.issue);68 changeCheckboxStatus(69 fixture.debugElement.query(By.css('input[formControlName="newsletter"]')),70 mockedData.agreements.newsletter71 );72 changeCheckboxStatus(73 fixture.debugElement.query(By.css('input[formControlName="rules"]')),74 mockedData.agreements.rules75 );76 mockedData.steps.forEach((value: string, key: number) => {77 changeTextValue(78 fixture.debugElement.queryAll(By.css('div[formArrayName="steps"] .step'))[key],79 mockedData.steps[key]80 );81 });82 changeTextValue(83 fixture.debugElement.query(By.css('textarea[formControlName="description"]')),84 mockedData.description85 );86 fixture.detectChanges();87 submitFormByClick(fixture.debugElement.query(By.css('.submit')));88 });89 it('should call submit method with data', () => {90 expect(submitMethod).toHaveBeenCalledWith(mockedData);91 });92 });93 describe('when user don\'t complete form', () => {94 let submitMethod;95 beforeEach(() => {96 submitMethod = spyOn(component, 'submit');97 submitFormByClick(fixture.debugElement.query(By.css('.submit')));98 fixture.detectChanges();99 });100 it('should be disable send button', () => {101 expect(submitMethod).not.toHaveBeenCalled();102 });103 it('should be display errors', () => {104 expect(fixture.debugElement.queryAll(By.css('.alert-danger')).length).toBe(10);105 });106 });...
Using AI Code Generation
1import { DebugElement } from '@angular/core';2import { ComponentFixture, TestBed } from '@angular/core/testing';3import { By } from '@angular/platform-browser';4import { MockBuilder, MockRender } from 'ng-mocks';5import { AppComponent } from './app.component';6import { AppModule } from './app.module';7describe('AppComponent', () => {8 let fixture: ComponentFixture<AppComponent>;9 let component: AppComponent;10 let debugElement: DebugElement;11 beforeEach(() => MockBuilder(AppComponent, AppModule));12 beforeEach(() => {13 fixture = MockRender(AppComponent);14 component = fixture.componentInstance;15 debugElement = fixture.debugElement;16 });17 it('should create the app', () => {18 expect(component).toBeTruthy();19 });20 it(`should have as title 'app'`, () => {21 expect(component.title).toEqual('app');22 });23 it('should render title in a h1 tag', () => {24 const h1 = debugElement.query(By.css('h1'));25 expect(h1.nativeElement.textContent).toContain('Welcome to app!');26 });27});28import { NgModule } from '@angular/core';29import { BrowserModule } from '@angular/platform-browser';30import { AppComponent } from './app.component';31@NgModule({32 imports: [BrowserModule],33})34export class AppModule {}35import { Component } from '@angular/core';36@Component({37 <h1>Welcome to {{ title }}!</h1>38})39export class AppComponent {40 title = 'app';41}42<h1>Welcome to {{ title }}!</h1>43import { ComponentFixture, TestBed } from '@angular/core/testing';44import { AppComponent } from './app.component';45describe('AppComponent', () => {46 let fixture: ComponentFixture<AppComponent>;47 let component: AppComponent;48 beforeEach(async () => {49 await TestBed.configureTestingModule({50 }).compileComponents();51 fixture = TestBed.createComponent(AppComponent);52 component = fixture.componentInstance;53 fixture.detectChanges();54 });55 it('should create the app', () => {56 expect(component).toBeTruthy();57 });58 it(`should have as title '
Using AI Code Generation
1import { DebugElement } from '@angular/core';2import { async, ComponentFixture, TestBed } from '@angular/core/testing';3import { By } from '@angular/platform-browser';4import { MockComponent } from 'ng-mocks';5import { AppComponent } from './app.component';6import { ChildComponent } from './child/child.component';7describe('AppComponent', () => {8 let component: AppComponent;9 let fixture: ComponentFixture<AppComponent>;10 let debugElement: DebugElement;11 beforeEach(async(() => {12 TestBed.configureTestingModule({13 MockComponent(ChildComponent)14 })15 .compileComponents();16 }));17 beforeEach(() => {18 fixture = TestBed.createComponent(AppComponent);19 component = fixture.componentInstance;20 debugElement = fixture.debugElement;21 fixture.detectChanges();22 });23 it('should create', () => {24 expect(component).toBeTruthy();25 });26 it('should display Child Component', () => {27 const childComponent = debugElement.query(By.css('app-child'));28 expect(childComponent).toBeTruthy();29 });30});
Using AI Code Generation
1import { DebugElement } from '@angular/core';2import { By } from '@angular/platform-browser';3import { MockRender, ngMocks } from 'ng-mocks';4describe('test', () => {5 beforeEach(() => MockRender('<div>Test</div>'));6 it('should work', () => {7 const debugElement: DebugElement = ngMocks.find('div');8 expect(debugElement).toBeDefined();9 expect(debugElement.nativeElement.textContent).toEqual('Test');10 });11 it('should work with by', () => {12 const debugElement: DebugElement = ngMocks.find(By.css('div'));13 expect(debugElement).toBeDefined();14 expect(debugElement.nativeElement.textContent).toEqual('Test');15 });16});17import { DebugElement } from '@angular/core';18import { By } from '@angular/platform-browser';19import { MockRender, ngMocks } from 'ng-mocks';20describe('test', () => {21 beforeEach(() => MockRender('<div>Test</div>'));22 it('should work', () => {23 const debugElement: DebugElement = ngMocks.find('div');24 expect(debugElement).toBeDefined();25 expect(debugElement.nativeElement.textContent).toEqual('Test');26 });27 it('should work with by', () => {28 const debugElement: DebugElement = ngMocks.find(By.css('div'));29 expect(debugElement).toBeDefined();30 expect(debugElement.nativeElement.textContent).toEqual('Test');31 });32});33import { DebugElement } from '@angular/core';34import { By } from '@angular/platform-browser';35import { MockRender, ngMocks } from 'ng-mocks';36describe('test', () => {37 beforeEach(() => MockRender('<div>Test</div>'));38 it('should work', () => {39 const debugElement: DebugElement = ngMocks.find('div');40 expect(debugElement).toBeDefined();41 expect(debugElement.nativeElement.textContent).toEqual('Test');42 });43 it('should work with by', () => {44 const debugElement: DebugElement = ngMocks.find(By.css('div'));45 expect(debugElement).toBeDefined();46 expect(debugElement.nativeElement.textContent).toEqual('Test');47 });48});49import { DebugElement } from
Using AI Code Generation
1import { debugElement } from 'ng-mocks';2import { By } from '@angular/platform-browser';3describe('AppComponent', () => {4 let fixture: ComponentFixture<AppComponent>;5 let component: AppComponent;6 beforeEach(async(() => {7 TestBed.configureTestingModule({8 }).compileComponents();9 fixture = TestBed.createComponent(AppComponent);10 component = fixture.componentInstance;11 }));12 it('should create the app', () => {13 expect(component).toBeTruthy();14 });15 it('should have a title', () => {16 expect(component.title).toEqual('app');17 });18 it('should render title in a h1 tag', () => {19 const title = debugElement(fixture, 'h1').nativeElement;20 expect(title.textContent).toContain('Welcome to app!');21 });22});23<h1> Welcome to {{title}}! </h1>24import { MockBuilder } from 'ng-mocks';25import { AppComponent } from './app.component';26import { MockedComponent } from 'ng-mocks/dist/lib/mock-builder/mock';27import { DataService } from './data.service';28describe('AppComponent', () => {29 let component: AppComponent;30 let fixture: ComponentFixture<AppComponent>;31 let dataService: DataService;32 beforeEach(async(() => {33 MockBuilder(AppComponent, DataService)34 .mock(DataService, {35 get: () => 'Mock Data'36 });37 }));38 beforeEach(() => {
Using AI Code Generation
1import { MockBuilder, MockRender } from 'ng-mocks';2import { ComponentFixture, TestBed } from '@angular/core/testing';3describe('test', () => {4 let fixture: ComponentFixture<any>;5 beforeEach(() => {6 MockBuilder();7 fixture = MockRender();8 });9 it('test', () => {10 const debugElement = fixture.debugElement;11 });12});13import { MockBuilder, MockRender } from 'ng-mocks';14import { ComponentFixture, TestBed } from '@angular/core/testing';15describe('test', () => {16 let fixture: ComponentFixture<any>;17 beforeEach(() => {18 MockBuilder();19 fixture = MockRender();20 });21 it('test', () => {22 const debugElement = fixture.debugElement;23 });24});25import { DebugElement } from '@angular/core';26import { DebugElement } from '@angular/core';27describe('test', () => {28 let fixture: ComponentFixture<any>;29 beforeEach(() => {30 MockBuilder();31 fixture = MockRender();32 });33 it('test', () => {34 const debugElement = fixture.debugElement;35 });36});
Using AI Code Generation
1import { MockRender } from 'ng-mocks';2import { render } from '@testing-library/angular';3describe('MockRender', () => {4 it('should render', () => {5 const component = MockRender(MyComponent);6 const debugElement = component.debugElement;7 });8});9describe('@testing-library/angular', () => {10 it('should render', async () => {11 const { debugElement } = await render(MyComponent);12 });13});
Using AI Code Generation
1describe('test', () => {2 it('should test', () => {3 const fixture = MockRender(`4 `);5 const debugElement = MockRender.debugElement(fixture);6 const component = debugElement.query(By.directive(SomeComponent));7 expect(component).toBeDefined();8 });9});10import { Component } from '@angular/core';11@Component({12})13export class SomeComponent {}14import { SomeComponent } from './some-component.component';15import { MockRender } from 'ng-mocks';16describe('SomeComponent', () => {17 it('should test', () => {18 const fixture = MockRender(SomeComponent);19 const debugElement = MockRender.debugElement(fixture);20 const component = debugElement.query(By.directive(SomeComponent));21 expect(component).toBeDefined();22 });23});24import { SomeComponent } from './some-component.component';25import { MockRender } from 'ng-mocks';26describe('SomeComponent', () => {27 it('should test', () => {28 const fixture = MockRender(SomeComponent);29 const debugElement = MockRender.debugElement(fixture);30 const component = debugElement.query(By.directive(SomeComponent));31 expect(component).toBeDefined();32 });33});34import { SomeComponent } from './some-component.component';35import { MockRender } from 'ng-mocks';36describe('SomeComponent', () => {37 it('should test', () => {38 const fixture = MockRender(SomeComponent);39 const debugElement = MockRender.debugElement(fixture);40 const component = debugElement.query(By.directive(SomeComponent));41 expect(component).toBeDefined();42 });43});
Using AI Code Generation
1import { debugElement } from 'ng-mocks';2const element = debugElement(fixture, '.my-class');3import { debugElement } from 'ng-mocks';4const element = debugElement(fixture, '.my-class');5import { debugElement } from 'ng-mocks';6const element = debugElement(fixture, '.my-class');7import { debugElement } from 'ng-mocks';8const element = debugElement(fixture, '.my-class');9import { debugElement } from 'ng-mocks';10const element = debugElement(fixture, '.my-class');11import { debugElement } from 'ng-mocks';12const element = debugElement(fixture, '.my-class');
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!!