Best JavaScript code snippet using ng-mocks
ServerNetworkedValuesReader.ts
Source:ServerNetworkedValuesReader.ts
1import { ISignal, ISignalConnection, Signal } from "@rbxts/signals-tooling";2import { RunService, HttpService } from "@rbxts/services";3import { JsonSafe } from "../../types/JsonSafe";4import { t } from "@rbxts/t";5import { ValueObjectClassName } from "../../types/ValueObjectClassName";6function mustGetValueObjectInstance(name: string, parentInstance: Instance) {7 const valueObjectInstance = parentInstance.FindFirstChild(name);8 if (valueObjectInstance === undefined) {9 throw `Networked value instance does not yet exist: ${name}`;10 }11 return valueObjectInstance;12}13function assertValueObjectInstanceType<T extends ValueObjectClassName>(14 valueObjectInstance: Instance,15 className: T,16): asserts valueObjectInstance is Instances[T] {17 assert(18 valueObjectInstance.IsA(className),19 `Expected networked value instance to be of type ${className}, got ${valueObjectInstance.ClassName}`,20 );21}22function assertValuePassesCheck<T>(value: unknown, tCheck: t.check<T>): asserts value is T {23 assert(tCheck(value), "Cannot deserialize value - serialized value is invalid");24}25function defaultCreateSignal(): ISignal {26 return new Signal();27}28export class ServerNetworkedValuesReader {29 private constructor(30 private readonly createSignal: () => ISignal,31 private readonly httpService: HttpService,32 private readonly runService: RunService,33 ) {}34 public static create(this: void) {35 if (!RunService.IsClient()) {36 throw `Cannot create unless on client`;37 }38 return new ServerNetworkedValuesReader(defaultCreateSignal, HttpService, RunService);39 }40 public doesNetworkedValueExist(name: string, parentInstance: Instance): boolean {41 try {42 const valueObject = mustGetValueObjectInstance(name, parentInstance);43 return valueObject.IsA("ValueBase");44 } catch {45 return false;46 }47 }48 public getCurrentBooleanValue(name: string, parentInstance: Instance): boolean {49 const valueObjectInstance = mustGetValueObjectInstance(name, parentInstance);50 assertValueObjectInstanceType(valueObjectInstance, "BoolValue");51 return valueObjectInstance.Value;52 }53 public getCurrentBrickColorValue(name: string, parentInstance: Instance): BrickColor {54 const valueObjectInstance = mustGetValueObjectInstance(name, parentInstance);55 assertValueObjectInstanceType(valueObjectInstance, "BrickColorValue");56 return valueObjectInstance.Value;57 }58 public getCurrentCFrameValue(name: string, parentInstance: Instance): CFrame {59 const valueObjectInstance = mustGetValueObjectInstance(name, parentInstance);60 assertValueObjectInstanceType(valueObjectInstance, "CFrameValue");61 return valueObjectInstance.Value;62 }63 public getCurrentColor3Value(name: string, parentInstance: Instance): Color3 {64 const valueObjectInstance = mustGetValueObjectInstance(name, parentInstance);65 assertValueObjectInstanceType(valueObjectInstance, "Color3Value");66 return valueObjectInstance.Value;67 }68 public getCurrentEnumValue<T extends number>(name: string, parentInstance: Instance): T {69 const valueObjectInstance = mustGetValueObjectInstance(name, parentInstance);70 assertValueObjectInstanceType(valueObjectInstance, "IntValue");71 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions72 return valueObjectInstance.Value as T;73 }74 public getCurrentInstanceValue(name: string, parentInstance: Instance): Instance | undefined {75 const valueObjectInstance = mustGetValueObjectInstance(name, parentInstance);76 assertValueObjectInstanceType(valueObjectInstance, "ObjectValue");77 return valueObjectInstance.Value;78 }79 public getCurrentJsonValue<T extends JsonSafe>(name: string, parentInstance: Instance, tCheck: t.check<T>): T {80 const valueObjectInstance = mustGetValueObjectInstance(name, parentInstance);81 assertValueObjectInstanceType(valueObjectInstance, "StringValue");82 const serializedValue = valueObjectInstance.Value;83 const deserializedValue = serializedValue === "" ? undefined : this.httpService.JSONDecode(serializedValue);84 assertValuePassesCheck(deserializedValue, tCheck);85 return deserializedValue;86 }87 public getCurrentNumberValue(name: string, parentInstance: Instance): number {88 const valueObjectInstance = mustGetValueObjectInstance(name, parentInstance);89 assertValueObjectInstanceType(valueObjectInstance, "NumberValue");90 return valueObjectInstance.Value;91 }92 public getCurrentRayValue(name: string, parentInstance: Instance): Ray {93 const valueObjectInstance = mustGetValueObjectInstance(name, parentInstance);94 assertValueObjectInstanceType(valueObjectInstance, "RayValue");95 return valueObjectInstance.Value;96 }97 public getCurrentStringValue(name: string, parentInstance: Instance): string {98 const valueObjectInstance = mustGetValueObjectInstance(name, parentInstance);99 assertValueObjectInstanceType(valueObjectInstance, "StringValue");100 return valueObjectInstance.Value;101 }102 public getCurrentVector3Value(name: string, parentInstance: Instance): Vector3 {103 const valueObjectInstance = mustGetValueObjectInstance(name, parentInstance);104 assertValueObjectInstanceType(valueObjectInstance, "Vector3Value");105 return valueObjectInstance.Value;106 }107 public subscribeToBooleanValue(108 name: string,109 parentInstance: Instance,110 valueChangedCallback: (newValue: boolean) => void,111 ): ISignalConnection {112 const valueObjectInstance = parentInstance.WaitForChild(name);113 assertValueObjectInstanceType(valueObjectInstance, "BoolValue");114 return valueObjectInstance.Changed.Connect(valueChangedCallback);115 }116 public subscribeToBrickColorValue(117 name: string,118 parentInstance: Instance,119 valueChangedCallback: (newValue: BrickColor) => void,120 ): ISignalConnection {121 const valueObjectInstance = parentInstance.WaitForChild(name);122 assertValueObjectInstanceType(valueObjectInstance, "BrickColorValue");123 return valueObjectInstance.Changed.Connect(valueChangedCallback);124 }125 public subscribeToCFrameValue(126 name: string,127 parentInstance: Instance,128 valueChangedCallback: (newValue: CFrame) => void,129 ): ISignalConnection {130 const valueObjectInstance = parentInstance.WaitForChild(name);131 assertValueObjectInstanceType(valueObjectInstance, "CFrameValue");132 return valueObjectInstance.Changed.Connect(valueChangedCallback);133 }134 public subscribeToColor3Value(135 name: string,136 parentInstance: Instance,137 valueChangedCallback: (newValue: Color3) => void,138 ): ISignalConnection {139 const valueObjectInstance = parentInstance.WaitForChild(name);140 assertValueObjectInstanceType(valueObjectInstance, "Color3Value");141 return valueObjectInstance.Changed.Connect(valueChangedCallback);142 }143 public subscribeToEnumValue<T extends number>(144 name: string,145 parentInstance: Instance,146 valueChangedCallback: (newValue: T) => void,147 ): ISignalConnection {148 const valueObjectInstance = parentInstance.WaitForChild(name);149 assertValueObjectInstanceType(valueObjectInstance, "IntValue");150 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions151 return valueObjectInstance.Changed.Connect((newValue) => valueChangedCallback(newValue as T));152 }153 public subscribeToInstanceValue(154 name: string,155 parentInstance: Instance,156 valueChangedCallback: (newValue: Instance | undefined) => void,157 ): ISignalConnection {158 const valueObjectInstance = parentInstance.WaitForChild(name);159 assertValueObjectInstanceType(valueObjectInstance, "ObjectValue");160 return valueObjectInstance.Changed.Connect(valueChangedCallback);161 }162 public subscribeToJsonValue<T extends JsonSafe>(163 name: string,164 parentInstance: Instance,165 tCheck: t.check<T>,166 valueChangedCallback: (newValue: T) => void,167 ): ISignalConnection {168 const valueObjectInstance = mustGetValueObjectInstance(name, parentInstance);169 assertValueObjectInstanceType(valueObjectInstance, "StringValue");170 const deserializeAndFireValueChangedCallback = (serializedValue: string) => {171 const deserializedValue = serializedValue === "" ? undefined : this.httpService.JSONDecode(serializedValue);172 assertValuePassesCheck(deserializedValue, tCheck);173 valueChangedCallback(deserializedValue);174 };175 return valueObjectInstance.Changed.Connect(deserializeAndFireValueChangedCallback);176 }177 public subscribeToNumberValue(178 name: string,179 parentInstance: Instance,180 valueChangedCallback: (newValue: number) => void,181 ): ISignalConnection {182 const valueObjectInstance = parentInstance.WaitForChild(name);183 assertValueObjectInstanceType(valueObjectInstance, "NumberValue");184 return valueObjectInstance.Changed.Connect(valueChangedCallback);185 }186 public subscribeToRayValue(187 name: string,188 parentInstance: Instance,189 valueChangedCallback: (newValue: Ray) => void,190 ): ISignalConnection {191 const valueObjectInstance = parentInstance.WaitForChild(name);192 assertValueObjectInstanceType(valueObjectInstance, "RayValue");193 return valueObjectInstance.Changed.Connect(valueChangedCallback);194 }195 public subscribeToStringValue(196 name: string,197 parentInstance: Instance,198 valueChangedCallback: (newValue: string) => void,199 ): ISignalConnection {200 const valueObjectInstance = parentInstance.WaitForChild(name);201 assertValueObjectInstanceType(valueObjectInstance, "StringValue");202 return valueObjectInstance.Changed.Connect(valueChangedCallback);203 }204 public subscribeToVector3Value(205 name: string,206 parentInstance: Instance,207 valueChangedCallback: (newValue: Vector3) => void,208 ): ISignalConnection {209 const valueObjectInstance = parentInstance.WaitForChild(name);210 assertValueObjectInstanceType(valueObjectInstance, "Vector3Value");211 return valueObjectInstance.Changed.Connect(valueChangedCallback);212 }213 public waitForNetworkedValueToExist(name: string, parentInstance: Instance) {214 if (this.doesNetworkedValueExist(name, parentInstance)) {215 return;216 }217 const tempSignal = this.createSignal();218 const steppedConnection = this.runService.Stepped.Connect(() => {219 if (this.doesNetworkedValueExist(name, parentInstance)) {220 steppedConnection.Disconnect();221 tempSignal.fire();222 }223 });224 tempSignal.Wait();225 tempSignal.destroy();226 }...
ReactEXT.js
Source:ReactEXT.js
1import ReactDOM from 'react-dom';2import { l } from './index'3import { reactify2 } from './reactify';4import React from 'react';5import ReactFiberReconciler from 'react-reconciler';6import invariant from 'fbjs/lib/invariant';7import emptyObject from 'fbjs/lib/emptyObject';8const UPDATE_SIGNAL = {};9const EXTRenderer = ReactFiberReconciler({10 createInstance(type, props, internalInstanceHandle) {11 let instance = null;12 const xtype = type.toLowerCase().replace(/_/g, '-')13 l(`first EXTRenderer createInstance ${xtype} (props, internalInstanceHandle, parentProps)`, props, internalInstanceHandle, internalInstanceHandle.initialConfig )14 var target = Ext.ClassManager.getByAlias(`widget.${xtype}`)15 if (target == undefined) {16 l(`****** undefined ${xtype} (props, internalInstanceHandle, parentProps)`, props, internalInstanceHandle, internalInstanceHandle.initialConfig )17 return instance18 }19 else {20 l(`EXTRenderer createInstance ${type} (props, internalInstanceHandle, parentProps)`, props, internalInstanceHandle, internalInstanceHandle.initialConfig )21 var Type = reactify2(type)22 instance = new Type(props);23 return instance;24 }25 },26 createTextInstance(text, rootContainerInstance, internalInstanceHandle) {27// l(`createTextInstance (text, rootContainerInstance, internalInstanceHandle)`,text, rootContainerInstance, internalInstanceHandle)28 return text;29 },30 finalizeInitialChildren(domElement, type, props) {31// l(`finalizeInitialChildren********** ${type} (domElement, props)`,domElement, props)32 return false;33 },34 getPublicInstance(instance) {35 l(`getPublicInstance`,instance)36 return instance;37 },38 prepareForCommit() {39 l(`prepareForCommit`)40 // Noop41 },42 prepareUpdate(domElement, type, oldProps, newProps) {43 l(`prepareUpdate ${type} (domElement, oldProps, newProps)`, domElement, oldProps, newProps)44 return UPDATE_SIGNAL;45 },46 resetAfterCommit() {47 l(`resetAfterCommit`)48 // Noop49 },50 resetTextContent(domElement) {51 l(`resetTextContent**********`)52 // Noop53 },54 shouldDeprioritizeSubtree(type, props) {55 l(`shouldDeprioritizeSubtree**********`)56 return false;57 },58 getRootHostContext() {59// l(`getRootHostContext**********`)60 return emptyObject;61 },62 getChildHostContext() {63// l(`getChildHostContext**********`)64 return emptyObject;65 },66// scheduleDeferredCallback: ReactDOMFrameScheduling.rIC,67 shouldSetTextContent(type, props) {68// l(`shouldSetTextContent**********`)69 return (70 typeof props.children === 'string' || typeof props.children === 'number'71 );72 },73 appendInitialChild(parentInstance, child) {74 // l('appendInitialChild (child.xtype, parentInstance, child)')75 // l('parentInstance',parentInstance)76 // l('child',child)77 if (parentInstance != null && child != null) {78 l('appendInitialChild (child.xtype, parentInstance, child)', child.xtype, parentInstance, child)79 l('appendInitialChild d', 'parent - ' + parentInstance.props.d, 'child - ' + child.props.d)80 doAdd(child.xtype, parentInstance._cmp, child)81 }82// parentInstance._cmp.add(child._cmp) //Ext add83 // if (typeof child === 'string') {84 // // Noop for string children of Text (eg <Text>{'foo'}{'bar'}</Text>)85 // invariant(false, 'Text children should already be flattened.');86 // return;87 // }88 // child.inject(parentInstance);89 },90// now: ReactDOMFrameScheduling.now,91 now: () => {},92 useSyncScheduling: true,93 mutation: {94 appendChild(parentInstance, child) {95 l('appendChild (child.xtype, parentInstance, child)')96 if (parentInstance != null && child != null) {97 l('appendChild (child.xtype, parentInstance, child)', child.xtype, parentInstance, child)98 doAdd(child.xtype, parentInstance._cmp, child)99 }100 },101 appendChildToContainer(parentInstance, child) {102 if (parentInstance != null && child != null) {103 l('appendChildToContainer (child.xtype, parentInstance, child)', child.xtype, parentInstance, child)104 doAdd(child.xtype, parentInstance, child)105 }106 else {107 l('appendChildToContainer (null)')108 }109 // if (parentInstance._cmp != null && child != null) {110 // l('appendChildToContainer (child.xtype, parentInstance, child)', child.xtype, parentInstance, child)111 // doAdd(child.xtype, parentInstance._cmp, child)112 // }113 },114 insertBefore(parentInstance, child, beforeChild) {115 l(`insertBefore**********`)116 invariant(117 child !== beforeChild,118 'ReactEXT: Can not insert node before itself',119 );120 child.injectBefore(beforeChild);121 },122 insertInContainerBefore(parentInstance, child, beforeChild) {123 l(`insertInContainerBefore**********`)124 invariant(125 child !== beforeChild,126 'ReactExt: Can not insert node before itself',127 );128 child.injectBefore(beforeChild);129 },130 removeChild(parentInstance, child) {131 l(`removeChild (parentInstance, child)`, parentInstance, child)132 if (parentInstance != null && child != null) {133 parentInstance._cmp.remove(child._cmp, true)134 }135 },136 removeChildFromContainer(parentInstance, child) {137 l(`removeChildFromContainer (parentInstance, child)`, parentInstance, child)138 if (parentInstance != null && child != null) {139 parentInstance.remove(child._cmp, true)140 }141 },142 commitTextUpdate(textInstance, oldText, newText) {143 l(`commitTextUpdate**********`)144 // Noop145 },146 commitMount(instance, type, newProps) {147 l(`commitMount**********`)148 // Noop149 },150 commitUpdate(instance, updatePayload, type, oldProps, newProps) {151 l(`commitUpdate**********`)152// instance._applyProps(instance, newProps, oldProps);153 },154 },155});156export default EXTRenderer157function doAdd(xtype, parentCmp, child) {158 var childCmp = child._cmp159 if (xtype == 'column') {160 l(`doAdd ${xtype}`)161 var columns = []162 var newColumns = []163 columns = parentCmp.getColumns()164 for (var item in columns) {165 newColumns.push(columns[item])166 }167 newColumns.push(childCmp)168 parentCmp.setColumns(newColumns)169 }170 else if (parentCmp.add != undefined) {171 l(`doAdd ${xtype} (parentCmp, childCmp)`, parentCmp, childCmp)172 parentCmp.add(childCmp)173// return174 var isHTML = false175 var children = child.props.children176 if (children != undefined) {177 if (children.length == undefined) {178 var child = children179 if (child != undefined) {180 if (child != undefined) {181 if (child.type != undefined) {182 if(child.type[0] != undefined) {183 var type = child.type184 const xtype = type.toLowerCase().replace(/_/g, '-')185 var target = Ext.ClassManager.getByAlias(`widget.${xtype}`)186 if (target == undefined) {187/// if (child.type[0] != child.type[0].toUpperCase()) {188 isHTML = true189 }190 else {191 var Type = reactify2(type)192 var instance = new Type(child.props)193 }194 }195 }196 }197 }198 }199 else {200 for (var child of children) {201 if (child != undefined) {202 if (child.type != undefined) {203 if(child.type[0] != undefined) {204 var type = child.type205 const xtype = type.toLowerCase().replace(/_/g, '-')206 var target = Ext.ClassManager.getByAlias(`widget.${xtype}`)207 if (target == undefined) {208/// if (child.type[0] != child.type[0].toUpperCase()) {209 isHTML = true210 }211 else {212 var Type = reactify2(type)213 var instance = new Type(child.props)214 }215 }216 }217 }218 }219 }220 }221 if (isHTML) {222 var widget = Ext.create({xtype:'widget'})223 childCmp.add(widget)224 ReactDOM.render(children,widget.el.dom)225 }226 }227 else {228 l(`doAdd ${xtype} undefined...`)229 }...
renderer.js
Source:renderer.js
1/* eslint-disable */2import emptyObject from 'fbjs/lib/emptyObject'3const Reconciler = require('react-reconciler')4import { createElement, getHostContextNode } from '../utils/createElement'5const RendererHostConfig = {6 appendInitialChild(parentInstance, child) {7 if (parentInstance.appendChild) {8 parentInstance.appendChild(child)9 } else {10 parentInstance.document = child11 }12 },13 createInstance(type, props, internalInstanceHandle) {14 return createElement(type, props)15 },16 createTextInstance(text, rootContainerInstance, internalInstanceHandle) {17 return text18 },19 finalizeInitialChildren(wordElement, type, props) {20 return false21 },22 getPublicInstance(inst) {23 return inst24 },25 prepareForCommit() {26 // noop27 },28 prepareUpdate(wordElement, type, oldProps, newProps) {29 return true30 },31 resetAfterCommit() {32 // noop33 },34 resetTextContent(wordElement) {35 // Redocx does not have a text node like DOM36 },37 // If you've such use case where you need to provide data from the root instance,38 // see the below example. This may help you in creating your own custom renderer39 40 createInstance(type, props, internalInstanceHandle) {41 // 'internalInstanceHandle' is not transparent here. So use host context methods42 // to get data from roots43 return createElement(type, props)44 },45 // Use this current instance to pass data from root46 getRootHostContext(instance) {47 // getHostContextNode here updates the internal state of createElement and stores a ref to current instance48 return getHostContextNode(instance)49 },50 getChildHostContext() {51 return emptyObject52 },53 shouldSetTextContent(type, props) {54 return false // Redocx does not have a text node like DOM55 },56 now: () => {},57 useSyncScheduling: true,58 mutation: {59 appendChild(parentInstance, child) {60 if (parentInstance.appendChild) {61 parentInstance.appendChild(child)62 } else {63 parentInstance.document = child64 }65 },66 appendChildToContainer(parentInstance, child) {67 if (parentInstance.appendChild) {68 parentInstance.appendChild(child)69 } else {70 parentInstance.document = child71 }72 },73 removeChild(parentInstance, child) {74 parentInstance.removeChild(child)75 },76 removeChildFromContainer(parentInstance, child) {77 parentInstance.removeChild(child)78 },79 insertBefore(parentInstance, child, beforeChild) {80 // noob81 },82 commitUpdate(instance, updatePayload, type, oldProps, newProps) {83 // noop84 },85 commitMount(instance, updatePayload, type, oldProps, newProps) {86 // noop87 },88 commitTextUpdate(textInstance, oldText, newText) {89 textInstance.children = newText90 },91 },92}93const WordRenderer = Reconciler(RendererHostConfig)...
Using AI Code Generation
1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2import { ParentComponent } from './parent.component';3import { ChildComponent } from './child.component';4describe('ParentComponent', () => {5 beforeEach(() => MockBuilder(ParentComponent));6 it('should create', () => {7 const fixture = MockRender(ParentComponent);8 const instance = ngMocks.parentInstance(fixture.debugElement);9 expect(instance).toBeDefined();10 });11 it('should find child component', () => {12 const fixture = MockRender(ParentComponent);13 const instance = ngMocks.parentInstance(fixture.debugElement, ChildComponent);14 expect(instance).toBeDefined();15 });16});17import { Component, OnInit } from '@angular/core';18@Component({19})20export class ParentComponent implements OnInit {21 constructor() {}22 ngOnInit() {}23}24import { Component, OnInit } from '@angular/core';25@Component({26})27export class ChildComponent implements OnInit {28 constructor() {}29 ngOnInit() {}30}31import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';32import { ParentComponent } from './parent.component';33import { ChildComponent } from './child.component';34describe('ParentComponent', () => {35 beforeEach(() => MockBuilder(ParentComponent));36 it('should create', () => {37 const fixture = MockRender(ParentComponent);38 const instance = ngMocks.parentInstance(fixture.debugElement);39 expect(instance).toBeDefined();40 });41 it('should find child component', () => {42 const fixture = MockRender(ParentComponent);43 const instance = ngMocks.parentInstance(fixture.debugElement, ChildComponent);44 expect(instance).toBeDefined();45 });46});47import { Component, OnInit } from '@angular/core';48@Component({49})50export class ParentComponent implements OnInit {51 constructor() {}52 ngOnInit() {}53}54import { Component, OnInit } from '@angular/core';55@Component({
Using AI Code Generation
1import { MockBuilder, MockRender, MockInstance } from 'ng-mocks';2import { AppComponent } from './app.component';3describe('AppComponent', () => {4 beforeEach(() => MockBuilder(AppComponent));5 it('should create the app', () => {6 const fixture = MockRender(AppComponent);7 const app = fixture.point.componentInstance;8 expect(app).toBeTruthy();9 });10 it('should add 2 numbers', () => {11 const fixture = MockRender(AppComponent);12 const app = fixture.point.componentInstance;13 const result = app.add(2, 3);14 expect(result).toBe(5);15 });16 it('should call the service method', () => {17 const fixture = MockRender(AppComponent);18 const app = fixture.point.componentInstance;19 spyOn(app, 'add').and.returnValue(10);20 const result = app.callService();21 expect(result).toBe(10);22 });23 it('should call the service method using MockInstance', () => {24 const fixture = MockRender(AppComponent);25 const app = fixture.point.componentInstance;26 MockInstance(app, 'add', 10);27 const result = app.callService();28 expect(result).toBe(10);29 });30});31MockInstance(instance, methodName, returnValue, returnValueForPromise)32import { MockBuilder, MockRender, MockInstance } from 'ng-mocks';33import { AppComponent } from './app.component';34import { DataService } from './data.service';35describe('AppComponent', () => {36 beforeEach(() => MockBuilder(AppComponent).mock(DataService));37 it('should create the app', () => {38 const fixture = MockRender(AppComponent);39 const app = fixture.point.componentInstance;40 expect(app).toBeTruthy();41 });42 it('should add
Using AI Code Generation
1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2import { AppModule } from './app.module';3import { AppComponent } from './app.component';4import { MyService } from './my.service';5describe('AppComponent', () => {6 beforeEach(() => MockBuilder(AppComponent, AppModule));7 it('should create the app', () => {8 const fixture = MockRender(AppComponent);9 const app = ngMocks.parentInstance(fixture.debugElement, AppComponent);10 expect(app).toBeTruthy();11 });12 it('should have as title "app"', () => {13 const fixture = MockRender(AppComponent);14 const app = ngMocks.parentInstance(fixture.debugElement, AppComponent);15 expect(app.title).toEqual('app');16 });17 it('should render title', () => {18 const fixture = MockRender(AppComponent);19 const app = ngMocks.parentInstance(fixture.debugElement, AppComponent);20 expect(fixture.nativeElement.querySelector('h1').textContent).toContain(21 );22 });23 it('should render title from the provided service', () => {24 const fixture = MockRender(AppComponent);25 const service = ngMocks.findInstance(MyService);26 expect(fixture.nativeElement.querySelector('h1').textContent).toContain(27 );28 });29});
Using AI Code Generation
1import { parentInstance } from 'ng-mocks';2import { MockBuilder, MockRender } from 'ng-mocks';3describe('parentInstance', () => {4 beforeEach(() => MockBuilder(MyComponent));5 it('should get the parent instance', () => {6 const fixture = MockRender(`7 `);8 const component = parentInstance(fixture.point.componentInstance);9 expect(component).toBeDefined();10 });11});12import { Component } from '@angular/core';13@Component({14})15export class MyComponent {}16import { MockBuilder, MockRender } from 'ng-mocks';17import { MyComponent } from './my-component';18describe('MyComponent', () => {19 beforeEach(() => MockBuilder(MyComponent));20 it('should create', () => {21 const fixture = MockRender(MyComponent);22 expect(fixture.point.componentInstance).toBeDefined();23 });24});25import { Component } from '@angular/core';26@Component({27})28export class MyComponent {}29import { MockBuilder, MockRender } from 'ng-mocks';30import { MyComponent } from './my-component';31describe('MyComponent', () => {32 beforeEach(() => MockBuilder(MyComponent));33 it('should create', () => {34 const fixture = MockRender(MyComponent);35 expect(fixture.point.componentInstance).toBeDefined();36 });37});38import { Component } from '@angular/core';39@Component({40})41export class MyComponent {}42import { MockBuilder, MockRender } from 'ng-mocks';43import { MyComponent } from './my-component';44describe('MyComponent', () => {45 beforeEach(() => MockBuilder(MyComponent));46 it('should create', () => {47 const fixture = MockRender(MyComponent);48 expect(fixture.point.componentInstance).toBeDefined();49 });50});51import { Component } from '@angular/core';52@Component({
Using AI Code Generation
1import { parentInstance } from 'ng-mocks';2@Component({3})4export class TestComponent {5 constructor() { }6}7import { parentInstance } from 'ng-mocks';8@Component({9})10export class TestChildComponent {11 constructor() {12 const parent = parentInstance(this);13 }14}
Using AI Code Generation
1import { parentInstance } from 'ng-mocks';2@Component({3})4export class ChildComponent {5 constructor() {6 console.log(parentInstance(ChildComponent));7 }8}9@Component({10})11export class ParentComponent {}12import { MockBuilder, MockRender } from 'ng-mocks';13describe('ParentComponent', () => {14 beforeEach(() => MockBuilder(ParentComponent));15 it('should create', () => {16 const fixture = MockRender(ParentComponent);17 expect(fixture.point.componentInstance).toBeTruthy();18 });19});20parentInstance()21parentInstance()
Using AI Code Generation
1import { parentInstance } from 'ng-mocks';2const fixture = MockRender(`3`);4const parent = parentInstance(fixture.debugElement.query(By.css('#child')));5expect(parent).toBeDefined();6expect(parent.nativeElement).toBeDefined();7expect(parent.nativeElement.tagName).toEqual('DIV');
Using AI Code Generation
1import { parentInstance } from 'ng-mocks';2import { TestBed } from '@angular/core/testing';3import { AppModule } from './app.module';4import { ChildComponent } from './child.component';5import { ParentComponent } from './parent.component';6describe('parentInstance', () => {7 beforeEach(() => TestBed.configureTestingModule({ imports: [AppModule] }));8 it('finds parent instance', () => {9 const parent = parentInstance(ChildComponent);10 expect(parent).toBeInstanceOf(ParentComponent);11 });12});13import { Component } from '@angular/core';14import { ChildComponent } from './child.component';15@Component({16})17export class ParentComponent {18 @ViewChild(ChildComponent, { static: true })19 public child: ChildComponent;20}21import { Component } from '@angular/core';22@Component({23})24export class ChildComponent {}25import { NgModule } from '@angular/core';26import { ChildComponent } from './child.component';27import { ParentComponent } from './parent.component';28@NgModule({29})30export class AppModule {}31import { Component } from '@angular/core';32import { ParentComponent } from './parent.component';33@Component({34})35export class AppComponent {36 @ViewChild(ParentComponent, { static: true })37 public parent: ParentComponent;38}
Using AI Code Generation
1import { parentInstance } from 'ng-mocks';2const fixture = MockRender(`3`);4const child = fixture.debugElement.query(By.css('.child'));5const parent = parentInstance(child);6console.log(parent);7import { getClosest } from 'ng-mocks';8const fixture = MockRender(`9`);10const child = fixture.debugElement.query(By.css('.child'));11const parent = getClosest(child, TestComponent);12console.log(parent);13import { closest } from 'ng-mocks';14const fixture = MockRender(`15`);16const child = fixture.debugElement.query(By.css('.child'));17const parent = closest(child, TestComponent);18console.log(parent);19import { getClosest } from 'ng-mocks';20const fixture = MockRender(`21`);22const child = fixture.debugElement.query(By.css('.child'));23const parent = getClosest(child, TestComponent);24console.log(parent);
Using AI Code Generation
1import {parentInstance} from 'ng-mocks';2const mockParent = {3 someMethod() {4 console.log('someMethod called!');5 }6};7const mockChild = {8 someMethod() {9 console.log('someMethod called!');10 }11};12describe('MockingParentComponent', () => {13 let fixture: ComponentFixture<MockingParentComponent>;14 let component: MockingParentComponent;15 beforeEach(async(() => {16 TestBed.configureTestingModule({17 {provide: MockingParentComponent, useValue: mockParent},18 {provide: MockingChildComponent, useValue: mockChild}19 }).compileComponents();20 }));21 beforeEach(() => {22 fixture = TestBed.createComponent(MockingParentComponent);23 component = fixture.componentInstance;24 });25 it('should call parent component method', () => {26 const spy = spyOn(component, 'someMethod');27 fixture.detectChanges();28 expect(spy).toHaveBeenCalled();29 });30 it('should call parent component method using parentInstance', () => {31 const spy = spyOn(parentInstance(fixture, MockingParentComponent), 'someMethod');32 fixture.detectChanges();33 expect(spy).toHaveBeenCalled();34 });35 it('should call child component method', () => {36 const spy = spyOn(component.childComponent, 'someMethod');37 fixture.detectChanges();38 expect(spy).toHaveBeenCalled();39 });40 it('should call child component method using parentInstance', () => {41 const spy = spyOn(parentInstance(fixture, MockingChildComponent), 'someMethod');42 fixture.detectChanges();43 expect(spy).toHaveBeenCalled();44 });45});46import { Component, OnInit } from '@angular/core';47import { MockingChildComponent } from '../mocking-child/mocking-child.component';48@Component({49})50export class MockingParentComponent implements OnInit {51 public childComponent: MockingChildComponent;52 constructor() { }53 ngOnInit() {54 this.childComponent = new MockingChildComponent();55 }56 public someMethod() {57 console.log('someMethod called!');58 }59}60import { Component, OnInit } from '@
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!!