Best JavaScript code snippet using ng-mocks
index.d.ts
Source:index.d.ts
1// Type definitions for rest.js v1.3.12// Project: https://github.com/cujojs/rest3// Definitions by: Wim Looman <https://github.com/Nemo157>4// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped5/// <reference types="when" />6declare module "rest" {7 import when = require("when");8 export = rest;9 function rest(path: string): rest.ResponsePromise;10 function rest(request: rest.Request): rest.ResponsePromise;11 namespace rest {12 export function setDefaultClient(client: Client): void;13 export function getDefaultClient(): Client;14 export function resetDefaultClient(): void;15 export function wrap<T>(interceptor: Interceptor<T>, config?: T): Client;16 export interface Request {17 method?: string;18 path?: string;19 params?: any;20 headers?: any;21 entity?: any;22 canceled?: boolean;23 cancel?: () => void;24 originator?: (request?: Request) => ResponsePromise;25 mixin?: any;26 }27 export interface Status {28 code: number;29 text?: string;30 }31 export interface Headers {32 [index: string]: any // string or string[]33 }34 export interface Response {35 request: Request;36 raw: any;37 status: Status;38 headers: Headers;39 entity: any;40 }41 export interface ResponsePromise extends when.Promise<Response> {42 entity(): when.Promise<any>;43 status(): when.Promise<number>;44 headers(): when.Promise<Headers>;45 header(headerName: string): when.Promise<any>; // string or string[]46 }47 export interface Interceptor<T> {48 (parent?: Client, config?: T): Client;49 }50 export interface Client {51 (path: string): ResponsePromise;52 (request: Request): ResponsePromise;53 skip(): Client;54 wrap<T>(interceptor: Interceptor<T>, config?: T): Client;55 }56 export interface Meta {57 client: Client;58 arguments: any;59 }60 }61}62declare module "rest/interceptor" {63 import when = require("when");64 import rest = require("rest");65 function interceptor<T, U>(config: interceptor.Config<T, U>): rest.Interceptor<T>;66 namespace interceptor {67 interface Config<T, U> {68 init?: (config: T) => U;69 request?: (request: rest.Request, config: U, meta: rest.Meta) => rest.Request | when.Promise<rest.Request>;70 response?: (response: rest.Response, config: U, meta: rest.Meta) => rest.Response | when.Promise<rest.Response>;71 success?: (response: rest.Response, config: U, meta: rest.Meta) => rest.Response | when.Promise<rest.Response>;72 error?: (response: rest.Response, config: U, meta: rest.Meta) => rest.Response | when.Promise<rest.Response>;73 }74 }75 export = interceptor;76}77declare module "rest/interceptor/defaultRequest" {78 import rest = require("rest");79 var defaultRequest: rest.Interceptor<defaultRequest.Config>;80 namespace defaultRequest {81 interface Config {82 method?: string;83 path?: string;84 params?: any;85 headers?: any;86 entity?: any;87 mixin?: any;88 }89 }90 export = defaultRequest;91}92declare module "rest/interceptor/hateoas" {93 import rest = require("rest");94 var hateoas: rest.Interceptor<hateoas.Config>;95 namespace hateoas {96 interface Config {97 target?: string;98 client?: rest.Client;99 }100 }101 export = hateoas;102}103declare module "rest/interceptor/location" {104 import rest = require("rest");105 var location: rest.Interceptor<location.Config>;106 namespace location {107 interface Config {108 client?: rest.Client;109 code?: number;110 }111 }112 export = location;113}114declare module "rest/interceptor/mime" {115 import rest = require("rest");116 import registry = require("rest/mime/registry");117 var mime: rest.Interceptor<mime.Config>;118 namespace mime {119 interface Config {120 mime?: string;121 accept?: string;122 registry?: registry.Registry;123 permissive?: boolean;124 }125 }126 export = mime;127}128declare module "rest/interceptor/pathPrefix" {129 import rest = require("rest");130 var pathPrefix: rest.Interceptor<pathPrefix.Config>;131 namespace pathPrefix {132 interface Config {133 prefix?: string;134 }135 }136 export = pathPrefix;137}138declare module "rest/interceptor/basicAuth" {139 import rest = require("rest");140 var basicAuth: rest.Interceptor<basicAuth.Config>;141 namespace basicAuth {142 interface Config {143 username?: string;144 password?: string;145 }146 }147 export = basicAuth;148}149declare module "rest/interceptor/oAuth" {150 import rest = require("rest");151 var oAuth: rest.Interceptor<oAuth.Config>;152 namespace oAuth {153 interface DismissWindow {154 (): void;155 }156 interface Config {157 token?: string;158 clientId?: string;159 scope?: string;160 authorizationUrl?: string;161 redirectUrl?: string;162 windowStrategy?: (url: string) => DismissWindow;163 oAuthCallback?: (hash: string) => void;164 oAuthCallbackName?: string;165 }166 }167 export = oAuth;168}169declare module "rest/interceptor/csrf" {170 import rest = require("rest");171 var csrf: rest.Interceptor<csrf.Config>;172 namespace csrf {173 interface Config {174 name?: string;175 token?: string;176 }177 }178 export = csrf;179}180declare module "rest/interceptor/errorCode" {181 import rest = require("rest");182 var errorCode: rest.Interceptor<errorCode.Config>;183 namespace errorCode {184 interface Config {185 code?: number;186 }187 }188 export = errorCode;189}190declare module "rest/interceptor/retry" {191 import rest = require("rest");192 var retry: rest.Interceptor<retry.Config>;193 namespace retry {194 interface Config {195 initial?: number;196 multiplier?: number;197 max?: number;198 }199 }200 export = retry;201}202declare module "rest/interceptor/template" {203 import rest = require("rest");204 var template: rest.Interceptor<template.Config>;205 namespace template {206 interface Config {207 template?: string;208 params?: {209 [name: string]: any;210 };211 }212 }213 export = template;214}215declare module "rest/interceptor/timeout" {216 import rest = require("rest");217 var timeout: rest.Interceptor<timeout.Config>;218 namespace timeout {219 interface Config {220 timeout?: number;221 transient?: boolean;222 }223 }224 export = timeout;225}226declare module "rest/interceptor/jsonp" {227 import rest = require("rest");228 var jsonp: rest.Interceptor<jsonp.Config>;229 namespace jsonp {230 interface Config {231 callback?: {232 param?: string;233 prefix?: string;234 name?: string;235 }236 }237 }238 export = jsonp;239}240declare module "rest/interceptor/ie/xdomain" {241 import rest = require("rest");242 var xdomain: rest.Interceptor<{}>;243 export = xdomain;244}245declare module "rest/interceptor/ie/xhr" {246 import rest = require("rest");247 var xhr: rest.Interceptor<{}>;248 export = xhr;249}250declare module "rest/mime/registry" {251 import when = require("when");252 var registry: registry.Registry;253 namespace registry {254 interface MIMEConverter {255 read(value: string): any | when.Promise<any>;256 write(value: any): string | when.Promise<string>;257 }258 interface Registry {259 lookup(mimeType: string): when.Promise<MIMEConverter>;260 register(mimeType: string, converter: MIMEConverter): void;261 }262 }263 export = registry;264}265declare module "rest/client/xhr" {266 import rest = require("rest");267 var xhr: rest.Client;268 export = xhr;269}270declare module "rest/client/node" {271 import rest = require("rest");272 var node: rest.Client;273 export = node;274}275declare module "rest/client/jsonp" {276 import rest = require("rest");277 var jsonp: rest.Client;278 export = jsonp;279}280declare module "rest/client/xdr" {281 import rest = require("rest");282 var xdr: rest.Client;283 export = xdr;...
log_interceptor.test.js
Source:log_interceptor.test.js
1/*2 * Licensed to Elasticsearch B.V. under one or more contributor3 * license agreements. See the NOTICE file distributed with4 * this work for additional information regarding copyright5 * ownership. Elasticsearch B.V. licenses this file to you under6 * the Apache License, Version 2.0 (the "License"); you may7 * not use this file except in compliance with the License.8 * You may obtain a copy of the License at9 *10 * http://www.apache.org/licenses/LICENSE-2.011 *12 * Unless required by applicable law or agreed to in writing,13 * software distributed under the License is distributed on an14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY15 * KIND, either express or implied. See the License for the16 * specific language governing permissions and limitations17 * under the License.18 */19import { LogInterceptor } from './log_interceptor';20function stubClientErrorEvent(errorMeta) {21 const error = new Error();22 Object.assign(error, errorMeta);23 return {24 event: 'error',25 pid: 1234,26 timestamp: Date.now(),27 tags: ['connection', 'client', 'error'],28 error,29 };30}31const stubEconnresetEvent = () => stubClientErrorEvent({ code: 'ECONNRESET' });32const stubEpipeEvent = () => stubClientErrorEvent({ errno: 'EPIPE' });33const stubEcanceledEvent = () => stubClientErrorEvent({ errno: 'ECANCELED' });34function assertDowngraded(transformed) {35 expect(!!transformed).toBe(true);36 expect(transformed).toHaveProperty('event', 'log');37 expect(transformed).toHaveProperty('tags');38 expect(transformed.tags).not.toContain('error');39}40describe('server logging LogInterceptor', () => {41 describe('#downgradeIfEconnreset()', () => {42 it('transforms ECONNRESET events', () => {43 const interceptor = new LogInterceptor();44 const event = stubEconnresetEvent();45 assertDowngraded(interceptor.downgradeIfEconnreset(event));46 });47 it('does not match if the tags are not in order', () => {48 const interceptor = new LogInterceptor();49 const event = stubEconnresetEvent();50 event.tags = [...event.tags.slice(1), event.tags[0]];51 expect(interceptor.downgradeIfEconnreset(event)).toBe(null);52 });53 it('ignores non ECONNRESET events', () => {54 const interceptor = new LogInterceptor();55 const event = stubClientErrorEvent({ errno: 'not ECONNRESET' });56 expect(interceptor.downgradeIfEconnreset(event)).toBe(null);57 });58 it('ignores if tags are wrong', () => {59 const interceptor = new LogInterceptor();60 const event = stubEconnresetEvent();61 event.tags = ['different', 'tags'];62 expect(interceptor.downgradeIfEconnreset(event)).toBe(null);63 });64 });65 describe('#downgradeIfEpipe()', () => {66 it('transforms EPIPE events', () => {67 const interceptor = new LogInterceptor();68 const event = stubEpipeEvent();69 assertDowngraded(interceptor.downgradeIfEpipe(event));70 });71 it('does not match if the tags are not in order', () => {72 const interceptor = new LogInterceptor();73 const event = stubEpipeEvent();74 event.tags = [...event.tags.slice(1), event.tags[0]];75 expect(interceptor.downgradeIfEpipe(event)).toBe(null);76 });77 it('ignores non EPIPE events', () => {78 const interceptor = new LogInterceptor();79 const event = stubClientErrorEvent({ errno: 'not EPIPE' });80 expect(interceptor.downgradeIfEpipe(event)).toBe(null);81 });82 it('ignores if tags are wrong', () => {83 const interceptor = new LogInterceptor();84 const event = stubEpipeEvent();85 event.tags = ['different', 'tags'];86 expect(interceptor.downgradeIfEpipe(event)).toBe(null);87 });88 });89 describe('#downgradeIfEcanceled()', () => {90 it('transforms ECANCELED events', () => {91 const interceptor = new LogInterceptor();92 const event = stubEcanceledEvent();93 assertDowngraded(interceptor.downgradeIfEcanceled(event));94 });95 it('does not match if the tags are not in order', () => {96 const interceptor = new LogInterceptor();97 const event = stubEcanceledEvent();98 event.tags = [...event.tags.slice(1), event.tags[0]];99 expect(interceptor.downgradeIfEcanceled(event)).toBe(null);100 });101 it('ignores non ECANCELED events', () => {102 const interceptor = new LogInterceptor();103 const event = stubClientErrorEvent({ errno: 'not ECANCELLED' });104 expect(interceptor.downgradeIfEcanceled(event)).toBe(null);105 });106 it('ignores if tags are wrong', () => {107 const interceptor = new LogInterceptor();108 const event = stubEcanceledEvent();109 event.tags = ['different', 'tags'];110 expect(interceptor.downgradeIfEcanceled(event)).toBe(null);111 });112 });113 describe('#downgradeIfHTTPSWhenHTTP', () => {114 it('transforms https requests when serving http errors', () => {115 const interceptor = new LogInterceptor();116 const event = stubClientErrorEvent({ message: 'Parse Error', code: 'HPE_INVALID_METHOD' });117 assertDowngraded(interceptor.downgradeIfHTTPSWhenHTTP(event));118 });119 it('ignores non events', () => {120 const interceptor = new LogInterceptor();121 const event = stubClientErrorEvent({122 message: 'Parse Error',123 code: 'NOT_HPE_INVALID_METHOD',124 });125 expect(interceptor.downgradeIfEcanceled(event)).toBe(null);126 });127 });128 describe('#downgradeIfHTTPWhenHTTPS', () => {129 it('transforms http requests when serving https errors', () => {130 const message =131 '40735139278848:error:1407609C:SSL routines:SSL23_GET_CLIENT_HELLO:http request:../deps/openssl/openssl/ssl/s23_srvr.c:394';132 const interceptor = new LogInterceptor();133 const event = stubClientErrorEvent({ message });134 assertDowngraded(interceptor.downgradeIfHTTPWhenHTTPS(event));135 });136 it('ignores non events', () => {137 const interceptor = new LogInterceptor();138 const event = stubClientErrorEvent({ message: 'Not error' });139 expect(interceptor.downgradeIfEcanceled(event)).toBe(null);140 });141 });...
index.ts
Source:index.ts
1/* "Barrel" of Http Interceptors */2import { HTTP_INTERCEPTORS } from '@angular/common/http';34import { AuthInterceptor } from './auth-interceptor';5import { CachingInterceptor } from './caching-interceptor';6import { CustomJsonInterceptor , CustomJsonParser, JsonParser} from './custom-json-interceptor';7import { EnsureHttpsInterceptor } from './ensure-https-interceptor';8import { LoggingInterceptor } from './logging-interceptor';9import { NoopInterceptor } from './noop-interceptor';10import { TrimNameInterceptor } from './trim-name-interceptor';11import { UploadInterceptor } from './upload-interceptor';12import { RetryInterceptor } from './retry-interceptor';1314/** Http interceptor providers in outside-in order */15export const httpInterceptorProviders = [16 { provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true },17 { provide: HTTP_INTERCEPTORS, useClass: CustomJsonInterceptor, multi: true },18 { provide: JsonParser, useClass: CustomJsonParser },1920 { provide: HTTP_INTERCEPTORS, useClass: EnsureHttpsInterceptor, multi: true },21 { provide: HTTP_INTERCEPTORS, useClass: TrimNameInterceptor, multi: true },22 { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },23 { provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true },24 { provide: HTTP_INTERCEPTORS, useClass: UploadInterceptor, multi: true },25 { provide: HTTP_INTERCEPTORS, useClass: CachingInterceptor, multi: true },2627];282930/*31Copyright Google LLC. All Rights Reserved.32Use of this source code is governed by an MIT-style license that33can be found in the LICENSE file at https://angular.io/license
...
Using AI Code Generation
1import { MockBuilder, MockRender, jasmine } from 'ng-mocks';2describe('AppComponent', () => {3 beforeEach(() => MockBuilder(AppComponent));4 it('should create the app', () => {5 const fixture = MockRender(AppComponent);6 const app = fixture.point.componentInstance;7 expect(app).toBeTruthy();8 });9});10import { AppComponent } from './app.component';11import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';12import { ApiService } from './api.service';13describe('AppComponent', () => {14 beforeEach(() => MockBuilder(AppComponent).mock(ApiService));15 it('should create the app', () => {16 const fixture = MockRender(AppComponent);17 const app = fixture.point.componentInstance;18 expect(app).toBeTruthy();19 });20 it('should call api service', () => {21 const fixture = MockRender(AppComponent);22 const app = fixture.point.componentInstance;23 const api = ngMocks.findInstance(ApiService);24 spyOn(api, 'callApi').and.callThrough();25 app.callApi();26 expect(api.callApi).toHaveBeenCalled();27 });28});29import { Injectable } from '@angular/core';30@Injectable()31export class ApiService {32 callApi() {33 return 'api response';34 }35}36import { Component } from '@angular/core';37import { ApiService } from './api.service';38@Component({39})40export class AppComponent {41 title = 'ng-mocks';42 constructor(private api: ApiService) {}43 callApi() {44 console.log(this.api.callApi());45 }46}47<button (click)="callApi()">Call API</button>48import { Component, Input } from '@angular/core';49@Component({50 <h1>{{ title }}</h1>51})52export class HeaderComponent {53 @Input() title: string;54}55import { HeaderComponent } from './app-header.component';56import { MockBuilder, MockRender
Using AI Code Generation
1import { mockInterceptor } from 'ng-mocks';2import { HttpInterceptor } from '@angular/common/http';3import { TestBed } from '@angular/core/testing';4import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';5import { AppComponent } from './app.component';6describe('AppComponent', () => {7 let httpMock: HttpTestingController;8 let interceptor: HttpInterceptor;9 beforeEach(async () => {10 await TestBed.configureTestingModule({11 imports: [HttpClientTestingModule]12 }).compileComponents();13 httpMock = TestBed.inject(HttpTestingController);14 interceptor = mockInterceptor([{15 request: {16 },17 response: {18 },19 }]);20 });21 it('should create the app', () => {22 const fixture = TestBed.createComponent(AppComponent);23 const app = fixture.componentInstance;24 expect(app).toBeTruthy();25 });26 it(`should have as title 'ng-mocks-demo'`, () => {27 const fixture = TestBed.createComponent(AppComponent);28 const app = fixture.componentInstance;29 expect(app.title).toEqual('ng-mocks-demo');30 });31 it('should render title', () => {32 const fixture = TestBed.createComponent(AppComponent);33 fixture.detectChanges();34 const compiled = fixture.nativeElement;35 expect(compiled.querySelector('.content span').textContent).toContain('ng-mocks-demo app is running!');36 });37 it('should render title', () => {38 const fixture = TestBed.createComponent(AppComponent);39 fixture.detectChanges();40 const compiled = fixture.nativeElement;41 expect(compiled.querySelector('.content span').textContent).toContain('ng-mocks-demo app is running!');42 });43 it('should render title', () => {44 const fixture = TestBed.createComponent(AppComponent);45 fixture.detectChanges();46 const compiled = fixture.nativeElement;47 expect(compiled.querySelector('.content span').textContent).toContain('ng-mocks-demo app is running!');48 });49 it('should render title', () => {50 const fixture = TestBed.createComponent(AppComponent);51 fixture.detectChanges();52 const compiled = fixture.nativeElement;53 expect(compiled.querySelector('.content span').textContent).toContain('ng-mocks-demo app is running!');54 });55 it('should render title', () => {56 const fixture = TestBed.createComponent(AppComponent);57 fixture.detectChanges();58 const compiled = fixture.nativeElement;
Using AI Code Generation
1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2describe('test', () => {3 beforeEach(() => MockBuilder().mock(InterceptorService, {4 get: () => {5 return of({ name: 'test' });6 }7 }));8 it('should test', () => {9 const fixture = MockRender(HomeComponent);10 expect(ngMocks.formatText(fixture)).toContain('test');11 });12});13@Injectable()14export class InterceptorService {15 constructor(private http: HttpClient) {}16 get(): Observable<any> {17 }18}19@Component({20})21export class HomeComponent implements OnInit {22 user$: Observable<any>;23 constructor(private service: InterceptorService) {}24 ngOnInit() {25 this.user$ = this.service.get();26 }27}28 <span *ngIf="user$ | async as user">{{ user.name }}</span>29beforeEach(() => MockBuilder().mock(InterceptorService, {30 get: () => {31 return of({ name: 'test' });32 }33}));34beforeEach(() => MockBuilder().mock(HttpClient, {35 get: () => {36 return of({ name: 'test' });37 }38}));39beforeEach(() => MockBuilder().mock(HttpClientModule, {40 get: () => {41 return of({ name: 'test' });42 }43}));44beforeEach(() => MockBuilder().mock(HttpClientModule, {45 get: () => {46 return of({ name: 'test' });47 }48}));49beforeEach(() => {
Using AI Code Generation
1(function () {2 'use strict';3 angular.module('app', ['ng-mocks']).run(function (interceptor) {4 interceptor.whenGET('/api/test').respond('Hello World');5 });6})();7(function () {8 'use strict';9 angular.module('app', ['ng-mocks']).run(function (interceptor) {10 interceptor.whenGET('/api/test').respond('Hello World');11 });12})();13(function () {14 'use strict';15 angular.module('app', ['ngMock']).run(function (httpBackend) {16 httpBackend.whenGET('/api/test').respond('Hello World');17 });18})();19(function () {20 'use strict';21 angular.module('app', ['ngMock']).run(function ($httpBackend) {22 $httpBackend.whenGET('/api/test').respond('Hello World');23 });24})();25(function () {26 'use strict';27 angular.module('app', ['ngMock']).run(function (httpBackend) {28 httpBackend.whenGET('/api/test').respond('Hello World');29 });30})();31(function () {32 'use strict';33 angular.module('app', ['ngMock']).run(function ($httpBackend) {34 $httpBackend.whenGET('/api/test').respond('Hello World');35 });36})();37(function () {38 'use strict';39 angular.module('app', ['ngMock']).run(function (httpBackend) {40 httpBackend.whenGET('/api/test').respond('Hello World');41 });42})();43(function () {44 'use strict';45 angular.module('app', ['ngMock']).run(function ($httpBackend) {46 $httpBackend.whenGET('/api/test').respond('Hello World');47 });48})();49(function () {50 'use strict';51 angular.module('app', ['ng
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!!