Best JavaScript code snippet using ng-mocks
mock-component.spec.ts
Source:mock-component.spec.ts  
1import {2  Component,3  ContentChild,4  ContentChildren,5  DebugElement,6  ElementRef,7  QueryList,8  TemplateRef,9  ViewChild,10  ViewChildren,11  ViewContainerRef,12} from '@angular/core';13import { ComponentFixture, TestBed } from '@angular/core/testing';14import {15  FormControl,16  FormsModule,17  ReactiveFormsModule,18} from '@angular/forms';19import { By } from '@angular/platform-browser';20import { isMockOf } from '../common/func.is-mock-of';21import { MockedDirective } from '../mock-directive/types';22import { ngMocks } from '../mock-helper/mock-helper';23import { MockRender } from '../mock-render/mock-render';24import { MockComponent, MockComponents } from './mock-component';25import { ChildComponent } from './mock-component.spec.child-component.fixtures';26import { CustomFormControlComponent } from './mock-component.spec.custom-form-control.component.fixtures';27import { EmptyComponent } from './mock-component.spec.empty-component.component.fixtures';28import { GetterSetterComponent } from './mock-component.spec.getter-setter.component.fixtures';29import { SimpleComponent } from './mock-component.spec.simple-component.component.fixtures';30import { TemplateOutletComponent } from './mock-component.spec.template-outlet.component.fixtures';31import { MockedComponent } from './types';32@Component({33  selector: 'example-component-container',34  template: `35    <getter-setter></getter-setter>36    <simple-component37      [someInput]="'hi'"38      [someOtherInput]="'bye'"39      [someInput3]="true"40      (someOutput1)="emitted = $event"41      (someOutput2)="emitted = $event"42    >43    </simple-component>44    <simple-component45      [someInput]="'hi again'"46      #f="seeimple"47    ></simple-component>48    <empty-component></empty-component>49    <custom-form-control50      [formControl]="formControl"51    ></custom-form-control>52    <empty-component id="ng-content-component">doh</empty-component>53    <empty-component54      id="ngmodel-component"55      [(ngModel)]="someOutputHasEmitted"56    ></empty-component>57    <child-component></child-component>58    <template-outlet-component id="element-with-content-and-template">59      ng-content body header60      <ng-template #block1>61        <div>block 1 body</div>62      </ng-template>63      <ng-template #block2><span>block 2 body</span></ng-template>64      ng-content body footer65    </template-outlet-component>66    <empty-component67      id="element-without-content-and-template"68    ></empty-component>69    <empty-component id="element-with-content-only"70      >child of element-with-content-only</empty-component71    >72  `,73})74export class ExampleContainerComponent {75  @ViewChild(ChildComponent, { static: true } as any)76  public childComponent?: ChildComponent;77  public emitted = '';78  public someOutputHasEmitted = '';79  public readonly formControl = new FormControl('');80  public performActionOnChild(s: string): void {81    if (this.childComponent) {82      this.childComponent.performAction(s);83    }84  }85}86describe('MockComponent', () => {87  let component: ExampleContainerComponent;88  let fixture: ComponentFixture<ExampleContainerComponent>;89  beforeEach(async () => {90    await TestBed.configureTestingModule({91      declarations: [92        ExampleContainerComponent,93        MockComponents(94          EmptyComponent,95          GetterSetterComponent,96          SimpleComponent,97          TemplateOutletComponent,98          ChildComponent,99          CustomFormControlComponent,100        ),101      ],102      imports: [FormsModule, ReactiveFormsModule],103    }).compileComponents();104    fixture = TestBed.createComponent(ExampleContainerComponent);105    component = fixture.componentInstance;106  });107  it('should have use a selector of the original component', () => {108    fixture.detectChanges();109    const mockComponent = fixture.debugElement.query(110      By.css('simple-component'),111    );112    expect(mockComponent).not.toBeNull();113  });114  it('should have the input set on the mock component', () => {115    fixture.detectChanges();116    const mockComponent = fixture.debugElement.query(117      By.directive(SimpleComponent),118    ).componentInstance;119    expect(mockComponent.someInput).toEqual('hi');120    expect(mockComponent.someInput2).toEqual('bye');121  });122  it('has no issues with multiple decorators on an input', () => {123    fixture.detectChanges();124    const mockComponent = fixture.debugElement.query(125      By.directive(SimpleComponent),126    );127    expect(mockComponent.componentInstance.someInput3).toEqual(true);128  });129  it('should trigger output bound behavior', () => {130    fixture.detectChanges();131    const mockComponent = fixture.debugElement.query(132      By.directive(SimpleComponent),133    ).componentInstance;134    mockComponent.someOutput1.emit('hi');135    expect(component.emitted).toEqual('hi');136  });137  it('should trigger output bound behavior for extended outputs', () => {138    fixture.detectChanges();139    const mockComponent = fixture.debugElement.query(140      By.directive(SimpleComponent),141    ).componentInstance;142    mockComponent.someOutput2.emit('hi');143    expect(component.emitted).toEqual('hi');144  });145  it('the mock should have an ng-content body', () => {146    fixture.detectChanges();147    const mockComponent = fixture.debugElement.query(148      By.css('#ng-content-component'),149    );150    expect(mockComponent.nativeElement.textContent).toContain('doh');151  });152  it('should give each instance of a mock component its own event emitter', () => {153    const mockComponents = fixture.debugElement.queryAll(154      By.directive(SimpleComponent),155    );156    const mockComponent1 = mockComponents[0].componentInstance;157    const mockComponent2 = mockComponents[1].componentInstance;158    expect(mockComponent1.someOutput1).not.toEqual(159      mockComponent2.someOutput1,160    );161  });162  it('should work with components w/o inputs or outputs', () => {163    const mockComponent = fixture.debugElement.query(164      By.directive(EmptyComponent),165    );166    expect(mockComponent).not.toBeNull();167  });168  it('should allow ngModel bindings', () => {169    const mockComponent = fixture.debugElement.query(170      By.css('#ngmodel-component'),171    );172    expect(mockComponent).not.toBeNull();173  });174  it('should memoize the return value by argument', () => {175    expect(MockComponent(EmptyComponent)).toBe(176      MockComponent(EmptyComponent),177    );178    expect(MockComponent(SimpleComponent)).toBe(179      MockComponent(SimpleComponent),180    );181    expect(MockComponent(EmptyComponent)).not.toBe(182      MockComponent(SimpleComponent),183    );184  });185  it('should set ViewChild components correctly', () => {186    fixture.detectChanges();187    expect(component.childComponent).toBeTruthy();188  });189  it('should allow spying of viewchild component methods', () => {190    const spy = component.childComponent191      ? component.childComponent.performAction192      : null;193    component.performActionOnChild('test');194    expect(spy).toHaveBeenCalledWith('test');195  });196  it('should set getters and setters to undefined instead of function', () => {197    const mockComponent = ngMocks.findInstance(198      fixture.debugElement,199      GetterSetterComponent,200    ) as MockedDirective<GetterSetterComponent>;201    expect(mockComponent.normalMethod).toBeDefined();202    expect(mockComponent.myGetter).not.toBeDefined();203    expect(mockComponent.mySetter).not.toBeDefined();204    expect(mockComponent.normalProperty).not.toBeDefined();205  });206  describe('ReactiveForms - ControlValueAccessor', () => {207    it('should allow you simulate the component being touched', () => {208      fixture.detectChanges();209      const customFormControl: MockedComponent<CustomFormControlComponent> =210        fixture.debugElement.query(211          By.css('custom-form-control'),212        ).componentInstance;213      customFormControl.__simulateTouch();214      expect(component.formControl.touched).toBe(true);215    });216    it('should allow you simulate a value being set', () => {217      fixture.detectChanges();218      const customFormControl: MockedComponent<CustomFormControlComponent> =219        fixture.debugElement.query(220          By.css('custom-form-control'),221        ).componentInstance;222      customFormControl.__simulateChange('foo');223      expect(component.formControl.value).toBe('foo');224    });225  });226  describe('NgTemplateOutlet', () => {227    it('renders all @ContentChild properties and ngContent in wrappers too', () => {228      let block1: DebugElement;229      let block2: DebugElement;230      let block3: DebugElement;231      fixture.detectChanges();232      // a mock component with @ViewChild was created without errors.233      const templateOutlet = fixture.debugElement.query(234        By.css('#element-with-content-and-template'),235      );236      expect(templateOutlet).toBeTruthy();237      // looking for ng-content.238      const ngContent = templateOutlet;239      expect(ngContent).toBeTruthy();240      expect(241        ngContent.nativeElement.textContent242          .replace(/\s+/gim, ' ')243          .trim(),244      ).toEqual('ng-content body header ng-content body footer');245      // looking for 1st templateRef.246      block1 = templateOutlet.query(By.css('[data-key="block1"]'));247      expect(block1).toBeFalsy();248      (249        templateOutlet.componentInstance as MockedComponent<TemplateOutletComponent>250      ).__render('block1');251      block1 = templateOutlet.query(By.css('[data-key="block1"]'));252      expect(block1).toBeTruthy();253      expect(block1.nativeElement.textContent.trim()).toEqual(254        'block 1 body',255      );256      // looking for 2nd templateRef.257      block2 = templateOutlet.query(By.css('[data-key="block2"]'));258      expect(block2).toBeFalsy();259      (260        templateOutlet.componentInstance as MockedComponent<TemplateOutletComponent>261      ).__render('block2');262      block2 = templateOutlet.query(By.css('[data-key="block2"]'));263      expect(block2).toBeTruthy();264      expect(block2.nativeElement.textContent.trim()).toEqual(265        'block 2 body',266      );267      // looking for 3rd templateRef.268      block3 = templateOutlet.query(By.css('[data-key="block3"]'));269      expect(block3).toBeFalsy();270      (271        templateOutlet.componentInstance as MockedComponent<TemplateOutletComponent>272      ).__render('block3');273      fixture.detectChanges();274      block3 = templateOutlet.query(By.css('[data-key="block3"]'));275      expect(block3).toBeTruthy();276      expect(block3.nativeElement.textContent.trim()).toEqual('');277      (278        templateOutlet.componentInstance as MockedComponent<TemplateOutletComponent>279      ).__hide('block3');280      fixture.detectChanges();281      expect(282        templateOutlet.query(By.css('[data-key="block3"]')),283      ).toBeFalsy();284    });285    it('ignores missed blocks', () => {286      ngMocks.flushTestBed();287      const loFixture = MockRender(TemplateOutletComponent);288      const loComponent: any = loFixture.point.componentInstance;289      if (isMockOf(loComponent, TemplateOutletComponent, 'c')) {290        expect(() => loComponent.__hide('empty')).not.toThrow();291        expect(() => loComponent.__render('empty')).not.toThrow();292      } else {293        fail('the component is not replaced with its mock copy');294      }295    });296    it('renders nothing if no @ContentChild in component and ng-content is empty', () => {297      fixture.detectChanges();298      // a mock component was created without errors.299      const templateOutlet = fixture.debugElement.query(300        By.css('#element-without-content-and-template'),301      );302      expect(templateOutlet).toBeTruthy();303      expect(templateOutlet.nativeElement.innerHTML).toBeFalsy();304    });305    it('renders ng-content without wrapper if no @ContentChild in component', () => {306      fixture.detectChanges();307      // a mock component was created without errors.308      const templateOutlet = fixture.debugElement.query(309        By.css('#element-with-content-only'),310      );311      expect(templateOutlet).toBeTruthy();312      // content has right value313      expect(templateOutlet.nativeElement.innerHTML.trim()).toEqual(314        'child of element-with-content-only',315      );316    });317  });318  it('A9 correct mocking of ContentChild, ContentChildren, ViewChild, ViewChildren ISSUE #109', () => {319    @Component({320      template: '',321    })322    class MyComponent {323      @ContentChild('i1', { read: TemplateRef } as any)324      public o1?: TemplateRef<any>;325      @ContentChildren('i2', { read: TemplateRef } as any)326      public o2?: QueryList<TemplateRef<any>>;327      @ViewChild('i3', { read: TemplateRef } as any)328      public o3?: TemplateRef<any>;329      @ViewChildren('i4', { read: TemplateRef } as any)330      public o4?: QueryList<TemplateRef<any>>;331      @ContentChild('i5', { read: ElementRef } as any)332      public o5?: ElementRef;333      @ContentChildren('i6', { read: ElementRef } as any)334      public o6?: QueryList<ElementRef>;335      @ViewChild('i7', { read: ElementRef } as any)336      public o7?: ElementRef;337      @ViewChildren('i8', { read: ElementRef } as any)338      public o8?: QueryList<ElementRef>;339    }340    const actual = MockComponent(MyComponent) as any;341    expect(actual.__prop__metadata__).toEqual({342      o1: [343        jasmine.objectContaining({344          selector: 'i1',345          isViewQuery: false,346          read: TemplateRef,347          ngMetadataName: 'ContentChild',348        }),349      ],350      o2: [351        jasmine.objectContaining({352          selector: 'i2',353          isViewQuery: false,354          read: TemplateRef,355          ngMetadataName: 'ContentChildren',356        }),357      ],358      o3: [359        jasmine.objectContaining({360          selector: 'i3',361          isViewQuery: true,362          read: TemplateRef,363          ngMetadataName: 'ViewChild',364        }),365      ],366      o4: [367        jasmine.objectContaining({368          selector: 'i4',369          isViewQuery: true,370          read: TemplateRef,371          ngMetadataName: 'ViewChildren',372        }),373      ],374      o5: [375        jasmine.objectContaining({376          selector: 'i5',377          isViewQuery: false,378          read: ElementRef,379          ngMetadataName: 'ContentChild',380        }),381      ],382      o6: [383        jasmine.objectContaining({384          selector: 'i6',385          isViewQuery: false,386          read: ElementRef,387          ngMetadataName: 'ContentChildren',388        }),389      ],390      o7: [391        jasmine.objectContaining({392          selector: 'i7',393          isViewQuery: true,394          read: ElementRef,395          ngMetadataName: 'ViewChild',396        }),397      ],398      o8: [399        jasmine.objectContaining({400          selector: 'i8',401          isViewQuery: true,402          read: ElementRef,403          ngMetadataName: 'ViewChildren',404        }),405      ],406      __ngMocksVcr_o1: [407        jasmine.objectContaining({408          selector: 'i1',409          isViewQuery: false,410          read: ViewContainerRef,411          ngMetadataName: 'ContentChild',412        }),413      ],414      __ngMocksVcr_o2: [415        jasmine.objectContaining({416          selector: 'i2',417          isViewQuery: false,418          read: ViewContainerRef,419          ngMetadataName: 'ContentChildren',420        }),421      ],422      __ngMocksVcr_o5: [423        jasmine.objectContaining({424          selector: 'i5',425          isViewQuery: false,426          read: ViewContainerRef,427          ngMetadataName: 'ContentChild',428        }),429      ],430      __ngMocksVcr_o6: [431        jasmine.objectContaining({432          selector: 'i6',433          isViewQuery: false,434          read: ViewContainerRef,435          ngMetadataName: 'ContentChildren',436        }),437      ],438      __mockView_key_i1: [439        jasmine.objectContaining({440          selector: 'key_i1',441          isViewQuery: true,442          static: false,443          ngMetadataName: 'ViewChild',444        }),445      ],446      __mockTpl_key_i1: [447        jasmine.objectContaining({448          selector: 'i1',449          isViewQuery: false,450          ngMetadataName: 'ContentChild',451        }),452      ],453      __mockView_prop_o1: [454        jasmine.objectContaining({455          selector: 'prop_o1',456          isViewQuery: true,457          static: false,458          ngMetadataName: 'ViewChild',459        }),460      ],461      __mockView_key_i2: [462        jasmine.objectContaining({463          selector: 'key_i2',464          isViewQuery: true,465          static: false,466          ngMetadataName: 'ViewChild',467        }),468      ],469      __mockTpl_key_i2: [470        jasmine.objectContaining({471          selector: 'i2',472          isViewQuery: false,473          ngMetadataName: 'ContentChildren',474        }),475      ],476      __mockView_prop_o2: [477        jasmine.objectContaining({478          selector: 'prop_o2',479          isViewQuery: true,480          static: false,481          ngMetadataName: 'ViewChild',482        }),483      ],484    });485  });...test.spec.ts
Source:test.spec.ts  
1import { CommonModule } from '@angular/common';2import {3  Component,4  ContentChild,5  ContentChildren,6  Directive,7  InjectionToken,8  Input,9  NgModule,10  Pipe,11  PipeTransform,12  QueryList,13  TemplateRef,14} from '@angular/core';15import { ComponentFixture } from '@angular/core/testing';16import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';17const TOKEN = new InjectionToken('TOKEN');18@Pipe({19  name: 'pure',20})21class PurePipe implements PipeTransform {22  public value: any;23  public transform(value: any): any {24    this.value = value;25    return value;26  }27}28@Pipe({29  name: 'impure',30  pure: false,31})32class ImpurePipe implements PipeTransform {33  public value: any;34  public transform(value: any): any {35    this.value = value;36    return value;37  }38}39@Directive({40  providers: [41    {42      provide: TOKEN,43      useValue: 'test',44    },45  ],46  selector: '[tpl]',47})48class TplDirective {49  @Input() public readonly data: any = null;50  @Input('tpl') public readonly name: string | null = null;51  public constructor(public readonly tpl: TemplateRef<any>) {}52}53@Directive({54  providers: [55    {56      provide: TOKEN,57      useValue: 'test',58    },59  ],60  selector: '[tpl2]',61})62class Tpl2Directive {63  @Input('tpl') public readonly name: string | null = null;64  public constructor(public readonly tpl?: TemplateRef<any>) {}65}66@Directive({67  providers: [68    {69      provide: TOKEN,70      useValue: 'test',71    },72  ],73  selector: '[block]',74})75class BlockDirective {76  @Input('block') public readonly name: string | null = null;77  @ContentChild(Tpl2Directive, {} as any)78  public readonly template?: QueryList<Tpl2Directive>;79  @ContentChildren(TplDirective)80  public readonly templates?: QueryList<TplDirective>;81}82@Component({83  providers: [84    {85      provide: TOKEN,86      useValue: 'test',87    },88  ],89  selector: 'mock',90  template: '',91})92class MockComponent {93  @ContentChildren(BlockDirective)94  public blocks?: QueryList<BlockDirective>;95}96@NgModule({97  declarations: [98    MockComponent,99    BlockDirective,100    TplDirective,101    Tpl2Directive,102    PurePipe,103    ImpurePipe,104  ],105  imports: [CommonModule],106  providers: [107    {108      provide: TOKEN,109      useValue: 'test',110    },111  ],112})113class TargetModule {}114describe('ng-mocks-reveal:test', () => {115  let fixture: ComponentFixture<any>;116  const data = {117    value: Math.random(),118  };119  beforeEach(() =>120    MockBuilder(null, TargetModule)121      .mock(PurePipe, v => v)122      .mock(ImpurePipe, v => v),123  );124  beforeEach(125    () =>126      (fixture = MockRender(127        `128      1-{{ echo | pure | impure }}129      <mock>130        <!-- fun --> 2 <!-- fun -->131        <ng-container block="1">132          3-{{ echo | impure | pure }}133          <ng-template tpl="header" [data]="data">rendered-header-1</ng-template>134          <!-- fun --> 4 <!-- fun -->135          <ng-template tpl2>rendered-1</ng-template>136          5-{{ echo | pure }}137          <ng-template tpl="footer" tpl2>rendered-footer-1</ng-template>138          <!-- fun --> 6 <!-- fun -->139        </ng-container>140        7-{{ echo | impure }}141        <div #div>142          <!-- fun --> 8 <!-- fun -->143          <span tpl2>hello</span>144          9-{{ echo }}145        </div>146        <!-- fun --> 10 <!-- fun -->147        <ng-container block="2">148          11-{{ echo | pure | impure }}149          <ng-template [tpl]="'header'">rendered-header-2</ng-template>150          <!-- fun --> 12 <!-- fun -->151          <ng-template tpl2>rendered-2</ng-template>152          13-{{ echo }}153          <ng-template [tpl]="'footer'" [data]="data">rendered-footer-2</ng-template>154          <!-- fun --> 14 <!-- fun -->155        </ng-container>156        15-{{ echo }}157      </mock>158      <!-- fun --> 16 <!-- fun -->159    `,160        { data, echo: 'A', tag: 'span' },161      )),162  );163  it('crawls blocks, templates and directives', () => {164    const el = ngMocks.reveal(MockComponent);165    expect(el).toBeDefined();166    expect(ngMocks.formatHtml(el)).toEqual(167      '2 3-A 4 5-A 6 7-A <div> 8 <span tpl2="">hello</span> 9-A </div> 10 11-A 12 13-A 14 15-A',168    );169    {170      expect(ngMocks.reveal(fixture, MockComponent)).toBe(el);171      expect(172        ngMocks.reveal(fixture.debugElement, MockComponent),173      ).toBe(el);174      expect(ngMocks.reveal('mock')).toBe(el);175      expect(ngMocks.reveal(fixture, 'mock')).toBe(el);176      expect(ngMocks.reveal(fixture.debugElement, 'mock')).toBe(el);177    }178    {179      const elSet = ngMocks.revealAll(MockComponent);180      expect(elSet.length).toEqual(1);181      expect(elSet[0]).toBe(el);182    }183    {184      const elSet = ngMocks.revealAll(fixture, MockComponent);185      expect(elSet.length).toEqual(1);186      expect(elSet[0]).toBe(el);187    }188    {189      const elSet = ngMocks.revealAll(190        fixture.debugElement,191        MockComponent,192      );193      expect(elSet.length).toEqual(1);194      expect(elSet[0]).toBe(el);195    }196    {197      const elSet = ngMocks.revealAll('mock');198      expect(elSet.length).toEqual(1);199      expect(elSet[0]).toBe(el);200    }201    {202      const elSet = ngMocks.revealAll(fixture, 'mock');203      expect(elSet.length).toEqual(1);204      expect(elSet[0]).toBe(el);205    }206    {207      const elSet = ngMocks.revealAll(fixture.debugElement, 'mock');208      expect(elSet.length).toEqual(1);209      expect(elSet[0]).toBe(el);210    }211    const div = ngMocks.reveal(el, '#div');212    expect(div).toBeDefined();213    expect(ngMocks.formatHtml(div)).toEqual(214      '8 <span tpl2="">hello</span> 9-A',215    );216    {217      const divSet = ngMocks.revealAll(el, '#div');218      expect(divSet.length).toEqual(1);219      expect(divSet[0]).toBe(div);220    }221    const tpl2 = ngMocks.reveal(div, Tpl2Directive);222    expect(tpl2).toBeDefined();223    {224      const tpl2Set = ngMocks.revealAll(div, Tpl2Directive);225      expect(tpl2Set.length).toEqual(1);226      expect(tpl2Set[0]).toBe(tpl2);227    }228    {229      // it is a tag name selector230      const tpl2Set = ngMocks.revealAll(div, 'tpl2');231      expect(tpl2Set.length).toEqual(0);232    }233    {234      // it is an attribute selector235      const tpl2Set = ngMocks.revealAll(div, ['tpl2']);236      expect(tpl2Set.length).toEqual(1);237      expect(tpl2Set[0]).toBe(tpl2);238    }239    {240      // it is an input selector, fails because there not an input.241      const tpl2Set = ngMocks.revealAll(div, ['tpl2', '']);242      expect(tpl2Set.length).toEqual(0);243    }244    {245      expect(ngMocks.revealAll(Tpl2Directive).length).toEqual(4);246      expect(ngMocks.revealAll(['tpl2']).length).toEqual(4);247    }248    const blocks = ngMocks.revealAll(el, ['block']);249    expect(blocks.length).toEqual(2);250    const [block1, block2] = blocks;251    expect(block1.injector.get(BlockDirective).name).toEqual('1');252    expect(block2.injector.get(BlockDirective).name).toEqual('2');253    {254      expect(ngMocks.revealAll(block1, ['tpl2']).length).toEqual(2);255      expect(ngMocks.revealAll(block2, Tpl2Directive).length).toEqual(256        1,257      );258    }259    {260      const header = ngMocks.reveal(block1, ['tpl', 'header']);261      expect(header.injector.get(TplDirective).name).toEqual(262        'header',263      );264      expect(header.injector.get(TplDirective).data).toBe(data);265      expect(() => footer.injector.get(Tpl2Directive)).toThrow();266      const footer = ngMocks.reveal(block1, ['tpl', 'footer']);267      expect(footer.injector.get(TplDirective).name).toEqual(268        'footer',269      );270      expect(footer.injector.get(TplDirective).data).toBeUndefined();271      expect(() => footer.injector.get(Tpl2Directive)).not.toThrow();272      const templates = ngMocks.revealAll(block1, ['tpl']);273      expect(templates.length).toEqual(2);274      expect(templates[0]).toBe(header);275      expect(templates[1]).toBe(footer);276    }277    {278      const header = ngMocks.reveal(block2, ['tpl', 'header']);279      expect(header.injector.get(TplDirective).name).toEqual(280        'header',281      );282      expect(header.injector.get(TplDirective).data).toBeUndefined();283      expect(() => footer.injector.get(Tpl2Directive)).toThrow();284      const footer = ngMocks.reveal(block2, ['tpl', 'footer']);285      expect(footer.injector.get(TplDirective).name).toEqual(286        'footer',287      );288      expect(footer.injector.get(TplDirective).data).toBe(data);289      expect(() => footer.injector.get(Tpl2Directive)).toThrow();290      const templates = ngMocks.revealAll(block2, TplDirective);291      expect(templates.length).toEqual(2);292      expect(templates[0]).toBe(header);293      expect(templates[1]).toBe(footer);294    }295    expect(ngMocks.formatHtml(el)).toContain('3-A 4');296    ngMocks.render(297      el.componentInstance,298      ngMocks.findTemplateRef(block1, ['tpl', 'header']),299    );300    expect(ngMocks.formatHtml(el)).toContain(301      '3-A rendered-header-1 4',302    );303    expect(ngMocks.formatHtml(el)).toContain('5-A 6');304    ngMocks.render(305      el.componentInstance,306      ngMocks.findTemplateRef(block1, ['tpl', 'footer']),307    );308    expect(ngMocks.formatHtml(el)).toContain(309      '5-A rendered-footer-1 6',310    );311    expect(ngMocks.formatHtml(el)).toContain('4 5-A');312    ngMocks.render(313      el.componentInstance,314      ngMocks.findTemplateRef(block1, Tpl2Directive),315    );316    expect(ngMocks.formatHtml(el)).toContain('4 rendered-1 5-A');317    expect(ngMocks.formatHtml(el)).toContain('11-A 12');318    ngMocks.render(319      el.componentInstance,320      ngMocks.findTemplateRef(block2, ['tpl', 'header']),321    );322    expect(ngMocks.formatHtml(el)).toContain(323      '11-A rendered-header-2 12',324    );325    expect(ngMocks.formatHtml(el)).toContain('13-A 14');326    ngMocks.render(327      el.componentInstance,328      ngMocks.findTemplateRef(block2, ['tpl', 'footer']),329    );330    expect(ngMocks.formatHtml(el)).toContain(331      '13-A rendered-footer-2 14',332    );333    expect(ngMocks.formatHtml(el)).toContain('12 13-A');334    ngMocks.render(335      el.componentInstance,336      ngMocks.findTemplateRef(block2, Tpl2Directive),337    );338    expect(ngMocks.formatHtml(el)).toContain('12 rendered-2 13-A');339  });340  it('throws on unknown selectors', () => {341    expect(() => ngMocks.reveal(5 as any)).toThrowError(342      'Unknown selector',343    );344    expect(() => ngMocks.revealAll({} as any)).toThrowError(345      'Unknown selector',346    );347  });348  it('throws on unknown elements', () => {349    expect(() => ngMocks.reveal('unknown')).toThrowError(350      'Cannot find a DebugElement via ngMocks.reveal(unknown)',351    );352  });353  it('returns default value on missed values selectors', () => {354    const defaultValue = {};355    expect(ngMocks.reveal('unknown', defaultValue)).toBe(356      defaultValue,357    );358  });359  it('skips itself', () => {360    ngMocks.flushTestBed();361    const loFixture = MockRender(`362      <ng-container block="1">363        <ng-container block="2">364          <ng-container block="3"></ng-container>365        </ng-container>366      </ng-container>367    `);368    const block1El = ngMocks.reveal(loFixture, BlockDirective);369    const block1 = ngMocks.get(block1El, BlockDirective);370    expect(block1.name).toEqual('1');371    const block2El = ngMocks.reveal(block1El, BlockDirective);372    const block2 = ngMocks.get(block2El, BlockDirective);373    expect(block2.name).toEqual('2');374    const block3El = ngMocks.reveal(block2El, BlockDirective);375    const block3 = ngMocks.get(block3El, BlockDirective);376    expect(block3.name).toEqual('3');377    expect(() =>378      ngMocks.reveal(block3El, BlockDirective),379    ).toThrowError(380      'Cannot find a DebugElement via ngMocks.reveal(BlockDirective)',381    );382    {383      const blocks = ngMocks.revealAll(loFixture, BlockDirective);384      expect(blocks.length).toEqual(3);385      expect(blocks[0]).toBe(block1El);386      expect(blocks[1]).toBe(block2El);387      expect(blocks[2]).toBe(block3El);388    }389    {390      const blocks = ngMocks.revealAll(block1El, BlockDirective);391      expect(blocks.length).toEqual(2);392      expect(blocks[0]).toBe(block2El);393      expect(blocks[1]).toBe(block3El);394    }395    {396      const blocks = ngMocks.revealAll(block2El, BlockDirective);397      expect(blocks.length).toEqual(1);398      expect(blocks[0]).toBe(block3El);399    }400    {401      const blocks = ngMocks.revealAll(block3El, BlockDirective);402      expect(blocks.length).toEqual(0);403    }404  });...Using AI Code Generation
1import { loFixture } from 'ng-mocks';2import { TestComponent } from './test.component';3describe('TestComponent', () => {4  it('should create', () => {5    const component = loFixture(TestComponent);6    expect(component).toBeTruthy();7  });8});9import { Component, OnInit } from '@angular/core';10@Component({11})12export class TestComponent implements OnInit {13  constructor() { }14  ngOnInit() {15  }16}Using AI Code Generation
1import { loFixture } from 'ng-mocks';2describe('TestComponent', () => {3  it('should create', () => {4    const component = loFixture(TestComponent);5    expect(component).toBeTruthy();6  });7});8import { Component } from '@angular/core';9@Component({10})11export class TestComponent {}12import { ComponentFixture, TestBed } from '@angular/core/testing';13import { TestComponent } from './test.component';14describe('TestComponent', () => {15  let component: TestComponent;16  let fixture: ComponentFixture<TestComponent>;17  beforeEach(async () => {18    await TestBed.configureTestingModule({19    }).compileComponents();20  });21  beforeEach(() => {22    fixture = TestBed.createComponent(TestComponent);23    component = fixture.componentInstance;24    fixture.detectChanges();25  });26  it('should create', () => {27    expect(component).toBeTruthy();28  });29});30import { ComponentFixture, TestBed } from '@angular/core/testing';31import { TestComponent } from './test.component';32describe('TestComponent', () => {33  let component: TestComponent;34  let fixture: ComponentFixture<TestComponent>;35  beforeEach(async () => {36    await TestBed.configureTestingModule({37    }).compileComponents();38  });39  beforeEach(() => {40    fixture = TestBed.createComponent(TestComponent);41    component = fixture.componentInstance;42    fixture.detectChanges();43  });44  it('should create', () => {45    expect(component).toBeTruthy();46  });47});48import { ComponentFixture, TestBed } from '@angular/core/testing';49import { TestComponent } from './test.component';50describe('TestComponent', () => {51  let component: TestComponent;52  let fixture: ComponentFixture<TestComponent>;53  beforeEach(async () => {54    await TestBed.configureTestingModule({55    }).compileComponents();56  });57  beforeEach(() => {58    fixture = TestBed.createComponent(TestComponent);59    component = fixture.componentInstance;60    fixture.detectChanges();61  });62  it('should create', () => {63    expect(component).toBeTruthy();64  });65});Using AI Code Generation
1describe('my test', function() {2    var $scope;3    beforeEach(module('myApp'));4    beforeEach(inject(function($rootScope, $controller) {5        $scope = $rootScope.$new();6        $controller('myController', {$scope: $scope});7    }));8    it('should test myController', function() {9        var myController = $scope.myController;10        expect(myController).toBeDefined();11        expect(myController.myMethod).toBeDefined();12        expect(myController.myMethod()).toEqual(123);13    });14});15angular.module('myApp').controller('myController', function($scope) {16    $scope.myController = {17        myMethod: function() {18            return 123;19        }20    };21});22describe('my test', function() {23    var $scope;24    beforeEach(module('myApp'));25    beforeEach(inject(function($rootScope, $controller) {26        $scope = $rootScope.$new();27        $controller('myController', {$scope: $scope});28    }));29    it('should test $scope', function() {30        expect($scope).toBeDefined();31        expect($scope.myMethod).toBeDefined();32        expect($scope.myMethod()).toEqual(123);33    });34});35angular.module('myApp').controller('myController', function($scope) {36    $scope.myMethod = function() {37        return 123;38    };39});Using AI Code Generation
1import { loFixture } from 'ng-mocks';2import { MyComponent } from './my.component';3import { MyModule } from './my.module';4describe('MyComponent', () => {5  const fixture = loFixture(MyComponent, MyModule);6  const component = fixture.componentInstance;7  it('should create', () => {8    expect(component).toBeTruthy();9  });10});Using AI Code Generation
1describe('test', () => {2  beforeEach(() => {3    TestBed.configureTestingModule({4        {5          useValue: loFixture(TestService)6        }7    });8  });9});10describe('TestComponent', () => {11  beforeEach(() => {12    TestBed.configureTestingModule({13        {14          useValue: loFixture(TestService)15        }16    });17  });18});19describe('TestService', () => {20  beforeEach(() => {21    TestBed.configureTestingModule({22        {23          useValue: loFixture(TestService)24        }25    });26  });27});28export class TestComponent implements OnInit {29  constructor(private testService: TestService) {}30  ngOnInit() {31    this.testService.testMethod();32  }33}34@Injectable()35export class TestService {36  testMethod() {37    console.log('test');38  }39}40describe('TestComponent', () => {41  beforeEach(() => {42    TestBed.configureTestingModule({43        {44          useValue: loFixture(TestService)45        }46    });47  });48  it('should create', () => {49    const fixture = TestBed.createComponent(TestComponent);50    const comp = fixture.componentInstance;51    expect(comp).toBeTruthy();52  });53});54describe('TestService', () => {55  beforeEach(() => {56    TestBed.configureTestingModule({57        {58          useValue: loFixture(TestService)59        }60    });61  });62  it('should create', () => {63    const fixture = TestBed.createComponent(TestComponent);64    const comp = fixture.componentInstance;65    expect(compUsing AI Code Generation
1import { loFixture } from 'ng-mocks';2import { MyComponent } from './my.component';3describe('MyComponent', () => {4  it('should show the title', () => {5    const component = loFixture(MyComponent);6    expect(component.nativeElement.innerHTML).toContain('Hello World');7  });8});Using AI Code Generation
1import {loFixture} from 'ng-mocks';2const fixture = loFixture({3});4import {loFixture} from 'ng-mocks';5const fixture = loFixture({6});Using AI Code Generation
1describe('Test', () => {2  beforeEach(() => {3    const fixture = loFixture(TestComponent);4    const component = fixture.componentInstance;5    const element = fixture.nativeElement;6  });7});8imports9describe('Test', () => {10  beforeEach(() => {11    const fixture = loFixture(TestComponent, {12      imports: [HttpClientModule],13    }, (fixture, component) => {14    });15    const component = fixture.componentInstance;16    const element = fixture.nativeElement;17  });18});Using AI Code Generation
1import { loFixture } from 'ng-mocks';2const fixture = loFixture({3  inputs: {4  },5  outputs: {6    action: () => console.log('Action!')7  }8});9const component = fixture.componentInstance;10const element = fixture.nativeElement;11const debugElement = fixture.debugElement;12const service = fixture.debugElement.injector.get(MyService);13const template = fixture.debugElement.nativeElement;Using AI Code Generation
1describe("MyController", function () {2  beforeEach(function () {3    module('myModule');4    loFixture.load('myController.html');5  });6});7angular.module('myModule', [])8  .controller('MyController', function ($scope) {9    $scope.myId = 'myId';10    $scope.mySpan = 'mySpan';11  });12describe("MyController", function () {13  beforeEach(function () {14    module('myModule');15    loFixture.load('myController.html');16  });17  it("should have a span with text Hello World", function () {18    inject(function ($controller, $rootScope) {19      var scope = $rootScope.$new();20      var ctrl = $controller('MyController', {$scope: scope});21      ctrl.init();22      expect(scope.myId).toBe('myId');23      expect(scope.mySpan).toBe('mySpan');24    });25  });26});27angular.module('myModule', [])28  .controller('MyController', function ($scope) {29    $scope.myId = 'myId';30    $scope.mySpan = 'mySpan';31  });32describe("MyController", function () {33  beforeEach(function () {34    module('myModule');35    loFixture.load('myController.html');36  });37  it("should have a span with text Hello World", function () {38    inject(function ($controller, $rootScope) {39      var scope = $rootScope.$new();40      var ctrl = $controller('MyController', {$scope: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!!
