Best JavaScript code snippet using ng-mocks
component.spec.ts
Source:component.spec.ts  
1import { CommonModule } from '@angular/common';2import {3  Component,4  ContentChild,5  ContentChildren,6  Directive,7  Input,8  NgModule,9  QueryList,10  TemplateRef,11} from '@angular/core';12import { isMockOf, MockBuilder, MockRender, ngMocks } from 'ng-mocks';13@Directive({14  selector: '[tpl1]',15})16class Mock1Directive {17  @Input('tpl1') public readonly name: string | null = null;18  public constructor(public readonly tpl: TemplateRef<any>) {}19}20@Directive({21  selector: '[tpl2]',22})23class Mock2Directive {24  @Input('tpl2') public readonly name: string | null = null;25  public constructor(public readonly tpl: TemplateRef<any>) {}26}27@Directive({28  selector: '[tpl3]',29})30class Mock3Directive {31  @Input('tpl3') public readonly name: string | null = null;32  @ContentChild('info', {} as any)33  public readonly tpl?: TemplateRef<any>;34}35@Component({36  selector: 'component',37  template: `38    <div data-role="header" *ngIf="header">39      <ng-container *ngTemplateOutlet="header"></ng-container>40    </div>41    <div data-role="info" *ngIf="info">42      <ng-container43        *ngTemplateOutlet="44          info.tpl;45          context: { $implicit: info.name }46        "47      ></ng-container>48    </div>49    <div data-role="templates" *ngIf="templates">50      <ng-container *ngFor="let template of templates">51        <ng-container52          *ngTemplateOutlet="53            template;54            context: { $implicit: 'template' }55          "56        ></ng-container>57      </ng-container>58    </div>59    <div data-role="directives" *ngIf="directives">60      <ng-container *ngFor="let directive of directives">61        <ng-container62          *ngTemplateOutlet="63            directive.tpl;64            context: { $implicit: directive.name }65          "66        ></ng-container>67      </ng-container>68    </div>69  `,70})71class MockComponent {72  @ContentChildren(Mock2Directive, {} as any)73  public readonly directives?: QueryList<Mock2Directive>;74  @ContentChild('header', {} as any)75  public readonly header?: TemplateRef<any>;76  @ContentChild(Mock3Directive, {} as any)77  public readonly info?: Mock3Directive;78  @ContentChildren(Mock1Directive, {79    read: TemplateRef,80  } as any)81  public readonly templates?: QueryList<TemplateRef<any>>;82}83@Component({84  selector: 'target',85  template: `86    <component>87      :step:1:88      <ng-template #header>rendered-header</ng-template>89      :step:2:90      <ng-template tpl1="tpl1" let-param91        >rendered-tpl1-1-{{ param }}</ng-template92      >93      :step:3:94      <div *tpl1="'tpl2'; let param">rendered-tpl1-2-{{ param }}</div>95      :step:4:96      <ng-template tpl2="tpl1" let-param97        >rendered-tpl2-1-{{ param }}</ng-template98      >99      :step:5:100      <div *tpl2="'tpl2'; let param">rendered-tpl2-2-{{ param }}</div>101      :step:6:102      <div tpl3="info">103        :step:7:104        <ng-template #info let-param105          >rendered-info-{{ param }}</ng-template106        >107        :step:8:108      </div>109      :step:9:110    </component>111  `,112})113class TargetComponent {}114@NgModule({115  declarations: [116    Mock1Directive,117    Mock2Directive,118    Mock3Directive,119    MockComponent,120    TargetComponent,121  ],122  imports: [CommonModule],123})124class TargetModule {}125// fix for jest without jasmine assertions126const assertion: any =127  typeof jasmine === 'undefined' ? expect : jasmine;128describe('ng-mocks-render:component:real', () => {129  beforeEach(() => MockBuilder(TargetComponent).keep(TargetModule));130  it('renders templates properly', () => {131    const fixture = MockRender(TargetComponent);132    const html = ngMocks.formatHtml(fixture.nativeElement);133    expect(html).not.toContain(':step:');134    expect(html).toContain('rendered-header');135    expect(html).toContain('rendered-info-info');136    expect(html).toContain('rendered-tpl1-1-template');137    expect(html).toContain('rendered-tpl1-2-template');138    expect(html).toContain('rendered-tpl2-1-tpl1');139    expect(html).toContain('rendered-tpl2-2-tpl2');140  });141});142describe('ng-mocks-render:component:mock', () => {143  beforeEach(() => MockBuilder(TargetComponent, TargetModule));144  it('renders directives on their positions', () => {145    let html = '';146    const fixture = MockRender(TargetComponent);147    html = ngMocks.formatHtml(fixture.nativeElement);148    expect(html).toContain(':step:2: :step:3: :step:4:');149    for (const directive of ngMocks.findInstances(Mock1Directive)) {150      if (isMockOf(directive, Mock1Directive, 'd')) {151        directive.__render('mock');152      }153    }154    html = ngMocks.formatHtml(fixture.nativeElement);155    expect(html).toContain(156      ':step:2: rendered-tpl1-1-mock :step:3: <div>rendered-tpl1-2-mock</div> :step:4:',157    );158  });159  it('renders queries of components in the end', () => {160    let html = '';161    const fixture = MockRender(TargetComponent);162    html = ngMocks.formatHtml(fixture.nativeElement);163    expect(html).toContain(':step:1: :step:2:');164    const component = ngMocks.findInstance(MockComponent);165    if (isMockOf(component, MockComponent, 'c')) {166      component.__render('header');167      component.__render(['templates'], ':templates:');168    }169    html = ngMocks.formatHtml(fixture.nativeElement);170    // component renders own queries in the end of own template.171    expect(html).toContain(':step:1: :step:2:');172    expect(html).toContain(173      ':step:9: ' +174        '<div data-key="header">rendered-header</div>' +175        '<div data-prop="templates">' +176        'rendered-tpl1-1-:templates:' +177        '<div>rendered-tpl1-2-:templates:</div>' +178        '</div>',179    );180  });181  it('renders all desired templates', () => {182    let html = '';183    const fixture = MockRender(TargetComponent);184    const tplHeader = ngMocks.findTemplateRef('header');185    const tpl1tpl1 = ngMocks.findTemplateRef(['tpl1', 'tpl1']);186    const tpl1tpl2 = ngMocks.findTemplateRef(['tpl1', 'tpl2']);187    const tpl2tpl1 = ngMocks.findTemplateRef(['tpl2', 'tpl1']);188    const tpl2tpl2 = ngMocks.findTemplateRef(['tpl2', 'tpl2']);189    const tpl3 = ngMocks.findTemplateRef('info');190    expect(tplHeader).toEqual(assertion.any(TemplateRef));191    expect(tpl1tpl1).toEqual(assertion.any(TemplateRef));192    expect(tpl1tpl2).toEqual(assertion.any(TemplateRef));193    expect(tpl2tpl1).toEqual(assertion.any(TemplateRef));194    expect(tpl2tpl2).toEqual(assertion.any(TemplateRef));195    expect(tpl3).toEqual(assertion.any(TemplateRef));196    // our render entrypoint component197    const component = ngMocks.findInstance(MockComponent);198    // render tplHeader199    html = ngMocks.formatHtml(fixture.nativeElement);200    expect(html).toContain(':step:1: :step:2:');201    ngMocks.render(component, tplHeader);202    html = ngMocks.formatHtml(fixture.nativeElement);203    expect(html).toContain(':step:1: rendered-header :step:2:');204    // render tpl1tpl1205    html = ngMocks.formatHtml(fixture.nativeElement);206    expect(html).toContain(':step:2: :step:3:');207    ngMocks.render(component, tpl1tpl1, 'tpl1tpl1');208    html = ngMocks.formatHtml(fixture.nativeElement);209    expect(html).toContain(210      ':step:2: rendered-tpl1-1-tpl1tpl1 :step:3:',211    );212    // render tpl1tpl2213    html = ngMocks.formatHtml(fixture.nativeElement);214    expect(html).toContain(':step:3: :step:4:');215    ngMocks.render(component, tpl1tpl2, 'tpl1tpl2');216    html = ngMocks.formatHtml(fixture.nativeElement);217    expect(html).toContain(218      ':step:3: <div>rendered-tpl1-2-tpl1tpl2</div> :step:4:',219    );220    // render tpl2tpl1221    html = ngMocks.formatHtml(fixture.nativeElement);222    expect(html).toContain(':step:4: :step:5:');223    ngMocks.render(component, tpl2tpl1, 'tpl2tpl1');224    html = ngMocks.formatHtml(fixture.nativeElement);225    expect(html).toContain(226      ':step:4: rendered-tpl2-1-tpl2tpl1 :step:5:',227    );228    // render tpl2tpl2229    html = ngMocks.formatHtml(fixture.nativeElement);230    expect(html).toContain(':step:5: :step:6:');231    ngMocks.render(component, tpl2tpl2, 'tpl2tpl2');232    html = ngMocks.formatHtml(fixture.nativeElement);233    expect(html).toContain(234      ':step:5: <div>rendered-tpl2-2-tpl2tpl2</div> :step:6:',235    );236    // render tpl3237    html = ngMocks.formatHtml(fixture.nativeElement);238    expect(html).toContain(':step:7: :step:8:');239    ngMocks.render(component, tpl3, 'tpl3');240    html = ngMocks.formatHtml(fixture.nativeElement);241    expect(html).toContain(':step:7: rendered-info-tpl3 :step:8:');242    // update tpl1tpl1 as directive243    const tpl1tpl1dir = ngMocks.findInstance(Mock1Directive);244    ngMocks.render(tpl1tpl1dir, tpl1tpl1dir, 'tpl1tpl1dir');245    html = ngMocks.formatHtml(fixture.nativeElement);246    expect(html).toContain(247      ':step:2: rendered-tpl1-1-tpl1tpl1dir :step:3:',248    );249    // update tpl3250    ngMocks.render(component, tpl3, 'tpl3-updated');251    html = ngMocks.formatHtml(fixture.nativeElement);252    expect(html).toContain(253      ':step:7: rendered-info-tpl3-updated :step:8:',254    );255    // hide tplHeader256    expect(html).not.toContain(':step:1: :step:2:');257    ngMocks.hide(component, tplHeader);258    html = ngMocks.formatHtml(fixture.nativeElement);259    expect(html).toContain(':step:1: :step:2:');260    // hide tpl1tpl1261    expect(html).not.toContain(':step:2: :step:3:');262    ngMocks.hide(component, tpl1tpl1);263    html = ngMocks.formatHtml(fixture.nativeElement);264    expect(html).toContain(':step:2: :step:3:');265    // hide tpl1tpl2266    const [, tpl1tpl2dir] = ngMocks.findInstances(Mock1Directive);267    expect(html).not.toContain(':step:3: :step:4:');268    ngMocks.hide(tpl1tpl2dir);269    html = ngMocks.formatHtml(fixture.nativeElement);270    expect(html).toContain(':step:3: :step:4:');271    // hide tpl2tpl1272    const [tpl2tpl1dir] = ngMocks.findInstances(Mock2Directive);273    expect(html).not.toContain(':step:4: :step:5:');274    ngMocks.hide(tpl2tpl1dir);275    html = ngMocks.formatHtml(fixture.nativeElement);276    expect(html).toContain(':step:4: :step:5:');277    // hide tpl2tpl2278    expect(html).not.toContain(':step:5: :step:6:');279    ngMocks.hide(280      component,281      ngMocks.findTemplateRef(['tpl2', 'tpl2']),282    );283    html = ngMocks.formatHtml(fixture.nativeElement);284    expect(html).toContain(':step:5: :step:6:');285    // hide tpl3286    expect(html).not.toContain(':step:7: :step:8:');287    ngMocks.hide(component, tpl3);288    html = ngMocks.formatHtml(fixture.nativeElement);289    expect(html).toContain(':step:7: :step:8:');290  });291  it('throws if not a mock instance has been passed', () => {292    MockRender(TargetComponent);293    const tpl = ngMocks.findTemplateRef('header');294    expect(() => ngMocks.render({}, tpl)).toThrowError(295      'Only instances of mock declarations are accepted',296    );297  });298  it('throws if TemplateRef cannot be found on render request', () => {299    MockRender(TargetComponent);300    const directive = ngMocks.findInstance(Mock3Directive);301    const tpl = ngMocks.findTemplateRef('header');302    expect(() => ngMocks.render(directive, tpl)).toThrowError(303      'Cannot find path to the TemplateRef',304    );305  });306  it('throws if no template has been passed on render request', () => {307    MockRender(TargetComponent);308    const directive = ngMocks.findInstance(Mock3Directive);309    expect(() =>310      ngMocks.render(directive, undefined as any),311    ).toThrowError(312      'Unknown template has been passed, only TemplateRef or a mock structural directive are supported',313    );314  });315  it('throws if TemplateRef cannot be found on hide request', () => {316    MockRender(TargetComponent);317    const directive = ngMocks.findInstance(Mock3Directive);318    const tpl = ngMocks.findTemplateRef('header');319    expect(() => ngMocks.hide(directive, tpl)).toThrowError(320      'Cannot find path to the TemplateRef',321    );322  });...Using AI Code Generation
1import { tpl2tpl2 } from 'ng-mocks';2import { AppComponent } from './app.component';3describe('AppComponent', () => {4  it('should create the app', () => {5    const fixture = tpl2tpl2(AppComponent);6    expect(fixture).toBeTruthy();7  });8});9import { Component } from '@angular/core';10@Component({11})12export class AppComponent {13  title = 'ng-mocks';14}15  Welcome to {{title}}!16h1 {17  color: #369;18  font-family: Arial, Helvetica, sans-serif;19  font-size: 250%;20}21import { TestBed } from '@angular/core/testing';22import { AppComponent } from './app.component';23describe('AppComponent', () => {24  beforeEach(async () => {25    await TestBed.configureTestingModule({26    }).compileComponents();27  });28  it('should create the app', () => {29    const fixture = TestBed.createComponent(AppComponent);30    const app = fixture.componentInstance;31    expect(app).toBeTruthy();32  });33  it(`should have as title 'ng-mocks'`, () => {34    const fixture = TestBed.createComponent(AppComponent);35    const app = fixture.componentInstance;36    expect(app.title).toEqual('ng-mocks');37  });38  it('should render title', () => {39    const fixture = TestBed.createComponent(AppComponent);40    fixture.detectChanges();41    const compiled = fixture.nativeElement;42    expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');43  });44});45module.exports = function (config) {46  config.set({47      require('karma-jasmine'),48      require('karma-chrome-launcher'),49      require('karma-jasmine-html-reporter'),50      require('karma-coverage-istanbul-reporter'),51      require('@angular-devkit/build-angular/plugins/karma')52    client: {53    },54    coverageIstanbulReporter: {55      dir: require('path').join(__dirname,Using AI Code Generation
1import { tpl2tpl2 } from 'ng-mocks';2import { tpl2tpl } from 'ng-mocks';3describe('tpl2tpl2', () => {4  it('should return a new template', () => {5    const actual = tpl2tpl2('<div>test</div>');6    expect(actual).toEqual('<div>test</div>');7  });8});9describe('tpl2tpl', () => {10  it('should return a new template', () => {11    const actual = tpl2tpl('<div>test</div>');12    expect(actual).toEqual('<div>test</div>');13  });14});15import 'ng-mocks/dist/ng-mocks';16import 'ng-mocks/dist/ng-mocks';17describe('tpl2tpl2', () => {18  it('should return a new template', () => {19    const actual = tpl2tpl2('<div>test</div>');20    expect(actual).toEqual('<div>test</div>');21  });22});23describe('tpl2tpl', () => {24  it('should return a new template', () => {25    const actual = tpl2tpl('<div>test</div>');26    expect(actual).toEqual('<div>test</div>');27  });28});29import { MockBuilder, MockRender, MockInstance } from 'ng-mocks';30import { MockBuilder, MockRender, MockInstance } from 'ng-mocks';31describe('tpl2tpl2', () => {32  beforeEach(() => MockBuilder().mock(TemplateRef));33  it('should return a new template', () => {34    const actual = tpl2tpl2('<div>test</div>');35    expect(actual).toEqual('<div>test</div>');36  });37});Using AI Code Generation
1import { tpl2tpl2 } from 'ng-mocks';2import { MyComponent } from './my.component';3import { MyModule } from './my.module';4describe('MyComponent', () => {5  it('should render', () => {6    const fixture = tpl2tpl2('<my-component></my-component>', {7      imports: [MyModule],8    });9    expect(fixture.nativeElement.innerHTML).toContain('Hello World');10  });11});12import { Component } from '@angular/core';13@Component({14})15export class MyComponent {}16import { NgModule } from '@angular/core';17import { MyComponent } from './my.component';18@NgModule({19})20export class MyModule {}21import { TestBed } from '@angular/core/testing';22import { MyComponent } from './my.component';23describe('MyComponent', () => {24  it('should render', () => {25    TestBed.configureTestingModule({26    }).compileComponents();27    const fixture = TestBed.createComponent(MyComponent);28    fixture.detectChanges();29    expect(fixture.nativeElement.innerHTML).toContain('Hello World');30  });31});Using AI Code Generation
1import { tpl2tpl2 } from 'ng-mocks';2import { MyComponent } from './my.component';3import { MyModule } from './my.module';4describe('MyComponent', () => {5  it('should render', () => {6    const fixture = tpl2tpl2('<my-component></my-component>', {7      imports: [MyModule],8    });9    expect(fixture.nativeElement.innerHTML).toContain('Hello World');10  });11});12import { ComponentFixture, TestBed } from '@angular/core/testing';13import { MyComponent } from './my.component';14describe('MyComponent', () => {15  let component: MyComponent;16  let fixture: ComponentFixture<MyComponent>;17  beforeEach(async () => {18    await TestBed.configureTestingModule({19    }).compileComponents();20  });21  beforeEach(() => {22    fixture = TestBed.createComponent(MyComponent);23    component = fixture.componentInstance;24    fixture.detectChanges();25  });26  it('should render', () => {27    expect(fixture.nativeElement.innerHTML).toContain('Hello World');28  });29});Using AI Code Generation
1import { tpl2tpl2 } from 'ng-mocks';2describe('test', () => {3  it('test', () => {4    `;5    const result = tpl2tpl2(template, {6      span: {7      },8    });9    expect(result).toEqual(`10    `);11  });12});13import { tpl2tpl2 } from 'ng-mocks';14describe('test', () => {15it('test', () => {16`;17const result = tpl2tpl2(template, {18span: {19},20});21expect(result).toEqual(`22`);23});24});25import { tpl2tpl2 } from 'ng-mocks';26describe('test', () => {27it('test', () => {28`;29const result = tpl2tpl2(template, {30span: {31},32});33expect(result).toEqual(`34`);35});36});37import { tpl2tpl2 } from 'ng-mocks';38describe('test', () => {39it('test', () => {40`;41const result = tpl2tpl2(template, {42span: {43},44});45expect(result).toEqual(`46`);47});48});49import { tpl2tpl2 } from 'ng-mocks';50describe('test', () => {51it('test', () => {52`;53const result = tpl2tpl2(template, {54span: {Using AI Code Generation
1import { MockBuilder, MockRender, MockInstance } from 'ng-mocks';2import { TestComponent } from './test.component';3import { TestModule } from './test.module';4MockInstance(TestComponent, 'tpl2', 'tpl2tpl2');5describe('TestComponent', () => {6  beforeEach(() => MockBuilder(TestComponent, TestModule));7  it('should create', () => {8    const fixture = MockRender(TestComponent);9    expect(fixture.point.componentInstance).toBeTruthy();10  });11});12import { Component } from '@angular/core';13@Component({14})15export class TestComponent {16  constructor() {}17}18import { NgModule } from '@angular/core';19import { CommonModule } from '@angular/common';20import { TestComponent } from './test.component';21@NgModule({22  imports: [CommonModule],23})24export class TestModule {}25import { MockBuilder, MockRender, MockInstance } from 'ng-mocks';26import { TestComponent } from './test.component';27import { TestModule } from './test.module';28describe('TestComponent', () => {29  beforeEach(() => MockBuilder(TestComponent, TestModule));30  it('should create', () => {31    const fixture = MockRender(TestComponent);32    expect(fixture.point.componentInstance).toBeTruthy();33  });34});35import { Component } from '@angular/core';36@Component({37})38export class TestComponent {39  constructor() {}40}41import { NgModule } from '@angular/core';42import { CommonModule } from '@angular/common';43import { TestComponent } from './test.component';44@NgModule({45  imports: [CommonModule],46})47export class TestModule {}48import { MockBuilder, MockRender, MockInstance } from 'ng-mocks';49import { TestUsing AI Code Generation
1var tpl2tpl2 = require('ng-mocks').tpl2tpl2;2var tpl = '<div>Hello World</div>';3tpl2tpl2(tpl).then(function (dom) {4  console.log(dom);5  done();6});7var tpl2tpl2 = require('ng-mocks').tpl2tpl2;8var tpl = '<div>Hello World</div>';9tpl2tpl2(tpl).then(function (dom) {10  console.log(dom);11  done();12});13var tpl2tpl2 = require('ng-mocks').tpl2tpl2;14var tpl = '<div>Hello World</div>';15tpl2tpl2(tpl).then(function (dom) {16  console.log(dom);17  done();18});19var tpl2tpl2 = require('ng-mocks').tpl2tpl2;20var tpl = '<div>Hello World</div>';21tpl2tpl2(tpl).then(function (dom) {22  console.log(dom);23  done();24});25var tpl2tpl2 = require('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!!
