Best JavaScript code snippet using ng-mocks
retry-async.service.ts
Source:retry-async.service.ts
1import angular from "angular";2export type RetryOptions = {3 delay: number;4 maxAttempts: number;5 isExponentialBackoffOn: boolean;6 // TODO: Add support for these two later7 // isJitterOn?: boolean;8 // errorToRetryPattern?: RegExp;9 excludeFunctionPattern?: RegExp;10};11export class RetryAsyncService {12 private options;13 withOptions(options: RetryOptions): RetryAsyncService {14 this.options = options;15 return this;16 }17 /**18 * Wrap all functions with retry logic in 'obj' whether it's through the first prototype link19 * or without a prototype. This will only retry on 5xx http codes20 *21 * Function names will be excluded based on the excludeFunctionPattern in RetryOptions22 * @param obj23 */24 wrap(obj: any) {25 let functions = Object.getOwnPropertyNames(obj)26 .filter((i) => typeof obj[i] === "function")27 .filter((p) => !this.options.excludeFunctionPattern?.test(p));28 let prototype;29 if (functions.length == 0) {30 prototype = Object.getPrototypeOf(obj);31 let prototypeKeys = Object.keys(prototype);32 prototypeKeys = prototypeKeys.filter(33 (p) => !this.options.excludeFunctionPattern?.test(p)34 );35 functions = prototypeKeys;36 }37 functions.forEach((functionName) => {38 const originalFunction = prototype39 ? prototype[functionName]40 : obj[functionName];41 async function retryWrapper(...args) {42 const actualArgs = Array.prototype.slice.call(args, 1);43 const callback = args[0];44 const options: RetryOptions = obj[functionName].retryOptions;45 let attempts = 0;46 let delay = 0;47 async function attempt(obj, args) {48 try {49 attempts++;50 return await callback.apply(obj, args);51 } catch (e: any) {52 const serverCodePattern = /^5/;53 if (serverCodePattern.test(e.body?.status)) {54 delay = options.isExponentialBackoffOn55 ? options.delay * Math.pow(2, attempts - 1)56 : options.delay;57 console.log("Retrying call in " + delay + "ms");58 return new Promise((resolve, reject) => {59 if (attempts < options.maxAttempts) {60 setTimeout(async () => {61 try {62 const val = await attempt(obj, args);63 resolve(val);64 } catch (error) {65 reject(error);66 }67 }, delay);68 } else {69 e._attempts = attempts;70 e._lastDelay = delay;71 reject(e);72 }73 });74 } else {75 throw e;76 }77 }78 }79 return await attempt(obj, actualArgs);80 }81 prototype82 ? (prototype[functionName] = retryWrapper.bind(obj, originalFunction))83 : (obj[functionName] = retryWrapper.bind(obj, originalFunction));84 prototype85 ? (prototype[functionName].retryOptions = this.options)86 : (obj[functionName].retryOptions = this.options);87 });88 return obj;89 }90}91angular92 .module("app.ui_shared_services")93 .service("RetryAsyncService", RetryAsyncService);...
intelli-di-ioc.js
Source:intelli-di-ioc.js
1import React from 'react';2import Helpers from './helpers';3export class IntelliDI {4 constructor(dependencies) {5 this.deps = {};6 this.processDeps(dependencies);7 }8 processDeps(dependencies) {9 dependencies.forEach(dep => {10 this.distinguishModules(dep);11 });12 }13 /* Filters between CommonJS modules and ES6 modules including default and named classes. */14 distinguishModules(dep) {15 const instDep = eval(`require("./${dep.file}")`);16 // console.log(instDep);17 //TODO: Refactor multiple if statement.18 if ((!dep.name || dep.name.toLowerCase() === 'default') && instDep['default']) {19 this.createDeps(instDep['default'],20 this.distinguishReactComponent(instDep['default']));21 } else if (dep.name) {22 this.createDeps(instDep[dep.name],23 this.distinguishReactComponent(instDep[dep.name]));24 } else if (typeof(instDep) === 'function') {25 this.createDeps(instDep,26 this.distinguishReactComponent(instDep));27 } else {28 throw new Error(`Dependency: ${dep} does not exist!`);29 }30 }31 distinguishReactComponent(dep) {32 const allObjectKeys = obj => {33 const result = [];34 for (const prop in obj) {35 result.push(prop);36 }37 return result;38 }39 const arrIncludes = (arr, value) => {40 return (arr.indexOf(value) > -1);41 }42 const prototypeKeys = allObjectKeys(dep.prototype);43 const keys = allObjectKeys(dep);44 if (arrIncludes(prototypeKeys, 'isReactComponent')45 || (arrIncludes(prototypeKeys, 'constructor') && arrIncludes(prototypeKeys, 'render'))46 || arrIncludes(keys, 'propTypes')47 || dep.prototype instanceof React.Component) {48 return true;49 }50 return false;51 }52 createDeps(dep, possiblyReact) {53 if (!possiblyReact) {54 const instantiate = new Function('Dep', 'return new Dep();');55 const instance = instantiate(dep);56 this.deps[`${instance.constructor.name.toLowerCase()}`] = instance;57 } else { 58 (dep.name)59 ? this.deps[`${Helpers.toCamelCase(dep.name)}`] = dep60 : this.deps[`${Helpers.toCamelCase(dep.displayName)}`] = dep;61 }62 } ...
entries.ts
Source:entries.ts
1import { isNil } from '../predicates/index.js';2const objectOwnProps = Object.getOwnPropertyNames(Object.getPrototypeOf({}));3const _keys = (obj: any, enumOnly: boolean, followProto: boolean): string[] => {4 if (!followProto) {5 if (enumOnly) {6 return Object.keys(obj);7 }8 return Object.getOwnPropertyNames(obj);9 }10 const props = new Set<any>();11 if (enumOnly) {12 for (const prop in obj) {13 props.add(prop);14 }15 } else {16 const { getOwnPropertyNames: fetchKeys } = Object;17 do {18 const ownKeys = fetchKeys(obj);19 for (let i = 0; i < ownKeys.length; ++i) {20 props.add(ownKeys[i]);21 }22 const prototype = Object.getPrototypeOf(obj);23 if (prototype) {24 const prototypeKeys = fetchKeys(prototype);25 for (let i = 0; i < prototypeKeys.length; ++i) {26 props.add(prototypeKeys[i]);27 }28 }29 obj = obj.__proto__;30 } while (obj);31 for (let i = 0; i < objectOwnProps.length; ++i) {32 props.delete(objectOwnProps[i]); // what if the props are modified?33 }34 }35 return [...props];36};37export const keys = (38 obj: any,39 { enumOnly = true, followProto = false, all = false } = {},40) => {41 if (isNil(obj)) {42 return [];43 }44 if (all) {45 [enumOnly, followProto] = [false, true];46 }47 return _keys(obj, enumOnly, followProto);48};49// TODO: tests50export const values = (51 obj: any,52 { enumOnly = true, followProto = false, all = false } = {},53) => {54 if (isNil(obj)) {55 return [];56 }57 if (all) {58 [enumOnly, followProto] = [false, true];59 }60 if (!followProto && enumOnly) {61 return Object.values(obj);62 }63 const k = _keys(obj, enumOnly, followProto);64 for (let i = 0; i < k.length; ++i) {65 k[i] = obj[k[i] as string];66 }67 return k;68};69// TODO: tests70export const entries = (71 obj: any,72 { enumOnly = true, followProto = false, all = false } = {},73) => {74 if (isNil(obj)) {75 return [];76 }77 if (all) {78 [enumOnly, followProto] = [false, true];79 }80 if (!followProto && enumOnly) {81 return Object.entries(obj);82 }83 const k = _keys(obj, enumOnly, followProto);84 const result = new Array(k.length);85 for (let i = 0; i < k.length; ++i) {86 const key = k[i];87 result[i] = [key, obj[key as string]];88 }89 return result;...
Using AI Code Generation
1import { prototypeKeys } from 'ng-mocks';2import { mockProvider } from 'ng-mocks';3import { TestComponent } from './test.component';4import { TestService } from './test.service';5describe('TestComponent', () => {6 let component: TestComponent;7 let fixture: ComponentFixture<TestComponent>;8 beforeEach(async(() => {9 TestBed.configureTestingModule({10 providers: [mockProvider(TestService)]11 })12 .compileComponents();13 }));14 beforeEach(() => {15 fixture = TestBed.createComponent(TestComponent);16 component = fixture.componentInstance;17 fixture.detectChanges();18 });19 it('should create', () => {20 expect(component).toBeTruthy();21 });22 it('should have a method called testMethod', () => {23 expect(prototypeKeys(TestService).indexOf('testMethod')).toBeGreaterThan(-1);24 });25});26import { Injectable } from '@angular/core';27@Injectable()28export class TestService {29 testMethod(): string {30 return 'test';31 }32}33import { Component, OnInit } from '@angular/core';34import { TestService } from './test.service';35@Component({36})37export class TestComponent implements OnInit {38 constructor(private testService: TestService) { }39 ngOnInit() {40 }41 testMethod() {42 return this.testService.testMethod();43 }44}45 {{testMethod()}}46div {47 color: red;48}49import { prototypeKeys } from 'ng-mocks';50import { mockProvider } from 'ng-mocks';51import { TestComponent } from './test.component';52import { TestService } from './test.service';53describe('TestComponent', () => {54 let component: TestComponent;55 let fixture: ComponentFixture<TestComponent>;56 beforeEach(async(() => {57 TestBed.configureTestingModule({58 providers: [mockProvider(TestService)]59 })60 .compileComponents();61 }));62 beforeEach(() => {63 fixture = TestBed.createComponent(TestComponent);64 component = fixture.componentInstance;65 fixture.detectChanges();66 });67 it('should create', () => {68 expect(component).toBeTruthy();69 });
Using AI Code Generation
1import { prototypeKeys } from 'ng-mocks';2export class Test {3 constructor() {4 prototypeKeys(Test);5 }6}7import { Test } from './test';8describe('Test', () => {9 it('should return the prototype keys of a class', () => {10 const test = new Test();11 expect(test.prototypeKeys(Test)).toEqual(['constructor']);12 });13});14import { prototypeKeys } from 'ng-mocks';15class Test {16 constructor() {}17}18const test = new Test();19console.log(test.prototypeKeys(Test));
Using AI Code Generation
1import { prototypeKeys } from 'ng-mocks';2import { MockService } from 'ng-mocks';3describe('mock service', () => {4 it('should mock a service', () => {5 const service = MockService(SomeService);6 expect(service).toBeTruthy();7 });8});9import { MockComponent } from 'ng-mocks';10describe('mock component', () => {11 it('should mock a component', () => {12 const component = MockComponent(SomeComponent);13 expect(component).toBeTruthy();14 });15});16import { MockDirective } from 'ng-mocks';17describe('mock directive', () => {18 it('should mock a directive', () => {19 const directive = MockDirective(SomeDirective);20 expect(directive).toBeTruthy();21 });22});23import { MockPipe } from 'ng-mocks';24describe('mock pipe', () => {25 it('should mock a pipe', () => {26 const pipe = MockPipe(SomePipe);27 expect(pipe).toBeTruthy();28 });29});30import { MockModule } from 'ng-mocks';31describe('mock module', () => {32 it('should mock a module', () => {33 const module = MockModule(SomeModule);34 expect(module).toBeTruthy();35 });36});37import { MockNg } from 'ng-mocks';38describe('mock ng module', () => {39 it('should mock a ng module', () => {40 const ngModule = MockNg(SomeNgModule);41 expect(ngModule).toBeTruthy();42 });43});44import { MockNg } from 'ng-mocks';45describe('mock ng module', () => {46 it('should mock a ng module', () => {47 const ngModule = MockNg(SomeNgModule);48 expect(ngModule).toBeTruthy();49 });50});51import { MockNg } from 'ng-mocks';52describe('mock ng module', () => {53 it('should mock a ng module', () => {54 const ngModule = MockNg(SomeNgModule);55 expect(ngModule).toBeTruthy();56 });57});58import {
Using AI Code Generation
1const mock = require('ng-mocks');2mock.prototypeKeys('test', {3});4const jasmine = require('jasmine');5jasmine.prototypeKeys('test', {6});7const jest = require('jest');8jest.prototypeKeys('test', {9});10const test = require('test');11describe('test', () => {12 it('should have prototype keys', () => {13 expect(test).toHavePrototypeKeys(['key1', 'key2']);14 });15});16const test = require('test');17describe('test', () => {18 it('should have prototype keys', () => {19 expect(test).toHavePrototypeKeys({20 });21 });22});23const test = require('test');24describe('test', () => {25 it('should have prototype keys', () => {26 expect(test).toHavePrototypeKeys(['key1', 'key2']);27 });28});29const test = require('test');30describe('test', () => {31 it('should have prototype keys', () => {32 expect(test).toHavePrototypeKeys({33 });34 });35});36const test = require('test');37describe('test', () => {38 it('should have prototype keys', () => {39 expect(test).toHavePrototypeKeys(['key1', 'key2']);40 });41});42const test = require('test');43describe('test', () => {44 it('should have prototype keys', () => {45 expect(test).toHavePrototypeKeys({46 });47 });48});49const test = require('test');50describe('test', () => {51 it('should have prototype keys', () => {52 expect(test).toHavePrototypeKeys(['key1', 'key2']);53 });
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!!