Best JavaScript code snippet using ng-mocks
test.spec.ts
Source:test.spec.ts
1import { Component, Directive, forwardRef } from '@angular/core';2import { TestBed } from '@angular/core/testing';3import {4 AbstractControl,5 ControlValueAccessor,6 FormControl,7 NG_ASYNC_VALIDATORS,8 NG_VALIDATORS,9 NG_VALUE_ACCESSOR,10 ReactiveFormsModule,11 ValidationErrors,12 Validator,13} from '@angular/forms';14import {15 isMockControlValueAccessor,16 isMockValidator,17 MockBuilder,18 MockRender,19 ngMocks,20} from 'ng-mocks';21@Component({22 providers: [23 {24 multi: true,25 provide: NG_VALUE_ACCESSOR,26 useExisting: forwardRef(() => TargetComponent),27 },28 ],29 selector: 'target',30 template: '{{ providedValue }}',31})32class TargetComponent implements ControlValueAccessor {33 public providedChange: any;34 public providedDisable: any;35 public providedTouch: any;36 public providedValue: any;37 public registerOnChange(fn: any): void {38 this.providedChange = fn;39 }40 public registerOnTouched(fn: any): void {41 this.providedTouch = fn;42 }43 public setDisabledState(isDisabled: boolean): void {44 this.providedDisable = isDisabled;45 }46 public writeValue(obj: any): void {47 this.providedValue = obj;48 }49}50@Directive({51 providers: [52 {53 multi: true,54 provide: NG_VALIDATORS,55 useExisting: forwardRef(() => TargetDirective),56 },57 ],58 selector: '[target]',59})60class TargetDirective implements Validator {61 public provideChange: any;62 public provideControl: any;63 public registerOnValidatorChange(fn: () => void): void {64 this.provideChange = fn;65 }66 public validate(control: AbstractControl): ValidationErrors | null {67 this.provideControl = control;68 return {69 target: true,70 };71 }72}73@Directive({74 providers: [75 {76 multi: true,77 provide: NG_ASYNC_VALIDATORS,78 useExisting: forwardRef(() => TargetAsyncDirective),79 },80 ],81 selector: '[targetAsync]',82})83class TargetAsyncDirective implements Validator {84 public provideChange: any;85 public provideControl: any;86 public registerOnValidatorChange(fn: () => void): void {87 this.provideChange = fn;88 }89 public async validate(90 control: AbstractControl,91 ): Promise<ValidationErrors> {92 this.provideControl = control;93 return {94 targetAsync: true,95 };96 }97}98// @see https://github.com/help-me-mom/ng-mocks/issues/24699describe('issue-246:real', () => {100 beforeEach(async () => {101 return TestBed.configureTestingModule({102 declarations: [103 TargetComponent,104 TargetDirective,105 TargetAsyncDirective,106 ],107 imports: [ReactiveFormsModule],108 }).compileComponents();109 });110 it('turns value control accessor into auto mocks', async () => {111 const control = new FormControl('246');112 // default render.113 const fixture = MockRender(114 '<target [formControl]="control" target targetAsync></target>',115 {116 control,117 },118 );119 await fixture.whenStable();120 expect(control.touched).toEqual(false);121 expect(control.dirty).toEqual(false);122 expect(control.errors).toEqual({123 target: true,124 });125 // async fails independently only.126 ngMocks.stubMember(127 ngMocks.findInstance(TargetDirective),128 'validate',129 typeof jest === 'undefined'130 ? jasmine.createSpy().and.returnValue(null)131 : jest.fn().mockReturnValue(null),132 );133 control.updateValueAndValidity();134 await fixture.whenStable();135 expect(control.errors).toEqual({136 targetAsync: true,137 });138 });139});140// @see https://github.com/help-me-mom/ng-mocks/issues/246141describe('issue-246:mock', () => {142 beforeEach(() =>143 MockBuilder(ReactiveFormsModule)144 .mock(TargetComponent)145 .mock(TargetDirective)146 .mock(TargetAsyncDirective),147 );148 it('turns value control accessor into auto mocks', async () => {149 const control = new FormControl('246');150 // default render.151 const fixture = MockRender(152 '<target [formControl]="control" target targetAsync></target>',153 {154 control,155 },156 );157 expect(control.touched).toEqual(false);158 expect(control.dirty).toEqual(false);159 const component = ngMocks.findInstance(TargetComponent);160 expect(component.registerOnChange).toHaveBeenCalledTimes(1);161 expect(component.registerOnTouched).toHaveBeenCalledTimes(1);162 expect(component.writeValue).toHaveBeenCalledWith('246');163 expect(component.writeValue).toHaveBeenCalledTimes(1);164 const directive = ngMocks.findInstance(TargetDirective);165 expect(directive.registerOnValidatorChange).toHaveBeenCalledTimes(166 1,167 );168 expect(directive.validate).toHaveBeenCalledWith(control);169 expect(directive.validate).toHaveBeenCalledTimes(1);170 const directiveAsync = ngMocks.findInstance(TargetAsyncDirective);171 expect(172 directiveAsync.registerOnValidatorChange,173 ).toHaveBeenCalledTimes(1);174 expect(directiveAsync.validate).toHaveBeenCalledWith(control);175 expect(directiveAsync.validate).toHaveBeenCalledTimes(1);176 // checking that touch works.177 if (isMockControlValueAccessor(component)) {178 component.__simulateTouch();179 }180 expect(control.touched).toEqual(true);181 // checking that change works.182 if (isMockControlValueAccessor(component)) {183 component.__simulateChange('fixed');184 }185 expect(control.value).toEqual('fixed');186 // checking async errors.187 if (isMockValidator(directiveAsync)) {188 ngMocks.stubMember(189 directiveAsync,190 'validate',191 typeof jest === 'undefined'192 ? jasmine.createSpy().and.returnValue(193 Promise.resolve({194 targetAsync: true,195 }),196 )197 : jest.fn().mockReturnValue(198 Promise.resolve({199 targetAsync: true,200 }),201 ),202 );203 directiveAsync.__simulateValidatorChange();204 }205 await fixture.whenStable();206 expect(control.errors).toEqual({207 targetAsync: true,208 });209 // checking sync errors, they block async validators.210 if (isMockValidator(directive)) {211 ngMocks.stubMember(212 directive,213 'validate',214 typeof jest === 'undefined'215 ? jasmine.createSpy().and.returnValue({216 test: true,217 })218 : jest.fn().mockReturnValue({219 test: true,220 }),221 );222 directive.__simulateValidatorChange();223 }224 expect(control.errors).toEqual({225 test: true,226 });227 });...
Using AI Code Generation
1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2import { TestComponent } from './test.component';3describe('TestComponent', () => {4 beforeEach(() => MockBuilder(TestComponent));5 it('should create', () => {6 const fixture = MockRender(TestComponent);7 expect(ngMocks.formatHtml(fixture)).toMatchSnapshot();8 });9});
Using AI Code Generation
1import { directiveAsync } from 'ng-mocks';2import { MyComponent } from './my.component';3describe('MyComponent', () => {4 it('should create the component', async () => {5 const fixture = await directiveAsync(MyComponent);6 const component = fixture.componentInstance;7 expect(component).toBeTruthy();8 });9});10import { Component } from '@angular/core';11@Component({12})13export class MyComponent {}
Using AI Code Generation
1import { MockBuilder, MockInstance, MockRender, ngMocks } from 'ng-mocks';2import { MyComponent } from './my.component';3import { MyService } from './my.service';4describe('MyComponent', () => {5 beforeEach(() => MockBuilder(MyComponent).mock(MyService));6 it('renders the component', () => {7 const fixture = MockRender(MyComponent);8 const component = ngMocks.findInstance(MyComponent);9 expect(component).toBeDefined();10 expect(fixture.nativeElement.innerHTML).toContain('test');11 });12});13import { Injectable } from '@angular/core';14@Injectable()15export class MyService {16 getTest(): string {17 return 'test';18 }19}20import { Component } from '@angular/core';21import { MyService } from './my.service';22@Component({23 template: '{{test}}',24})25export class MyComponent {26 test: string;27 constructor(myService: MyService) {28 this.test = myService.getTest();29 }30}31import { MockBuilder, MockRender } from 'ng-mocks';32import { MyComponent } from './my.component';33import { MyService } from './my.service';34describe('MyComponent', () => {35 beforeEach(() => MockBuilder(MyComponent).mock(MyService));36 it('renders the component', () => {37 const fixture = MockRender(MyComponent);38 expect(fixture.nativeElement.innerHTML).toContain('test');39 });40});41import { Injectable } from '@angular/core';42@Injectable()43export class MyService {44 getTest(): string {45 return 'test';46 }47}48import { Component } from '@angular/core';49import { MyService } from './my.service';50@Component({51 template: '{{test}}',52})53export class MyComponent {54 test: string;55 constructor(myService: MyService) {56 this.test = myService.getTest();57 }58}59import { MockBuilder, MockRender } from 'ng-mocks';60import { MyComponent } from './my.component';61import { MyService } from './my.service';62describe('MyComponent', () => {63 beforeEach(() => MockBuilder(MyComponent).mock(MyService));64 it('renders the component', () =>
Using AI Code Generation
1import { directiveAsync } from 'ng-mocks';2describe('Directive: Test', () => {3 beforeEach(() => {4 TestBed.configureTestingModule({5 });6 });7 it('should create an instance', async () => {8 const fixture = await directiveAsync(TestDirective);9 expect(fixture).toBeTruthy();10 });11});12import { Directive, Input } from '@angular/core';13@Directive({14})15export class TestDirective {16 @Input() test: string;17}18import { TestDirective } from './test.directive';19describe('TestDirective', () => {20 it('should create an instance', () => {21 const directive = new TestDirective();22 expect(directive).toBeTruthy();23 });24});25import { TestBed } from '@angular/core/testing';26import { TestDirective } from './test.directive';27import { TestComponent } from './test.component';28describe('TestDirective', () => {29 beforeEach(() => {30 TestBed.configureTestingModule({31 });32 });33 it('should create an instance', () => {34 const fixture = TestBed.createComponent(TestComponent);35 expect(fixture).toBeTruthy();36 });37});38import { Component } from '@angular/core';39@Component({40})41export class TestComponent {42 test = 'test';43}44import { TestBed } from '@angular/core/testing';45import { TestComponent } from './test.component';46import { TestDirective } from './test.directive';47describe('TestComponent', () => {48 beforeEach(() => {49 TestBed.configureTestingModule({50 });51 });52 it('should create an instance', () => {53 const fixture = TestBed.createComponent(TestComponent);54 expect(fixture).toBeTruthy();55 });56});
Using AI Code Generation
1import { directiveAsync } from 'ng-mocks';2import { MyDirective } from './my-directive';3describe('MyDirective', () => {4 it('is async', () => {5 return directiveAsync(MyDirective).then(directive => {6 });7 });8});9import { TestBed } from '@angular/core/testing';10import { MockBuilder, MockRender, directiveAsync } from 'ng-mocks';11import { MyDirective } from './my-directive';12import { MyComponent } from './my-component';13describe('MyDirective', () => {14 beforeEach(() => MockBuilder(MyDirective).mock(MyComponent));15 it('is async', () => {16 return directiveAsync(MyDirective).then(directive => {17 });18 });19});20import { TestBed } from '@angular/core/testing';21import { MockBuilder, MockRender, directiveAsync } from 'ng-mocks';22import { MyDirective } from './my-directive';23import { MyComponent } from './my-component';24describe('MyDirective', () => {25 beforeEach(() => MockBuilder(MyDirective).mock(MyComponent));26 it('is async', () => {27 return directiveAsync(MyDirective).then(directive => {28 directive.detectChanges();29 });30 });31});32import { TestBed } from '@angular/core/testing';33import { MockBuilder, MockRender, directiveAsync } from 'ng-mocks';34import { MyDirective } from './my-directive';35import { MyComponent } from './my-component';36describe('MyDirective', () => {37 beforeEach(() => MockBuilder(MyDirective).mock(MyComponent));38 it('is async', () => {39 return directiveAsync(MyDirective, null, { test: 'test' }).then(directive => {40 directive.detectChanges();41 });42 });43});
Using AI Code Generation
1describe('my directive', () => {2 let fixture: ComponentFixture<MyComponent>;3 let context: MyComponent;4 let element: any;5 beforeEach(async(() => {6 return directiveAsync(MyComponent, MyDirective).then((f) => {7 fixture = f;8 context = fixture.componentInstance;9 element = fixture.nativeElement;10 });11 }));12 it('should do something', () => {13 });14});15describe('my directive', () => {16 let fixture: ComponentFixture<MyComponent>;17 let context: MyComponent;18 let element: any;19 beforeEach(async(() => {20 return directiveDef(MyComponent, MyDirective).then((f) => {21 fixture = f;22 context = fixture.componentInstance;23 element = fixture.nativeElement;24 });25 }));26 it('should do something', () => {27 });28});29describe('my directive', () => {30 let fixture: ComponentFixture<MyComponent>;31 let context: MyComponent;32 let element: any;33 beforeEach(async(() => {34 return directiveDefAsync(MyComponent, MyDirective).then((f) => {35 fixture = f;36 context = fixture.componentInstance;37 element = fixture.nativeElement;38 });39 }));40 it('should do something', () => {41 });42});43describe('my directive', () => {44 let fixture: ComponentFixture<MyComponent>;45 let context: MyComponent;46 let element: any;47 beforeEach(async(() => {48 return directiveHost(MyComponent, MyDirective).then((f) => {49 fixture = f;50 context = fixture.componentInstance;51 element = fixture.nativeElement;52 });53 }));54 it('should do something', () => {55 });56});
Using AI Code Generation
1var directiveAsync = ngMocks.directiveAsync;2describe('Directive: myDirective', function() {3 beforeEach(module('myApp'));4 it('should create the directive', directiveAsync('myDirective', {5 }, function() {6 }));7});
Using AI Code Generation
1import { directiveAsync } from 'ng-mocks';2import { MyDirective } from './my-directive';3it('should render async directive', async () => {4 const fixture = directiveAsync(MyDirective);5 const element = fixture.debugElement.nativeElement;6 expect(element.textContent).toBe('async directive');7});8import { directiveAsync } from 'ng-mocks';9import { MyDirective } from './my-directive';10it('should render async directive', async () => {11 const fixture = directiveAsync(MyDirective);12 const element = fixture.debugElement.nativeElement;13 expect(element.textContent).toBe('async directive');14});15import { directiveAsync } from 'ng-mocks';16import { MyDirective } from './my-directive';17it('should render async directive', async () => {18 const fixture = directiveAsync(MyDirective);19 const element = fixture.debugElement.nativeElement;20 expect(element.textContent).toBe('async directive');21});22import { directiveAsync } from 'ng-mocks';23import { MyDirective } from './my-directive';24it('should render async directive', async () => {25 const fixture = directiveAsync(MyDirective);26 const element = fixture.debugElement.nativeElement;27 expect(element.textContent).toBe('async directive');28});29import { directiveAsync } from 'ng-mocks';30import { MyDirective } from './my-directive';31it('should render async directive', async () => {32 const fixture = directiveAsync(MyDirective);33 const element = fixture.debugElement.nativeElement;34 expect(element.textContent).toBe('async directive');35});
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!!