Best JavaScript code snippet using ng-mocks
translator.js
Source:translator.js
1var App=App||{}2App.Translator=class{3 async init(urls) {4 const model=await (async (url)=>{5 try {6 const model = await tf.loadLayersModel(url);7 console.log('Done loading pretrained model.');8 return model;9 } catch (err) {10 console.error(err);11 console.error('Loading pretrained model failed.');12 throw err;13 }14 })(urls.model)15 const translationMetadata = await (async (url)=>{try {16 const metadataJson = await fetch(url);17 const metadata = await metadataJson.json();18 console.log('Done loading metadata.');19 return metadata;20 } catch (err) {21 console.error(err);22 console.error('Loading metadata failed.');23 }})(urls.metadata);24 this.maxDecoderSeqLength = translationMetadata['max_decoder_seq_length'];25 this.maxEncoderSeqLength = translationMetadata['max_encoder_seq_length'];26 console.log('maxDecoderSeqLength = ' + this.maxDecoderSeqLength);27 console.log('maxEncoderSeqLength = ' + this.maxEncoderSeqLength);28 this.inputTokenIndex = translationMetadata['input_token_index'];29 this.targetTokenIndex = translationMetadata['target_token_index'];30 this.reverseTargetCharIndex = Object.keys(this.targetTokenIndex).reduce((obj, key) => (obj[this.targetTokenIndex[key]] = key, obj), {});31 this.prepareEncoderModel(model)32 this.prepareDecoderModel(model)33 }34 prepareEncoderModel(model) {35 this.numEncoderTokens = model.input[0].shape[2];36 console.log('numEncoderTokens = ' + this.numEncoderTokens);37 const encoderInputs = model.input[0];38 const stateH = model.layers[2].output[1];39 const stateC = model.layers[2].output[2];40 const encoderStates = [stateH, stateC];41 this.encoderModel = tf.model({inputs: encoderInputs, outputs: encoderStates});42 }43 prepareDecoderModel(model) {44 this.numDecoderTokens = model.input[1].shape[2];45 console.log('numDecoderTokens = ' + this.numDecoderTokens);46 const stateH = model.layers[2].output[1];47 const latentDim = stateH.shape[stateH.shape.length - 1];48 console.log('latentDim = ' + latentDim);49 const decoderStateInputH = tf.input({shape: [latentDim], name: 'decoder_state_input_h'});50 const decoderStateInputC = tf.input({shape: [latentDim], name: 'decoder_state_input_c'});51 const decoderStateInputs = [decoderStateInputH, decoderStateInputC];52 const decoderLSTM = model.layers[3];53 const decoderInputs = decoderLSTM.input[0];54 const applyOutputs = decoderLSTM.apply(decoderInputs, {initialState: decoderStateInputs});55 let decoderOutputs = applyOutputs[0];56 const decoderStateH = applyOutputs[1];57 const decoderStateC = applyOutputs[2];58 const decoderStates = [decoderStateH, decoderStateC];59 const decoderDense = model.layers[4];60 decoderOutputs = decoderDense.apply(decoderOutputs);61 this.decoderModel = tf.model({inputs: [decoderInputs].concat(decoderStateInputs),outputs: [decoderOutputs].concat(decoderStates)});62 }63 encodeString(str) {64 const strLen = str.length;65 const encoded = tf.buffer([1, this.maxEncoderSeqLength, this.numEncoderTokens]);66 for (let i = 0; i < strLen; ++i) {67 if (i >= this.maxEncoderSeqLength) {68 console.error( 'Input sentence exceeds maximum encoder sequence length: ' + this.maxEncoderSeqLength);69 }70 const tokenIndex = this.inputTokenIndex[str[i]];71 if (tokenIndex == null) {72 console.error( 'Character not found in input token index: "' + tokenIndex + '"');73 }74 encoded.set(1, 0, i, tokenIndex);75 }76 return encoded.toTensor();77 }78 decodeSequence(inputSeq) {79 let statesValue = this.encoderModel.predict(inputSeq);80 let targetSeq = tf.buffer([1, 1, this.numDecoderTokens]);81 targetSeq.set(1, 0, 0, this.targetTokenIndex['\t']);82 let stopCondition = false;83 let decodedSentence = '';84 while (!stopCondition) {85 const predictOutputs = this.decoderModel.predict([targetSeq.toTensor()].concat(statesValue));86 const outputTokens = predictOutputs[0];87 const h = predictOutputs[1];88 const c = predictOutputs[2];89 const logits = outputTokens.reshape([outputTokens.shape[2]]);90 const sampledTokenIndex = logits.argMax().dataSync()[0];91 const sampledChar = this.reverseTargetCharIndex[sampledTokenIndex];92 decodedSentence += sampledChar;93 if (sampledChar === '\n' ||94 decodedSentence.length > this.maxDecoderSeqLength) {95 stopCondition = true;96 }97 targetSeq = tf.buffer([1, 1, this.numDecoderTokens]);98 targetSeq.set(1, 0, 0, sampledTokenIndex);99 statesValue = [h, c];100 }101 return decodedSentence;102 }103 translate(inputSentence) {104 let decodedSentence=""105 tf.tidy(()=>{106 const inputSeq = this.encodeString(inputSentence);107 decodedSentence = this.decodeSequence(inputSeq);108 })109 return decodedSentence;110 }...
index.js
Source:index.js
1import * as tf from "@tensorflow/tfjs";2import * as loader from "./loader";3import * as ui from "./ui";4// load our pretrained models5const HOSTED_URLS = {6 model:7 "https://storage.googleapis.com/tfjs-models/tfjs/translation_en_fr_v1/model.json",8 metadata:9 "https://storage.googleapis.com/tfjs-models/tfjs/translation_en_fr_v1/metadata.json"10};11// translator12class Translator {13 async init(urls) {14 this.urls = urls;15 const model = await loader.loadHostedPretrainedModel(urls.model);16 await this.loadMetadata();17 this.prepareEncoderModel(model);18 this.prepareDecoderModel(model);19 return this;20 }21 async loadMetadata() {22 // retrieve from helper class23 const translationMetadata = await loader.loadHostedPretrainedModel(24 this.urls.metadata25 );26 this.maxDecoderSeqLength = translationMetadata["max_decoder_seq_length"];27 this.maxEncoderSeqLength = translationMetadata["max_encoder_seq_length"];28 this.inputTokenIndex = translationMetadata["input_token_index"];29 this.targetTokenIndex = translationMetadata["target_token_index"];30 }31 prepareEncoderModel(model) {32 // encoder token count?33 this.numEncoderTokens = model.input[0].shape[2];34 const encoderInputs = model.input[0];35 const stateH = model.layers[2].output[1];36 const stateC = model.layers[2].output[2];37 const encoderStates = [stateH, stateC];38 this.encoderModel = tf.model({39 inputs: encoderInputs,40 outputs: encoderStates41 });42 }43 prepareDecoderModel(model) {44 this.numDecoderTokens = model.input[1].shape[2];45 const stateH = model.layers[2].output[1];46 const latentDim = stateH.shape[stateH.shape.length - 1];47 const decoderStateInputH = tf.input({48 shape: [latentDim],49 name: "decoder_state_input_h"50 });51 const decoderStateInputC = tf.input({52 shape: [latentDim],53 name: "decoder_state_input_c"54 });55 const decoderStateInputs = [decoderStateInputH, decoderStateInputC];56 // retrieve the LSSTM model57 const decoderLSTM = model.layers[3];58 const decoderInputs = decoderLSTM.input[0];59 const applyOutputs = decoderLSTM.apply(decoderInputs, {60 initalState: decoderStateInputs61 });62 let decoderOutputs = applyOutputs[0];63 const decoderStateH = applyOutputs[1];64 const decoderStateC = applyOutputs[2];65 const decoderStates = [decoderStateH, decoderStateC];66 const decoderDense = model.layers[4];67 decoderOutputs = decoderDense.apply(decoderOutputs);68 this.decoderModel = tf.model({69 inputs: [decoderInputs].concat(decoderStateInputs),70 outputs: [decoderOutputs].concat(decoderState)71 });72 }...
Using AI Code Generation
1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2import { AppComponent } from './app.component';3describe('AppComponent', () => {4 beforeEach(() => MockBuilder(AppComponent));5 it('should create the app', () => {6 const fixture = MockRender(AppComponent);7 const component = fixture.point.componentInstance;8 expect(component).toBeTruthy();9 });10 it('should display a title', () => {11 const fixture = MockRender(AppComponent);12 const component = fixture.point.componentInstance;13 const title = ngMocks.find('h1').nativeElement;14 expect(title.textContent).toContain(component.title);15 });16 it('should display a title using applyOutputs', () => {17 const fixture = MockRender(AppComponent);18 const component = fixture.point.componentInstance;19 const title = ngMocks.find('h1').nativeElement;20 ngMocks.applyOutputs(component);21 expect(title.textContent).toContain(component.title);22 });23});24import { Component } from '@angular/core';25@Component({26})27export class AppComponent {28 title = 'app';29 onClick() {30 this.title = 'app-clicked';31 }32}33<h1 (click)="onClick()">Welcome to {{ title }}!</h1>34h1 {35 font-family: Lato;36}37import { TestBed, async } from '@angular/core/testing';38import { RouterTestingModule } from '@angular/router/testing';39import { AppComponent } from './app.component';40describe('AppComponent', () => {41 beforeEach(async(() => {42 TestBed.configureTestingModule({43 imports: [RouterTestingModule],44 }).compileComponents();45 }));46 it('should create the app', () => {47 const fixture = TestBed.createComponent(AppComponent);48 const app = fixture.debugElement.componentInstance;49 expect(app).toBeTruthy();50 });51 it(`should have as title 'app'`, () => {52 const fixture = TestBed.createComponent(AppComponent);53 const app = fixture.debugElement.componentInstance;54 expect(app.title).toEqual('app');55 });56 it('should render title in a h1 tag', () => {57 const fixture = TestBed.createComponent(AppComponent);58 fixture.detectChanges();59 const compiled = fixture.debugElement.nativeElement;
Using AI Code Generation
1const { applyOutputs } = require('ng-mocks');2const { Component, NgModule } = require('@angular/core');3const { TestBed } = require('@angular/core/testing');4@Component({5})6class TestComponent {}7@NgModule({8})9class TestModule {}10const fixture = TestBed.configureTestingModule({11 imports: [TestModule],12}).createComponent(TestComponent);13applyOutputs(fixture);14console.log(fixture.componentInstance);15const { MockBuilder, MockRender } = require('ng-mocks');16const { TestComponent } = require('./test');17describe('TestComponent', () => {18 beforeEach(() => MockBuilder(TestComponent));19 it('should create', () => {20 const fixture = MockRender(TestComponent);21 expect(fixture.point.componentInstance).toBeDefined();22 });23});24const { MockBuilder, MockRender } = require('ng-mocks');25const { TestComponent } = require('./test');26describe('TestComponent', () => {27 beforeEach(() => MockBuilder(TestComponent));28 it('should create', () => {29 const fixture = MockRender(TestComponent);30 expect(fixture.point.componentInstance).toBeDefined();31 });32});33const { MockBuilder, MockRender } = require('ng-mocks');34const { TestComponent } = require('./test');35describe('TestComponent', () => {36 beforeEach(() => MockBuilder(TestComponent));37 it('should create', () => {38 const fixture = MockRender(TestComponent);39 expect(fixture.point.componentInstance).toBeDefined();40 });41});42const { MockBuilder, MockRender } = require('ng-mocks');43const { TestComponent } = require('./test');44describe('TestComponent', () => {45 beforeEach(() => MockBuilder(TestComponent));46 it('should create', () => {47 const fixture = MockRender(TestComponent);48 expect(fixture.point.componentInstance).toBeDefined();49 });50});51const { MockBuilder, MockRender } = require('ng-mocks');52const { TestComponent } = require('./test');53describe('TestComponent', () => {54 beforeEach(() => MockBuilder(TestComponent));55 it('should create', () => {56 const fixture = MockRender(TestComponent);57 expect(fixture.point.componentInstance).toBeDefined();58 });59});
Using AI Code Generation
1import {applyOutputs} from 'ng-mocks';2import {MyComponent} from './my.component';3describe('MyComponent', () => {4 it('should work', () => {5 const instance = new MyComponent();6 const outputs = applyOutputs(instance, {7 });8 expect(outputs).toEqual({9 });10 });11});
Using AI Code Generation
1const ngMocks = require('ng-mocks');2const path = require('path');3const fs = require('fs');4const outputPath = path.join(__dirname, 'output');5if (!fs.existsSync(outputPath)) {6 fs.mkdirSync(outputPath);7}8const inputs = {9};10ngMocks.applyOutputs(outputPath, inputs);11{12}13{14}15{16}17{18}19{20}
Using AI Code Generation
1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2MockBuilder(Comp).keep(CompModule);3const fixture = MockRender(Comp);4ngMocks.applyOutputs(fixture.debugElement, {5 click: () => {6 console.log('clicked');7 },8});9import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';10describe('applyOutputs', () => {11 beforeEach(() => MockBuilder(Comp).keep(CompModule));12 it('should apply outputs', () => {13 const fixture = MockRender(Comp);14 const spy = spyOn(console, 'log');15 ngMocks.applyOutputs(fixture.debugElement, {16 click: () => {17 console.log('clicked');18 },19 });20 ngMocks.triggerClick(fixture.debugElement, 'button');21 expect(spy).toHaveBeenCalledWith('clicked');22 });23});24import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';25describe('applyOutputs', () => {26 beforeEach(() => MockBuilder(Comp).keep(CompModule));27 it('should apply outputs', () => {28 const fixture = MockRender(Comp);29 const spy = spyOn(console, 'log');30 ngMocks.applyOutputs(fixture.debugElement, {31 click: () => {32 console.log('clicked');33 },34 });35 ngMocks.triggerClick(fixture.debugElement, 'button');36 expect(spy).toHaveBeenCalledWith('clicked');37 });38});39import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';40describe('applyOutputs', () => {41 beforeEach(() => MockBuilder(Comp).keep(CompModule));42 it('should apply outputs', () => {43 const fixture = MockRender(Comp);44 const spy = spyOn(console, 'log');45 ngMocks.applyOutputs(fixture.debugElement, {46 click: () => {47 console.log('clicked');48 },49 });50 ngMocks.triggerClick(fixture.debugElement, 'button');51 expect(spy).toHaveBeenCalledWith('clicked');52 });53});54import { MockBuilder, MockRender, ngMocks
Using AI Code Generation
1const mock = ngMocks.findInstance(Comp);2ngMocks.applyOutputs(mock, { output: 'value' });3const mock = ngMocks.findInstance(Comp);4ngMocks.applyInputs(mock, { input: 'value' });5const mock = ngMocks.findInstance(Comp);6ngMocks.applyProperties(mock, { input: 'value', output: 'value' });7const mock = ngMocks.findInstance(Comp);8ngMocks.applyChanges(mock, { input: 'value', output: 'value' });9const mock = ngMocks.findInstance(Comp);10ngMocks.applyAllChanges(mock, { input: 'value', output: 'value' });11const mock = ngMocks.findInstance(Comp);12ngMocks.applyAllChanges(mock, { input: 'value', output: 'value' });13const mock = ngMocks.findInstance(Comp);14ngMocks.applyAllChanges(mock, { input: 'value', output: 'value' });15const mock = ngMocks.findInstance(Comp);16ngMocks.applyAllChanges(mock, { input: 'value', output: 'value' });17const mock = ngMocks.findInstance(Comp);18ngMocks.applyAllChanges(mock, { input: 'value', output: 'value' });19const mock = ngMocks.findInstance(Comp);20ngMocks.applyAllChanges(mock, { input: 'value', output: 'value' });21const mock = ngMocks.findInstance(Comp);22ngMocks.applyAllChanges(mock, { input: 'value', output: 'value' });23const mock = ngMocks.findInstance(Comp);24ngMocks.applyAllChanges(mock, { input: 'value', output: 'value' });25const mock = ngMocks.findInstance(Comp);
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!!