Best JavaScript code snippet using ng-mocks
oyakata.js
Source:oyakata.js
1define(['basho/main', 'haridashi/main', 'ichimon/main', 'sumoji/main', 'yobidashi/main', 'require'],2 function (platform, utility, mixins, components, messages, require) {3 var oop = {};4 //create a sumo5 oop.create = function (def) {6 var ctor = function (extend) {7 if (!(this instanceof ctor)) {8 console.log('called without keyword new');9 return;10 }11 var extendedDef = {};12 //apply mixins needed for runtime13 //mixins have a race condition14 if (def.mixins) {15 def.isReady = false;16 extendedDef = oop.mixins(def, def.mixins);17 } else {18 }19 //extend the defs passed to the constructor20 extendedDef = utility.extend(def, extend);21 extendedDef = utility.extend(def, oop.extends);22 if (extendedDef.create) {23 extendedDef.create();24 }25 return extendedDef;26 }27 ctor.prototype = def;28 //return the sumo29 return ctor;30 };31 oop.extends = {32 //collection of extends that will be applied to a sumo33 ready: function (fn) {34 var component = this;35 var boundFn = utility.bind(fn, component);36 var readyStateCheckInterval = window.setInterval(function () {37 if (component.isReady) {38 window.clearInterval(readyStateCheckInterval);39 boundFn();40 }41 }, 10);42 }43 };44 oop.mixins = function (def, _mixins) {45 //array with keys for loaded mixins46 var loadedMixins = [];47 //pop from _mixins and push to requiredMixins48 //a list used to load our async mixins in49 //correct order50 var requiredMixins = [];51 var mixed = function (_mixin_) {52 loadedMixins[_mixin_.name] = _mixin_;53 //check if the arrays match length, and all mixins were loaded54 //then mixin according to proper order of precedence55 if (Object.keys(loadedMixins).length === requiredMixins.length) {56 //we have a full array of loaded mixins57 //lets load them accoeding to the required mixins order58 requiredMixins.map(function (mixin, index) {59 //add mixin60 def = mixins.mix(def, loadedMixins[mixin]);61 });62 //report the component is ready63 def.isReady = true;64 }65 }66 //apply mixins to a sumo, and then declare that sumo is ready67 while (_mixins.length > 0) {68 var _mixin = _mixins.pop();69 if (components[_mixin]) {70 //load mixin from memory object71 def = mixins.mix(def, components[_mixin]);72 }73 else if(typeof _mixin === 'object') {74 //load mixin from passed object75 def = mixins.mix(def, _mixin);76 }77 else {78 //load modules dynamically from the app source if desired79 requiredMixins.push(_mixin);80 require(['./components/' + _mixin], function (_mixin_) {81 //if the mixin isn't named, name it so we know what we are loading82 if (!_mixin_.name) {83 _mixin_.name = _mixin84 };85 //add to mixing que86 mixed(_mixin_);87 });88 }89 }90 //if there are no requiredMixins we can resolve this component now91 if (requiredMixins.length == 0) {92 def.isReady = true;93 }94 //remove mixins property95 delete def.mixins;96 return def;97 };98 return oop;...
init-ng-modules.ts
Source:init-ng-modules.ts
1import { flatten, mapValues } from '../../common/core.helpers';2import coreReflectProvidedIn from '../../common/core.reflect.provided-in';3import { AnyDeclaration } from '../../common/core.types';4import errorJestMock from '../../common/error.jest-mock';5import funcGetName from '../../common/func.get-name';6import funcGetProvider from '../../common/func.get-provider';7import { isNgDef } from '../../common/func.is-ng-def';8import { isNgInjectionToken } from '../../common/func.is-ng-injection-token';9import { isStandalone } from '../../common/func.is-standalone';10import ngMocksUniverse from '../../common/ng-mocks-universe';11import markProviders from '../../mock-module/mark-providers';12import initModule from './init-module';13import { BuilderData, NgMeta } from './types';14const skipDef = (def: any): boolean =>15 ngMocksUniverse.touches.has(def) || isNgDef(def) || isNgInjectionToken(def) || typeof def === 'string';16const handleDef = ({ imports, declarations, providers }: NgMeta, def: any, defProviders: Map<any, any>): void => {17 if (!skipDef(def)) {18 errorJestMock(def);19 }20 let touched = false;21 if (isNgDef(def, 'm')) {22 const extendedDef = initModule(def, defProviders);23 imports.push(extendedDef);24 touched = true;25 // adding providers to touches26 if (typeof extendedDef === 'object' && extendedDef.providers) {27 for (const provider of flatten(extendedDef.providers)) {28 ngMocksUniverse.touches.add(funcGetProvider(provider));29 }30 }31 }32 if (isNgDef(def, 'c') || isNgDef(def, 'd') || isNgDef(def, 'p')) {33 (isStandalone(def) ? imports : declarations).push(ngMocksUniverse.getBuildDeclaration(def));34 touched = true;35 }36 if (isNgDef(def, 'i') || !isNgDef(def)) {37 const mock = ngMocksUniverse.builtProviders.get(def);38 if (mock && typeof mock !== 'string' && isNgDef(mock, 't') === false) {39 providers.push(mock);40 touched = true;41 }42 }43 if (touched) {44 ngMocksUniverse.touches.add(def);45 }46};47export default (48 { configDef, configDefault, keepDef, mockDef, replaceDef }: BuilderData,49 defProviders: Map<any, any>,50): NgMeta => {51 const meta: NgMeta = { imports: [], declarations: [], providers: [] };52 const forgotten: AnyDeclaration<any>[] = [];53 // Adding suitable leftovers.54 for (const def of [...mapValues(mockDef), ...mapValues(keepDef), ...mapValues(replaceDef)]) {55 const configInstance = ngMocksUniverse.configInstance.get(def);56 const config = configDef.get(def);57 if (!config.dependency && config.export && !configInstance?.exported && (isNgDef(def, 'i') || !isNgDef(def))) {58 handleDef(meta, def, defProviders);59 markProviders([def]);60 } else if (!ngMocksUniverse.touches.has(def) && !config.dependency) {61 handleDef(meta, def, defProviders);62 } else if (63 config.dependency &&64 configDefault.dependency &&65 coreReflectProvidedIn(def) !== 'root' &&66 (typeof def !== 'object' || !(def as any).__ngMocksSkip)67 ) {68 forgotten.push(def);69 }70 }71 // Checking missing dependencies72 const globalFlags = ngMocksUniverse.global.get('flags');73 for (const def of forgotten) {74 if (ngMocksUniverse.touches.has(def)) {75 continue;76 }77 const errorMessage = [78 `MockBuilder has found a missing dependency: ${funcGetName(def)}.`,79 'It means no module provides it.',80 'Please, use the "export" flag if you want to add it explicitly.',81 'https://ng-mocks.sudo.eu/api/MockBuilder#export-flag',82 ].join(' ');83 if (globalFlags.onMockBuilderMissingDependency === 'warn') {84 console.warn(errorMessage);85 } else if (globalFlags.onMockBuilderMissingDependency === 'throw') {86 throw new Error(errorMessage);87 }88 }89 return meta;...
extensions.ts
Source:extensions.ts
1import type ajv from 'ajv'2import type { produce } from 'immer'3import type { Definition, JSONSchema } from './types'4import type { Options, Model } from './model'5import { InferShapeOfDef } from './inference'6export { ValidationError } from 'ajv'7export { immerable } from 'immer'8export interface Extensions {9 extend(def: ElementDefinitionOptions): Extensions10 validate(obj: unknown): void11 produce: Function12}13type Ajv = Pick<ajv.Ajv, 'compile' | 'errorsText'> & {14 // need a work around with loose type annotation15 // since different sources of Ajv could be treated as imcompatible16 // even when they have same version17 addSchema(schema: JSONSchema): void18}19export interface ExtensionOptions {20 ajv?: Ajv21 immer?: typeof produce22}23export type InferExtensionsByOptions<24 Def extends Definition,25 Opts extends Options,26 Shape = Opts['immer'] extends typeof produce27 ? Readonly<InferShapeOfDef<Def>>28 : InferShapeOfDef<Def>29> = Model<Def, Shape> & {30 extend<ExtendedDef extends Definition>(31 def: ExtendedDef32 ): InferExtensionsByOptions<ExtendedDef & Def, Opts>33} & (Opts['ajv'] extends Ajv34 ? {35 // eslint-disable-next-line @typescript-eslint/no-explicit-any36 validate(obj: any): obj is Shape37 extend<ExtendedDef extends Definition>(38 def: ExtendedDef39 ): InferExtensionsByOptions<ExtendedDef & Def, Opts>40 }41 : {}) &42 (Opts['immer'] extends typeof produce43 ? {44 produce: typeof produce &45 (<T extends Shape>(46 base: T,47 updater: (draft: T) => T48 ) => Shape)49 extend<ExtendedDef extends Definition>(50 def: ExtendedDef51 ): InferExtensionsByOptions<ExtendedDef & Def, Opts>52 }...
Using AI Code Generation
1import {extendedDef} from 'ng-mocks';2import {mockComponent} from 'ng-mocks';3import {mockDirective} from 'ng-mocks';4import {mockPipe} from 'ng-mocks';5import {mockProvider} from 'ng-mocks';6import {mockRender} from 'ng-mocks';7import {ngMocks} from 'ng-mocks';8import {ngMocksUniverse} from 'ng-mocks';9import {ngMocksFormat} from 'ng-mocks';10import {ngMocksGuts} from 'ng-mocks';11import {ngMocksGlobal} from 'ng-mocks';12import {ngMocksInput} from 'ng-mocks';13import {ngMocksOutput} from 'ng-mocks';14import {ngMocksStubs} from 'ng-mocks';15import {ngMocksUniverse} from 'ng-mocks';16import {ngMocksUniverseReset} from 'ng-mocks';17import {ngMocksUniverseSet} from 'ng-mocks';18import {ngMocksWarn} from 'ng-mocks';19import {ngMocksX} from 'ng-mocks';20import {MockBuilder} from 'ng-mocks';
Using AI Code Generation
1import { extendedDef } from 'ng-mocks';2import { MyComponent } from './my.component';3describe('MyComponent', () => {4 it('should render', () => {5 const fixture = extendedDef(MyComponent).create();6 expect(fixture.nativeElement).toBeDefined();7 });8});9import { Component, Input } from '@angular/core';10@Component({11 <div [class]="class">{{ text }}</div>12})13export class MyComponent {14 @Input() public text: string;15 @Input() public class: string;16}
Using AI Code Generation
1import {extendedDef} from 'ng-mocks';2import {TestBed} from '@angular/core/testing';3import {Component} from '@angular/core';4import {MockService} from './mock-service';5@Component({6})7class TestComponent {8 constructor(9 ) {}10}11describe('TestComponent', () => {12 beforeEach(() => {13 TestBed.configureTestingModule({14 extendedDef(MockService)15 });16 });17 it('should create', () => {18 const fixture = TestBed.createComponent(TestComponent);19 const component = fixture.componentInstance;20 expect(component).toBeTruthy();21 });22});23import {Injectable} from '@angular/core';24@Injectable()25export class MockService {26 constructor() {}27}28{29 "compilerOptions": {30 },31}32{33 "compilerOptions": {34 "importHelpers": true,35 }36}37module.exports = {38 globals: {39 'ts-jest': {
Using AI Code Generation
1describe('MyService', () => {2 let myService: MyService;3 beforeEach(() => {4 myService = extendedDef(MyService);5 });6 it('should return "Hello World!"', () => {7 expect(myService.getHello()).toBe('Hello World!');8 });9});10describe('MyService', () => {11 let myService: MyService;12 beforeEach(() => {13 myService = extendedDef(MyService);14 });15 it('should return "Hello World!"', () => {16 expect(myService.getHello()).toBe('Hello World!');17 });18});
Using AI Code Generation
1import {extendDef} from 'ng-mocks';2extendDef('my-component', {3});4import {TestBed} from '@angular/core/testing';5import {MyComponent} from './my-component';6describe('MyComponent', () => {7 beforeEach(() => {8 TestBed.configureTestingModule({9 });10 });11 it('should create the component', () => {12 const fixture = TestBed.createComponent(MyComponent);13 const app = fixture.debugElement.componentInstance;14 expect(app).toBeTruthy();15 });16});17import {TestBed} from '@angular/core/testing';18import {MyComponent} from './my-component';19describe('MyComponent', () => {20 beforeEach(() => {21 TestBed.configureTestingModule({22 });23 });24 it('should create the component', () => {25 const fixture = TestBed.createComponent(MyComponent);26 const app = fixture.debugElement.componentInstance;27 expect(app).toBeTruthy();28 });29});
Using AI Code Generation
1const mock = ngMocks.default;2mock.extend('extendedDef', (mock, def) => {3 mock.componentDef = def;4 return mock;5});6const mock = ngMocks.default;7mock.extend('extendedDef', (mock, def) => {8 mock.componentDef = def;9 return mock;10});11const mock = ngMocks.default;12mock.extend('extendedDef', (mock, def) => {13 mock.componentDef = def;14 return mock;15});16const mock = ngMocks.default;17mock.extend('extendedDef', (mock, def) => {18 mock.componentDef = def;19 return mock;20});21const mock = ngMocks.default;22mock.extend('extendedDef', (mock, def) => {23 mock.componentDef = def;24 return mock;25});26const mock = ngMocks.default;27mock.extend('extendedDef', (mock, def) => {28 mock.componentDef = def;29 return mock;30});31const mock = ngMocks.default;32mock.extend('extendedDef', (mock, def) => {33 mock.componentDef = def;34 return mock;35});36const mock = ngMocks.default;37mock.extend('extendedDef', (mock, def) => {38 mock.componentDef = def;39 return mock;40});41const mock = ngMocks.default;42mock.extend('extendedDef', (mock, def) => {43 mock.componentDef = def;44 return mock;45});46const mock = ngMocks.default;47mock.extend('extendedDef', (mock, def) => {48 mock.componentDef = def;49 return mock;50});51const mock = ngMocks.default;52mock.extend('extendedDef', (mock, def) => {53 mock.componentDef = def;
Using AI Code Generation
1const { extendDef } = require('ng-mocks');2const extendedDef = extendDef(MyComponent);3const mock = extendedDef.createMock();4const fixture = extendedDef.create();5const testBed = extendedDef.createTestBed();6const testHost = extendedDef.createTestHost();7const { extend } = require('ng-mocks');8const extendedDef = extend(MyComponent);9const mock = extendedDef.createMock();10const fixture = extendedDef.create();11const testBed = extendedDef.createTestBed();12const testHost = extendedDef.createTestHost();13const { ExtendedDef } = require('ng-mocks');14const extendedDef = new ExtendedDef(MyComponent);15const mock = extendedDef.createMock();16const fixture = extendedDef.create();17const testBed = extendedDef.createTestBed();18const testHost = extendedDef.createTestHost();19const { ExtendedDef } = require('ng-mocks');20const extendedDef = new ExtendedDef(MyComponent);21const mock = extendedDef.createMock();22const fixture = extendedDef.create();23const testBed = extendedDef.createTestBed();
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!!