Best JavaScript code snippet using ng-mocks
mock-provider.ts
Source:mock-provider.ts
1import { Provider } from '@angular/core';2import coreConfig from '../common/core.config';3import { Type } from '../common/core.types';4import funcGetProvider from '../common/func.get-provider';5import { isNgInjectionToken } from '../common/func.is-ng-injection-token';6import ngMocksUniverse from '../common/ng-mocks-universe';7import helperDefinePropertyDescriptor from './helper.define-property-descriptor';8import helperExtractPropertyDescriptor from './helper.extract-property-descriptor';9import helperUseFactory from './helper.use-factory';10import { MockService } from './mock-service';11const { neverMockProvidedFunction, neverMockToken } = coreConfig;12const applyMissingClassProperties = (instance: any, useClass: Type<any>) => {13 const existing = Object.getOwnPropertyNames(instance);14 const child = MockService(useClass);15 for (const name of Object.getOwnPropertyNames(child)) {16 if (existing.indexOf(name) !== -1) {17 continue;18 }19 const def = helperExtractPropertyDescriptor(child, name);20 helperDefinePropertyDescriptor(instance, name, def);21 }22};23const createFactoryProvider = (provider: any, provide: any) =>24 helperUseFactory(provide, () => {25 const instance = MockService(provide);26 // Magic below adds missed properties to the instance to27 // fulfill missed abstract methods.28 if (provide !== provider && Object.keys(provider).indexOf('useClass') !== -1) {29 applyMissingClassProperties(instance, provider.useClass);30 }31 return instance;32 });33const normalizePrimitivesMap: Array<[(value: any) => boolean, any]> = [34 [value => typeof value === 'boolean', false],35 [value => typeof value === 'number', 0],36 [value => typeof value === 'string', ''],37 [value => value === null, null],38];39const normalizePrimitives = (value: any): any => {40 for (const [check, result] of normalizePrimitivesMap) {41 if (check(value)) {42 return result;43 }44 }45 return undefined;46};47const createValueProvider = (provider: any, provide: any) =>48 helperUseFactory(provide, () =>49 provider.useValue && typeof provider.useValue === 'object'50 ? MockService(provider.useValue)51 : normalizePrimitives(provider.useValue),52 );53const createClassProvider = (provider: any, provide: any) =>54 ngMocksUniverse.builtProviders.has(provider.useClass) &&55 ngMocksUniverse.builtProviders.get(provider.useClass) === provider.useClass56 ? provider57 : helperUseFactory(provide, () => MockService(provider.useClass));58const createMockProvider = (provider: any, provide: any, cacheProviders?: Map<any, any>): Provider | undefined => {59 let mockProvider: Provider | undefined;60 if (typeof provide === 'function') {61 mockProvider = createFactoryProvider(provider, provide);62 }63 if (provide === provider && mockProvider && cacheProviders) {64 cacheProviders.set(provide, mockProvider);65 }66 return mockProvider;67};68// Tokens are special subject, we can skip adding them because in a mock module they are useless.69// The main problem is that providing undefined to HTTP_INTERCEPTORS and others breaks their code.70// If a testing module / component requires omitted tokens then they should be provided manually71// during creation of TestBed module.72const handleProvider = (provider: any, provide: any, useFactory: boolean) => {73 if (provide === provider) {74 return useFactory ? helperUseFactory(provider, () => undefined) : undefined;75 }76 if (provider.multi) {77 ngMocksUniverse.config.get('ngMocksMulti')?.add(provide);78 return undefined;79 }80 let mockProvider: any;81 // istanbul ignore else82 if (Object.keys(provider).indexOf('useValue') !== -1) {83 mockProvider = createValueProvider(provider, provide);84 } else if (Object.keys(provider).indexOf('useExisting') !== -1) {85 mockProvider = provider;86 } else if (Object.keys(provider).indexOf('useClass') !== -1) {87 mockProvider = createClassProvider(provider, provide);88 } else if (Object.keys(provider).indexOf('useFactory') !== -1) {89 mockProvider = helperUseFactory(provide, () => ({}));90 }91 return mockProvider;92};93const isNeverMockFunction = (provide: any): boolean =>94 typeof provide === 'function' && neverMockProvidedFunction.indexOf(provide.name) !== -1;95const isNeverMockToken = (provide: any): boolean =>96 isNgInjectionToken(provide) && neverMockToken.indexOf(provide.toString()) !== -1;97export default (provider: any, useFactory = false): Provider | undefined => {98 const provide = funcGetProvider(provider);99 if (ngMocksUniverse.getResolution(provide) === 'mock') {100 // nothing to do101 } else if (isNeverMockFunction(provide)) {102 return provider;103 } else if (isNeverMockToken(provide)) {104 return undefined;105 }106 // Only pure provides should be cached to avoid their influence on107 // another different declarations.108 const cacheProviders = ngMocksUniverse.flags.has('cacheProvider')109 ? ngMocksUniverse.cacheProviders110 : /* istanbul ignore next */ undefined;111 if (provide === provider && cacheProviders && cacheProviders.has(provide)) {112 return cacheProviders.get(provide);113 }114 return createMockProvider(provider, provide, cacheProviders) || handleProvider(provider, provide, useFactory);...
StoreCaches.ts
Source:StoreCaches.ts
1import {CacheProviders} from "./CacheProviders";2import {CacheProvider} from "./CacheProvider";3import {ICacheKeyCalculator} from "./ICacheKeyCalculator";4import { CacheKeyCalculators } from "./CacheKeyCalculators";5import {Preconditions} from "polar-shared/src/Preconditions";6import {CachedStore} from "./store/cached/CachedStore";7import { IFirestore } from "./store/IFirestore";8/**9 * The general design here is that we have a snapshot interface that mimics10 * Firestore and the main and high level usage pattern.11 *12 */13export namespace StoreCaches {14 export type SnapshotBacking = 'none' | 'IndexedDB';15 export interface SnapshotCacheConfig {16 readonly backing: SnapshotBacking;17 }18 export let config: SnapshotCacheConfig = {19 // backing: 'IndexedDB'20 backing: 'none'21 };22 console.log("Using StoreCache: " + config.backing);23 let cacheProvider: CacheProvider = CacheProviders.create(config.backing);24 /**25 * Purge all data in the snapshot cache using the current configuration26 */27 export async function purge() {28 await cacheProvider.purge();29 }30 /**31 * Configure how the snapshot cache works, whether it's enabled, etc.32 */33 export function configure(newConfig: SnapshotCacheConfig) {34 config = newConfig;35 cacheProvider = CacheProviders.create(config.backing);36 }37 export interface IStoreBuilder {38 readonly build: (delegate: IFirestore) => Promise<IFirestore>;39 }40 export function create(): IStoreBuilder {41 let cacheKeyCalculator: ICacheKeyCalculator | undefined;42 async function build(delegate: IFirestore) {43 Preconditions.assertPresent(delegate, 'delegate');44 cacheKeyCalculator = CacheKeyCalculators.createGeneric();45 switch (config.backing) {46 case "none":47 return delegate;48 case "IndexedDB":49 return CachedStore.create(delegate, CacheProviders.create(config.backing), cacheKeyCalculator!);50 }51 }52 return {53 build54 }55 }...
ListProvidersService.ts
Source:ListProvidersService.ts
1import { inject, injectable } from "tsyringe";2import User from "@modules/users/infra/typeorm/entities/User";3import IUsersRepository from "@modules/users/repositories/IUserRepository";4import ICacheProvider from "@shared/container/providers/CacheProvider/models/ICacheProvider";5import { classToClass } from "class-transformer";6@injectable()7class ListProvidersService {8 constructor(9 @inject("UsersRepository")10 private usersRepository: IUsersRepository,11 @inject("CacheProvider")12 private cacheProvider: ICacheProvider13 ) {}14 public async execute(user_id: string): Promise<User[] | undefined> {15 let cacheProviders = await this.cacheProvider.get<User[]>(16 `providers-list:${user_id}`17 );18 // let cacheProviders = null;19 if (!cacheProviders) {20 console.log("Query DB => Providers List");21 let providers = await this.usersRepository.findAllProviders({22 except_user_id: user_id,23 });24 this.cacheProvider.save(25 `providers-list:${user_id}`,26 classToClass(providers)27 );28 return providers;29 }30 return cacheProviders;31 }32}...
Using AI Code Generation
1import { cacheProviders } from 'ng-mocks';2import { MyComponent } from './my-component';3describe('MyComponent', () => {4 let component: MyComponent;5 let fixture: ComponentFixture<MyComponent>;6 beforeEach(() => {7 TestBed.configureTestingModule({8 imports: [MyModule],9 providers: cacheProviders({10 useValue: { test: 'test' },11 }),12 }).compileComponents();13 fixture = TestBed.createComponent(MyComponent);14 component = fixture.componentInstance;15 fixture.detectChanges();16 });17 it('should create', () => {18 expect(component).toBeTruthy();19 });20});21import { TestBed, ComponentFixture } from '@angular/core/testing';22import { MyComponent } from './my-component';23describe('MyComponent', () => {24 let component: MyComponent;25 let fixture: ComponentFixture<MyComponent>;26 beforeEach(() => {27 TestBed.configureTestingModule({28 imports: [MyModule],29 {30 useValue: { test: 'test' },31 },32 }).compileComponents();33 fixture = TestBed.createComponent(MyComponent);34 component = fixture.componentInstance;35 fixture.detectChanges();36 });37 it('should create', () => {38 expect(component).toBeTruthy();39 });40});41import { TestBed, ComponentFixture } from '@angular/core/testing';42import { MyComponent } from './my-component';43describe('MyComponent', () => {44 let component: MyComponent;45 let fixture: ComponentFixture<MyComponent>;46 beforeEach(() => {47 TestBed.configureTestingModule({48 imports: [MyModule],49 {50 useValue: { test: 'test' },51 },52 }).compileComponents();53 fixture = TestBed.createComponent(MyComponent);54 component = fixture.componentInstance;55 fixture.detectChanges();56 });57 it('should create', () => {58 expect(component).toBeTruthy();59 });60});61import { TestBed, ComponentFixture } from '@angular/core/testing';62import { MyComponent } from './my-component';63describe('MyComponent', () => {64 let component: MyComponent;65 let fixture: ComponentFixture<MyComponent>;66 beforeEach(() => {67 TestBed.configureTestingModule({68 imports: [MyModule],69 {70 useValue: { test: 'test' },71 },72 }).compileComponents();73 fixture = TestBed.createComponent(MyComponent);74 component = fixture.componentInstance;75 fixture.detectChanges();76 });
Using AI Code Generation
1import { cacheProviders } from 'ng-mocks/dist/lib/mock-module/mock-module';2import { cacheProviders } from 'ng-mocks/dist/lib/mock-module/mock-module';3import { cacheProviders } from 'ng-mocks/dist/lib/mock-module/mock-module';4import { cacheProviders } from 'ng-mocks/dist/lib/mock-module/mock-module';5import { cacheProviders } from 'ng-mocks/dist/lib/mock-module/mock-module';6import { cacheProviders } from 'ng-mocks/dist/lib/mock-module/mock-module';
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!!