Best JavaScript code snippet using ng-mocks
topics.js
Source:topics.js
1var express = require("express");2var path = require("path");3var auth = require("../libs/auth");4var models = require("../models");5var render_args = require("../libs/render_args");6var util = require("../libs/util");7var router = express.Router();8router.post("/", function(req, res) {9 // Prepare render arguments10 var args = new render_args();11 // Check session12 var token_object = auth.checkSession(req);13 if(token_object != undefined) {14 args.setLoggedinUser(token_object);15 } else {16 res.redirect("/index");17 return;18 }19 var user_id = token_object.user_id;20 var title = req.body.title;21 var message = req.body.message;22 models.Topic.create({23 "title": title,24 "UserId": user_id25 })26 .then((topic) => {27 models.Message.create({28 "message": message,29 "UserId": user_id,30 "TopicId": topic["id"],31 })32 .then((message) => {33 res.redirect(path.join(req.originalUrl, ""+topic["id"]));34 })35 .catch((error) => {36 console.error(error);37 res.redirect("/500");38 });39 })40 .catch((error) => {41 console.error(error);42 res.redirect("/500");43 });44});45router.get("/:topic_id", (req, res) => {46 // Prepare render arguments47 var args = new render_args();48 // Check session49 var token_object = auth.checkSession(req);50 if(token_object != undefined) {51 args.setLoggedinUser(token_object);52 }53 // Get topic information and messages54 var topic_id = req.params.topic_id;55 var find_one_args = {56 "where": {"id": topic_id},57 "include": [58 {59 "model": models.Message,60 "include": [models.User]61 }62 ],63 "order": [64 ["Messages", 'createdAt', 'ASC']65 ]66 };67 models.Topic.findOne(find_one_args)68 .then((topic) => {69 args.topic = {70 "topic_id": topic["id"],71 "title": topic["title"]72 };73 args.topic.messages = [];74 topic['Messages'].forEach((message) => {75 var can_edit = false;76 if(token_object) {77 can_edit = message["User"]["id"] == token_object["user_id"] ||78 token_object["user_type"] == "Administrator" ||79 token_object["user_type"] == "Moderator";80 }81 var message_to_send = {82 "message_id": message["id"],83 "Username": message["User"]["username"],84 "UserType": message["User"]["user_type"],85 "MessageTime": util.formatDates(message["createdAt"]),86 "MessageF": util.formatOutput(message["message"]),87 "SignatureF": util.formatOutput(message["User"]["signature"]),88 "CanEdit": can_edit89 };90 args.topic.messages.push(message_to_send);91 });92 res.render(path.join("../views/pages", "topic"), args);93 })94 .catch((error) => {95 console.error(error);96 res.redirect("/500");97 });98});99router.post("/:topic_id", function(req, res) {100 var args = new render_args();101 var token_object = auth.checkSession(req);102 if(token_object != undefined) {103 args.setLoggedinUser(token_object);104 } else {105 res.end("Error");106 return;107 }108 var topic_id = req.params.topic_id;109 var method = req.body.method;110 var message_id = req.body.message_id;111 var user_id = token_object.user_id;112 var message = req.body.message;113 if(method == "post") {114 models.Message.create({115 "message": message,116 "UserId": user_id,117 "TopicId": topic_id118 })119 .then((message) => {120 res.redirect("back");121 })122 .catch((error) => {123 console.error(error);124 res.redirect("/500");125 });126 } else {127 var find_one_args = {128 "where": {"id": message_id}129 };130 models.Message.findOne(find_one_args)131 .then((message_obj) => {132 message_obj["message"] = message;133 message_obj.save().then(() => {134 res.redirect(req.originalUrl);135 });136 })137 .catch((error) => {138 console.error(error);139 res.redirect("/500");140 });141 }142});143router.get("/messages/:message_id", function(req, res) {144 var message_id = req.params.message_id;145 var find_one_args = {146 "where": {"id": message_id}147 };148 models.Message.findOne(find_one_args)149 .then((message) => {150 res.end(message["message"]);151 })152 .catch((error) => {153 console.error(error);154 res.redirect("/500");155 });156});...
verifySignature.js
Source:verifySignature.js
1const _ = require('lodash');2const timestamp = require('@6crm/sixcrmcore/lib/util/timestamp').default;3const signature = require('@6crm/sixcrmcore/lib/util/signature').default;4const du = require('@6crm/sixcrmcore/lib/util/debug-utilities').default;5const eu = require('@6crm/sixcrmcore/lib/util/error-utilities').default;6const AccessKeyController = global.SixCRM.routes.include('controllers', 'entities/AccessKey.js');7module.exports = class verifySignatureController {8 constructor() {9 this.accessKeyController = new AccessKeyController();10 }11 execute(event) {12 return this.parseEventSignature(event)13 .then(this.createTokenObject.bind(this))14 .then(this.verifyTimestamp.bind(this))15 .then(this.verifySignature.bind(this))16 .then(this.populateAuthorityUser.bind(this));17 }18 parseEventSignature(event) {19 const tokens = event.authorizationToken.split(':');20 if (!_.isArray(tokens) || !(tokens.length == 3)) {21 du.warning('Signature failed: Incorrect structure');22 return Promise.reject(false);23 }24 return Promise.resolve(tokens);25 }26 createTokenObject(tokens) {27 return new Promise((resolve, reject) => {28 this.accessKeyController.disableACLs();29 this.accessKeyController.getAccessKeyByKey(tokens[0]).then((access_key) => {30 this.accessKeyController.enableACLs();31 if (_.has(access_key, 'secret_key') && _.has(access_key, 'id')) {32 let token_object = {33 access_key: access_key,34 timestamp: tokens[1],35 signature: tokens[2]36 };37 return resolve(token_object);38 } else {39 return reject(eu.getError('not_implemented', 'Unset Access Key properties.'));40 }41 }).catch((error) => {42 return reject(error);43 });44 });45 }46 verifyTimestamp(token_object) {47 let time_difference = timestamp.getTimeDifference(token_object.timestamp);48 if (time_difference > (60 * 60 * 5)) {49 du.warning('Signature failed: Timestamp expired');50 return Promise.reject(false);51 }52 du.info('Timestamp valid');53 return Promise.resolve(token_object);54 }55 verifySignature(token_object) {56 if (!signature.validateSignature(token_object.access_key.secret_key, token_object.timestamp, token_object.signature)) {57 du.warning('Signature failed: Incorrect Signature');58 return Promise.reject(false);59 } else {60 du.info('Signature valid');61 return Promise.resolve(token_object);62 }63 }64 populateAuthorityUser() {65 return {66 id: 'system@sixcrm.com'67 };68 }...
decodeToken.js
Source:decodeToken.js
1const jwt = require('jsonwebtoken')2const JWT_KEY = '6eoc94l@t*bi2w3vm(-d7#dqr($rkuzgg$f6#@1b)smkzg*j7i'3function decodeToken(req) {4 let token = null5 let token_object = null6 let message = null7 try {8 token = req.header('Authorization').replace('Bearer ', '')9 }10 catch (e) {11 message = 'Authentication credentials were not provided.'12 13 return {14 token_object: token_object,15 message: message16 }17 }18 try {19 token_object = jwt.verify(token, JWT_KEY)20 }21 catch (e) {22 message = 'Invalid authentication. Could not decode token.'23 return {24 token_object: token_object,25 message: message26 }27 }28 let now = new Date()29 let expired_at = new Date(token_object.expired_at)30 if (Date.parse(now.toString()) > Date.parse(expired_at.toString())) {31 message = 'The token has expired.'32 return {33 token_object: token_object,34 message: message35 }36 }37 return {38 token_object: token_object,39 message: message40 }41}...
Using AI Code Generation
1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2import { AppComponent } from './app.component';3import { AppModule } from './app.module';4describe('AppComponent', () => {5 beforeEach(() => MockBuilder(AppComponent, AppModule));6 it('should create the app', () => {7 const fixture = MockRender(AppComponent);8 const app = ngMocks.findInstance(AppComponent);9 expect(app).toBeTruthy();10 });11});12ngMocks.findInstance() method13ngMocks.findInstance(component: Type<T> | AbstractType<T> | any): T;14import { Component } from '@angular/core';15import { TestBed } from '@angular/core/testing';16import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';17@Component({18})19class AppComponent {}20describe('AppComponent', () => {21 beforeEach(() => MockBuilder(AppComponent));22 it('should create the app', () => {23 const fixture = MockRender(AppComponent);24 const app = ngMocks.findInstance(AppComponent);25 expect(app).toBeTruthy();26 });27});28✓ should create the app (5ms)29ngMocks.findInstance() method30ngMocks.findInstance(component: Type<T> | AbstractType<T> | any): T;
Using AI Code Generation
1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2import { AppComponent } from './app.component';3import { AppModule } from './app.module';4describe('AppComponent', () => {5 beforeEach(() => MockBuilder(AppComponent, AppModule));6 it('should create the app', () => {7 const fixture = MockRender(AppComponent);8 const app = ngMocks.findInstance(AppComponent);9 expect(app).toBeTruthy();10 });11});12import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';13import { AppComponent } from './app.component';14import { AppModule } from './app.module';15describe('AppComponent', () => {16 beforeEach(() => MockBuilder(AppComponent, AppModule));17 it('should create the app', () => {18 const fixture = MockRender(AppComponent);19 const app = ngMocks.findInstance(AppComponent);20 expect(app).toBeTruthy();21 });22});23import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';24import { AppComponent } from './app.component';25import { AppModule } from './app.module';26describe('AppComponent', () => {27 beforeEach(() => MockBuilder(AppComponent, AppModule));28 it('should create the app', () => {29 const fixture = MockRender(AppComponent);30 const app = ngMocks.findInstance(AppComponent);31 expect(app).toBeTruthy();32 });33});34import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';35import { AppComponent } from './app.component';36import { AppModule } from './app.module';37describe('AppComponent', () => {38 beforeEach(() => MockBuilder(AppComponent, AppModule));39 it('should create the app', () => {40 const fixture = MockRender(AppComponent);41 const app = ngMocks.findInstance(AppComponent);42 expect(app).toBeTruthy();43 });44});45import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';46import { AppComponent } from './app.component';47import { AppModule } from './app.module';48describe('AppComponent', () => {49 beforeEach(() => Mock
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 app = ngMocks.find('app-root');8 expect(app).toBeTruthy();9 });10});11import { Component, OnInit } from '@angular/core';12@Component({13})14export class AppComponent implements OnInit {15 constructor() { }16 ngOnInit() {17 }18}19import { BrowserModule } from '@angular/platform-browser';20import { NgModule } from '@angular/core';21import { AppRoutingModule } from './app-routing.module';22import { AppComponent } from './app.component';23import { BrowserAnimationsModule } from '@angular/platform-browser/animations';24@NgModule({25 imports: [26})27export class AppModule { }28import { NgModule } from '@angular/core';29import { Routes, RouterModule } from '@angular/router';30const routes: Routes = [];31@NgModule({32 imports: [RouterModule.forRoot(routes)],33})34export class AppRoutingModule { }35import 'zone.js/dist/zone-testing';36import { getTestBed } from '@angular/core/testing';37import {38} from '@angular/platform-browser-dynamic/testing';39getTestBed().initTestEnvironment(40 platformBrowserDynamicTesting()41);
Using AI Code Generation
1import { TOKEN_OBJECT } from 'ng-mocks';2import { MockComponent } from 'ng-mocks';3const mockModule = TOKEN_OBJECT({4 imports: [],5 MockComponent({ selector: 'app-test' }),6});7describe('TestComponent', () => {8 beforeEach(() => {9 TestBed.configureTestingModule({10 imports: [11 });12 });13});14import { MockModule } from 'ng-mocks';15describe('TestComponent', () => {16 beforeEach(() => {17 TestBed.configureTestingModule({18 imports: [19 MockModule({20 imports: [],21 MockComponent({ selector: 'app-test' }),22 }),23 });24 });25});26import { TOKEN_OBJECT } from 'ng-mocks';27import { MockComponent } from 'ng-mocks';
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!!