Best JavaScript code snippet using ng-mocks
jsonpack.js
Source:jsonpack.js
1/*2 Copyright (c) 2013, Rodrigo González, Sapienlab All Rights Reserved.3 Available via MIT LICENSE. See https://github.com/roro89/jsonpack/blob/master/LICENSE.md for details.4 */5(function(define) {6 define([], function() {7 var TOKEN_TRUE = -1;8 var TOKEN_FALSE = -2;9 var TOKEN_NULL = -3;10 var TOKEN_EMPTY_STRING = -4;11 var TOKEN_UNDEFINED = -5;12 var pack = function(json, options) {13 // Canonizes the options14 options = options || {};15 // A shorthand for debugging16 var verbose = options.verbose || false;17 verbose && console.log('Normalize the JSON Object');18 // JSON as Javascript Object (Not string representation)19 json = typeof json === 'string' ? this.JSON.parse(json) : json;20 verbose && console.log('Creating a empty dictionary');21 // The dictionary22 var dictionary = {23 strings : [],24 integers : [],25 floats : []26 };27 verbose && console.log('Creating the AST');28 // The AST29 var ast = (function recursiveAstBuilder(item) {30 verbose && console.log('Calling recursiveAstBuilder with ' + this.JSON.stringify(item));31 // The type of the item32 var type = typeof item;33 // Case 7: The item is null34 if (item === null) {35 return {36 type : 'null',37 index : TOKEN_NULL38 };39 }40 41 //add undefined 42 if (typeof item === 'undefined') {43 return {44 type : 'undefined',45 index : TOKEN_UNDEFINED46 };47 }48 // Case 1: The item is Array Object49 if ( item instanceof Array) {50 // Create a new sub-AST of type Array (@)51 var ast = ['@'];52 // Add each items53 for (var i in item) {54 55 if (!item.hasOwnProperty(i)) continue;56 ast.push(recursiveAstBuilder(item[i]));57 }58 // And return59 return ast;60 }61 // Case 2: The item is Object62 if (type === 'object') {63 // Create a new sub-AST of type Object ($)64 var ast = ['$'];65 // Add each items66 for (var key in item) {67 if (!item.hasOwnProperty(key))68 continue;69 ast.push(recursiveAstBuilder(key));70 ast.push(recursiveAstBuilder(item[key]));71 }72 // And return73 return ast;74 }75 // Case 3: The item empty string76 if (item === '') {77 return {78 type : 'empty',79 index : TOKEN_EMPTY_STRING80 };81 }82 // Case 4: The item is String83 if (type === 'string') {84 // The index of that word in the dictionary85 var index = _indexOf.call(dictionary.strings, item);86 // If not, add to the dictionary and actualize the index87 if (index == -1) {88 dictionary.strings.push(_encode(item));89 index = dictionary.strings.length - 1;90 }91 // Return the token92 return {93 type : 'strings',94 index : index95 };96 }97 // Case 5: The item is integer98 if (type === 'number' && item % 1 === 0) {99 // The index of that number in the dictionary100 var index = _indexOf.call(dictionary.integers, item);101 // If not, add to the dictionary and actualize the index102 if (index == -1) {103 dictionary.integers.push(_base10To36(item));104 index = dictionary.integers.length - 1;105 }106 // Return the token107 return {108 type : 'integers',109 index : index110 };111 }112 // Case 6: The item is float113 if (type === 'number') {114 // The index of that number in the dictionary115 var index = _indexOf.call(dictionary.floats, item);116 // If not, add to the dictionary and actualize the index117 if (index == -1) {118 // Float not use base 36119 dictionary.floats.push(item);120 index = dictionary.floats.length - 1;121 }122 // Return the token123 return {124 type : 'floats',125 index : index126 };127 }128 // Case 7: The item is boolean129 if (type === 'boolean') {130 return {131 type : 'boolean',132 index : item ? TOKEN_TRUE : TOKEN_FALSE133 };134 }135 // Default136 throw new Error('Unexpected argument of type ' + typeof (item));137 })(json);138 // A set of shorthands proxies for the length of the dictionaries139 var stringLength = dictionary.strings.length;140 var integerLength = dictionary.integers.length;141 var floatLength = dictionary.floats.length;142 verbose && console.log('Parsing the dictionary');143 // Create a raw dictionary144 var packed = dictionary.strings.join('|');145 packed += '^' + dictionary.integers.join('|');146 packed += '^' + dictionary.floats.join('|');147 verbose && console.log('Parsing the structure');148 // And add the structure149 packed += '^' + (function recursiveParser(item) {150 verbose && console.log('Calling a recursiveParser with ' + this.JSON.stringify(item));151 // If the item is Array, then is a object of152 // type [object Object] or [object Array]153 if ( item instanceof Array) {154 // The packed resulting155 var packed = item.shift();156 for (var i in item) {157 158 if (!item.hasOwnProperty(i)) 159 continue;160 161 packed += recursiveParser(item[i]) + '|';162 }163 return (packed[packed.length - 1] === '|' ? packed.slice(0, -1) : packed) + ']';164 }165 // A shorthand proxies166 var type = item.type, index = item.index;167 if (type === 'strings') {168 // Just return the base 36 of index169 return _base10To36(index);170 }171 if (type === 'integers') {172 // Return a base 36 of index plus stringLength offset173 return _base10To36(stringLength + index);174 }175 if (type === 'floats') {176 // Return a base 36 of index plus stringLength and integerLength offset177 return _base10To36(stringLength + integerLength + index);178 }179 if (type === 'boolean') {180 return item.index;181 }182 if (type === 'null') {183 return TOKEN_NULL;184 }185 if (type === 'undefined') {186 return TOKEN_UNDEFINED;187 }188 if (type === 'empty') {189 return TOKEN_EMPTY_STRING;190 }191 throw new TypeError('The item is alien!');192 })(ast);193 verbose && console.log('Ending parser');194 // If debug, return a internal representation of dictionary and stuff195 if (options.debug)196 return {197 dictionary : dictionary,198 ast : ast,199 packed : packed200 };201 return packed;202 };203 var unpack = function(packed, options) {204 // Canonizes the options205 options = options || {};206 // A raw buffer207 var rawBuffers = packed.split('^');208 // Create a dictionary209 options.verbose && console.log('Building dictionary');210 var dictionary = [];211 // Add the strings values212 var buffer = rawBuffers[0];213 if (buffer !== '') {214 buffer = buffer.split('|');215 options.verbose && console.log('Parse the strings dictionary');216 for (var i=0, n=buffer.length; i<n; i++){217 dictionary.push(_decode(buffer[i]));218 }219 }220 // Add the integers values221 buffer = rawBuffers[1];222 if (buffer !== '') {223 buffer = buffer.split('|');224 options.verbose && console.log('Parse the integers dictionary');225 for (var i=0, n=buffer.length; i<n; i++){226 dictionary.push(_base36To10(buffer[i]));227 }228 }229 // Add the floats values230 buffer = rawBuffers[2];231 if (buffer !== '') {232 buffer = buffer.split('|')233 options.verbose && console.log('Parse the floats dictionary');234 for (var i=0, n=buffer.length; i<n; i++){235 dictionary.push(parseFloat(buffer[i]));236 }237 }238 // Free memory239 delete buffer;240 options.verbose && console.log('Tokenizing the structure');241 // Tokenizer the structure242 var number36 = '';243 var tokens = [];244 var len=rawBuffers[3].length;245 for (var i = 0; i < len; i++) {246 var symbol = rawBuffers[3].charAt(i);247 if (symbol === '|' || symbol === '$' || symbol === '@' || symbol === ']') {248 if (number36) {249 tokens.push(_base36To10(number36));250 number36 = '';251 }252 symbol !== '|' && tokens.push(symbol);253 } else {254 number36 += symbol;255 }256 }257 // A shorthand proxy for tokens.length258 var tokensLength = tokens.length;259 // The index of the next token to read260 var tokensIndex = 0;261 options.verbose && console.log('Starting recursive parser');262 return (function recursiveUnpackerParser() {263 // Maybe '$' (object) or '@' (array)264 var type = tokens[tokensIndex++];265 options.verbose && console.log('Reading collection type ' + (type === '$' ? 'object' : 'Array'));266 // Parse an array267 if (type === '@') {268 var node = [];269 for (; tokensIndex < tokensLength; tokensIndex++) {270 var value = tokens[tokensIndex];271 options.verbose && console.log('Read ' + value + ' symbol');272 if (value === ']')273 return node;274 if (value === '@' || value === '$') {275 node.push(recursiveUnpackerParser());276 } else {277 switch(value) {278 case TOKEN_TRUE:279 node.push(true);280 break;281 case TOKEN_FALSE:282 node.push(false);283 break;284 case TOKEN_NULL:285 node.push(null);286 break;287 case TOKEN_UNDEFINED:288 node.push(undefined);289 break;290 case TOKEN_EMPTY_STRING:291 node.push('');292 break;293 default:294 node.push(dictionary[value]);295 }296 }297 }298 options.verbose && console.log('Parsed ' + this.JSON.stringify(node));299 return node;300 }301 // Parse a object302 if (type === '$') {303 var node = {};304 for (; tokensIndex < tokensLength; tokensIndex++) {305 var key = tokens[tokensIndex];306 if (key === ']')307 return node;308 if (key === TOKEN_EMPTY_STRING)309 key = '';310 else311 key = dictionary[key];312 var value = tokens[++tokensIndex];313 if (value === '@' || value === '$') {314 node[key] = recursiveUnpackerParser();315 } else {316 switch(value) {317 case TOKEN_TRUE:318 node[key] = true;319 break;320 case TOKEN_FALSE:321 node[key] = false;322 break;323 case TOKEN_NULL:324 node[key] = null;325 break;326 case TOKEN_UNDEFINED:327 node[key] = undefined;328 break;329 case TOKEN_EMPTY_STRING:330 node[key] = '';331 break;332 default:333 node[key] = dictionary[value];334 }335 }336 }337 options.verbose && console.log('Parsed ' + this.JSON.stringify(node));338 return node;339 }340 throw new TypeError('Bad token ' + type + ' isn\'t a type');341 })();342 }343 /**344 * Get the index value of the dictionary345 * @param {Object} dictionary a object that have two array attributes: 'string' and 'number'346 * @param {Object} data347 */348 var _indexOfDictionary = function(dictionary, value) {349 // The type of the value350 var type = typeof value;351 // If is boolean, return a boolean token352 if (type === 'boolean')353 return value ? TOKEN_TRUE : TOKEN_FALSE;354 // If is null, return a... yes! the null token355 if (value === null)356 return TOKEN_NULL;357 //add undefined358 if (typeof value === 'undefined')359 return TOKEN_UNDEFINED;360 if (value === '') {361 return TOKEN_EMPTY_STRING;362 }363 if (type === 'string') {364 value = _encode(value);365 var index = _indexOf.call(dictionary.strings, value);366 if (index === -1) {367 dictionary.strings.push(value);368 index = dictionary.strings.length - 1;369 }370 }371 // If has an invalid JSON type (example a function)372 if (type !== 'string' && type !== 'number') {373 throw new Error('The type is not a JSON type');374 };375 if (type === 'string') {// string376 value = _encode(value);377 } else if (value % 1 === 0) {// integer378 value = _base10To36(value);379 } else {// float380 }381 // If is number, "serialize" the value382 value = type === 'number' ? _base10To36(value) : _encode(value);383 // Retrieve the index of that value in the dictionary384 var index = _indexOf.call(dictionary[type], value);385 // If that value is not in the dictionary386 if (index === -1) {387 // Push the value388 dictionary[type].push(value);389 // And return their index390 index = dictionary[type].length - 1;391 }392 // If the type is a number, then add the '+' prefix character393 // to differentiate that they is a number index. If not, then394 // just return a 36-based representation of the index395 return type === 'number' ? '+' + index : index;396 };397 var _encode = function(str) {398 if ( typeof str !== 'string')399 return str;400 return str.replace(/[\+ \|\^\%]/g, function(a) {401 return ({402 ' ' : '+',403 '+' : '%2B',404 '|' : '%7C',405 '^' : '%5E',406 '%' : '%25'407 })[a]408 });409 };410 var _decode = function(str) {411 if ( typeof str !== 'string')412 return str;413 return str.replace(/\+|%2B|%7C|%5E|%25/g, function(a) {414 return ({415 '+' : ' ',416 '%2B' : '+',417 '%7C' : '|',418 '%5E' : '^',419 '%25' : '%'420 })[a]421 })422 };423 var _base10To36 = function(number) {424 return Number.prototype.toString.call(number, 36).toUpperCase();425 };426 var _base36To10 = function(number) {427 return parseInt(number, 36);428 };429 var _indexOf = Array.prototype.indexOf ||430 function(obj, start) {431 for (var i = (start || 0), j = this.length; i < j; i++) {432 if (this[i] === obj) {433 return i;434 }435 }436 return -1;437 };438 return {439 JSON : JSON,440 pack : pack,441 unpack : unpack442 };443 });444})( typeof define == 'undefined' || !define.amd ? function(deps, factory) {445 var jsonpack = factory();446 if ( typeof exports != 'undefined')447 for (var key in jsonpack)448 exports[key] = jsonpack[key];449 else450 window.jsonpack = jsonpack;...
test.spec.ts
Source:test.spec.ts
1import { InjectionToken, NgModule } from '@angular/core';2import { MockBuilder, ngMocks } from 'ng-mocks';3const TOKEN_OBJECT = new InjectionToken('OBJECT');4const TOKEN_CLASS = new InjectionToken('CLASS');5const TOKEN_BOOLEAN = new InjectionToken('BOOLEAN');6const TOKEN_NUMBER = new InjectionToken('NUMBER');7const TOKEN_STRING = new InjectionToken('STRING');8const TOKEN_NULL = new InjectionToken('NULL');9class DummyClass {}10@NgModule({11 providers: [12 {13 provide: TOKEN_OBJECT,14 useValue: {15 func: () => 'hello',16 prop: 123,17 },18 },19 {20 provide: TOKEN_CLASS,21 useValue: DummyClass,22 },23 {24 provide: TOKEN_BOOLEAN,25 useValue: true,26 },27 {28 provide: TOKEN_NUMBER,29 useValue: 5,30 },31 {32 provide: TOKEN_STRING,33 useValue: 'hello',34 },35 {36 provide: TOKEN_NULL,37 useValue: null,38 },39 ],40})41class TargetModule {}42// fix for jest without jasmine assertions43const assertion: any =44 typeof jasmine === 'undefined' ? expect : jasmine;45describe('tokens-value', () => {46 ngMocks.faster();47 beforeEach(() => MockBuilder().mock(TargetModule));48 it('mocks TOKEN_OBJECT via MockService', () => {49 const actual = ngMocks.findInstance<any>(TOKEN_OBJECT);50 expect(actual).toEqual({51 func: assertion.anything(),52 });53 expect(actual.func()).toBeUndefined();54 });55 it('mocks TOKEN_CLASS as undefined', () => {56 const actual = ngMocks.findInstance(TOKEN_CLASS);57 expect(actual).toBeUndefined();58 });59 it('mocks TOKEN_BOOLEAN as false', () => {60 const actual = ngMocks.findInstance(TOKEN_BOOLEAN);61 expect(actual).toBe(false);62 });63 it('mocks TOKEN_NUMBER as 0', () => {64 const actual = ngMocks.findInstance(TOKEN_NUMBER);65 expect(actual).toBe(0);66 });67 it('mocks TOKEN_STRING as an empty string', () => {68 const actual = ngMocks.findInstance(TOKEN_STRING);69 expect(actual).toBe('');70 });71 it('mocks TOKEN_NULL as null', () => {72 const actual = ngMocks.findInstance(TOKEN_NULL);73 expect(actual).toBe(null);74 });...
test.js
Source:test.js
1/* ENTENDIENDO EL DOBLE SIGNO DE EXCLAMACIÃN2 Los signos de exclamación dobles realmente pueden convertirlo al valor booleano correspondiente. 3 El primer signo de exclamación es convertirlo en un valor booleano, pero esta operación obtiene 4 el valor después de su negación, 5 que puede obtenerse realizando una operación de negación Que corresponde a un verdadero booleano6*/7var token_null = null;8console.log( 'token_null =', token_null ); // null9console.log( '!token_null =', !token_null ); // true10console.log( '!!token_null =', !!token_null ); // false11console.log( '-----------' );12var token_undefined = undefined;13console.log( 'token_undefined =', token_undefined ); // undefined14console.log( '!token_undefined =', !token_undefined ); // true15console.log( '!!token_undefined =', !!token_undefined ); // false16console.log( '-----------' );17var token_string = 'mi_token';18console.log( 'token_string =', token_string ); // "mi_token"19console.log( '!token_string =', !token_string ); // false...
Using AI Code Generation
1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2import { AppModule } from './app.module';3import { AppComponent } from './app.component';4describe('AppComponent', () => {5 beforeEach(() => MockBuilder(AppComponent, AppModule));6 it('should create the app', () => {7 const fixture = MockRender(AppComponent);8 const app = fixture.point.componentInstance;9 expect(app).toBeTruthy();10 });11 it('should render title', () => {12 const fixture = MockRender(AppComponent);13 const app = fixture.point.componentInstance;14 const compiled = fixture.point.nativeElement;15 expect(compiled.querySelector('h1').textContent).toContain(app.title);16 });17 it('should render title', () => {18 const fixture = MockRender(AppComponent);19 const compiled = fixture.point.nativeElement;20 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');21 });22 it('should render title', () => {23 const fixture = MockRender(AppComponent);24 const compiled = fixture.point.nativeElement;25 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');26 });27 it('should render title', () => {28 const fixture = MockRender(AppComponent);29 const compiled = fixture.point.nativeElement;30 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');31 });32 it('should render title', () => {33 const fixture = MockRender(AppComponent);34 const compiled = fixture.point.nativeElement;35 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');36 });37 it('should render title', () => {38 const fixture = MockRender(AppComponent);39 const compiled = fixture.point.nativeElement;40 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');41 });42 it('should render title', () => {43 const fixture = MockRender(AppComponent);44 const compiled = fixture.point.nativeElement;45 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');46 });47 it('should render title', () => {48 const fixture = MockRender(AppComponent);49 const compiled = fixture.point.nativeElement;50 expect(compiled.querySelector('h1').textContent).toContain('Welcome to ng-mocks!');51 });52 it('should render title', () => {53 const fixture = MockRender(AppComponent);
Using AI Code Generation
1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2import { AppModule } from './app.module';3import { AppComponent } from './app.component';4describe('AppComponent', () => {5 beforeEach(() => MockBuilder(AppComponent, AppModule));6 it('should create the app', () => {7 const fixture = MockRender(AppComponent);8 const app = fixture.point.componentInstance;9 expect(app).toBeTruthy();10 });11 it(`should have as title 'app'`, () => {12 const fixture = MockRender(AppComponent);13 const app = fixture.point.componentInstance;14 expect(app.title).toEqual('app');15 });16 it('should render title in a h1 tag', () => {17 const fixture = MockRender(AppComponent);18 expect(fixture.debugElement.nativeElement.querySelector('h1').textContent).toContain('Welcome to app!');19 });20 it('should render a mocked component', () => {21 const fixture = MockRender(AppComponent);22 const mock = ngMocks.findInstance(MockComponent);23 expect(mock).toBeTruthy();24 });25});26import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';27import { AppModule } from './app.module';28import { AppComponent } from './app.component';29import { MockComponent } from './mock.component';30describe('AppComponent', () => {31 beforeEach(() => MockBuilder(AppComponent, AppModule));32 it('should create the app', () => {33 const fixture = MockRender(AppComponent);34 const app = fixture.point.componentInstance;35 expect(app).toBeTruthy();36 });37 it(`should have as title 'app'`, () => {38 const fixture = MockRender(AppComponent);39 const app = fixture.point.componentInstance;40 expect(app.title).toEqual('app');41 });42 it('should render title in a h1 tag', () => {43 const fixture = MockRender(AppComponent);44 expect(fixture.debugElement.nativeElement.querySelector('h1').textContent).toContain('Welcome to app!');45 });46 it('should render a mocked component', () => {47 const fixture = MockRender(AppComponent);48 const mock = ngMocks.findInstance(MockComponent);49 expect(mock).toBeTruthy();50 });51});52import { NgModule } from '@angular/core';53import { BrowserModule } from '@angular/platform-browser';54import { AppComponent } from './app.component
Using AI Code Generation
1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2beforeEach(() => MockBuilder().mock(TOKEN_NULL));3it('renders', () => {4 const fixture = MockRender(`5 `);6 const div = ngMocks.findInstance(fixture.debugElement, DivComponent);7 expect(div).toBeDefined();8});9import { Component, Inject } from '@angular/core';10import { TOKEN_NULL } from './test';11@Component({12})13export class DivComponent {14 constructor(@Inject(TOKEN_NULL) private token: any) {}15}16import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';17import { TOKEN_NULL } from './test';18beforeEach(() => MockBuilder().mock(TOKEN_NULL));19it('renders', () => {20 const fixture = MockRender(`21 `);22 const div = ngMocks.findInstance(fixture.debugElement, DivComponent);23 expect(div).toBeDefined();24});25import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';26import { TOKEN_NULL } from './test';27beforeEach(() => MockBuilder().mock(TOKEN_NULL));28it('renders', () => {29 const fixture = MockRender(`30 `);31 const div = ngMocks.findInstance(fixture.debugElement, DivComponent);32 expect(div).toBeDefined();33});34import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';35import { TOKEN_NULL } from './test';36beforeEach(() => MockBuilder().mock(TOKEN_NULL));37it('renders', () => {38 const fixture = MockRender(`39 `);40 const div = ngMocks.findInstance(fixture.debugElement, DivComponent);41 expect(div).toBeDefined();42});
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!!