Best JavaScript code snippet using ng-mocks
Parser.spec.ts
Source:Parser.spec.ts
...29 new Token(1, 1, opType),30 generateConstant()[0]31 ];32}33function generateReturn(expression?: Token[]) {34 if (!expression) expression = generateExpression();35 return [new Token(1, 1, TokenType.Keyword, "return")]36 .concat(expression)37 .concat(new Token(1, 1, TokenType.Semicolon));38}39describe("Parser", () => {40 describe("Parser.parseOpType()", () => {41 it("should return the corresponding opType when given an operation token", () => {42 for (let tokType in TokenType) {43 if (!OperationType.hasOwnProperty(tokType)) continue;44 if (/^[0-9]+$/.test(tokType)) continue;45 let tok = new Token(1, 1, parseInt(TokenType[tokType]));46 expect(Parser["parseOpType"](tok)).to.equal(OperationType[tokType]);47 }48 });49 it("should throw an error when given a tokenType that has no corresponding operation", () => {50 expect(Parser["parseOpType"].bind(Parser, new Token(1, 1, TokenType.Identifier, "bad")))51 .to.throw("Invalid operator: bad");52 expect(Parser["parseOpType"].bind(Parser, new Token(1, 1, TokenType.Keyword, "bad")))53 .to.throw("Invalid operator: bad");54 expect(Parser["parseOpType"].bind(Parser, new Token(1, 1, TokenType.Semicolon)))55 .to.throw("Invalid operator: ;");56 });57 });58 describe("Parser.parseFactor()", () => {59 // A factor is a constant, an expression or factor wrapped in parentheses, or a monadic operation60 it("should correctly parse a valid factor", () => {61 let factor = Parser["parseFactor"](generateFactor());62 expect(factor).to.be.an.instanceof(MonadicASTNode);63 factor = Parser["parseFactor"](generateConstant());64 expect(factor).to.be.an.instanceof(ConstantASTNode);65 factor = Parser["parseFactor"](parenWrap(generateFactor()));66 expect(factor).to.be.an.instanceof(ExpressionASTNode);67 factor = Parser["parseFactor"](parenWrap(generateExpression()));68 expect(factor).to.be.an.instanceof(ExpressionASTNode);69 });70 it("should throw an error when given an invalid factor", () => {71 expect(Parser["parseFactor"].bind(Parser, [new Token(1, 1, TokenType.Semicolon)]))72 .to.throw("Invalid factor: ;");73 expect(Parser["parseFactor"].bind(Parser, [new Token(1, 1, TokenType.Identifier, "bad")]))74 .to.throw("Invalid factor: bad");75 expect(Parser["parseFactor"].bind(Parser, [new Token(1, 1, TokenType.OpenBrace)]))76 .to.throw("Invalid factor: {");77 expect(Parser["parseFactor"].bind(Parser, [new Token(1, 1, TokenType.Multiplication)]))78 .to.throw("Invalid factor: *");79 });80 it("should throw an error when given mis-matched parens", () => {81 expect(Parser["parseFactor"].bind(Parser,82 parenWrap(generateExpression().concat([new Token(1, 1, TokenType.Semicolon)]))83 )).to.throw("Expected " + TokenType.CloseParen + " but found ;");84 });85 });86 describe("Parser.parseExpression()", () => {87 // An expression is a factor, or a diadic operation88 it("should correctly parse a valid expression", () => {89 let expr = Parser["parseExpression"](generateFactor());90 expect(expr).to.be.an.instanceof(MonadicASTNode);91 expr = Parser["parseExpression"](generateConstant());92 expect(expr).to.be.an.instanceof(ConstantASTNode);93 expr = Parser["parseExpression"](generateExpression());94 expect(expr).to.be.an.instanceof(DiadicASTNode);95 expr = Parser["parseExpression"](parenWrap(generateFactor()));96 expect(expr).to.be.an.instanceof(MonadicASTNode);97 expr = Parser["parseExpression"](parenWrap(generateExpression()));98 expect(expr).to.be.an.instanceof(DiadicASTNode);99 });100 it("should correctly parse sub-factors", () => {101 let tokens = generateExpression(TokenType.Multiplication);102 tokens.pop();103 tokens = tokens.concat(generateFactor());104 let expr: ExpressionASTNode = Parser["parseExpression"](tokens);105 expect(expr).to.be.an.instanceof(DiadicASTNode);106 expect((expr as DiadicASTNode).childNodes[1]).to.be.an.instanceof(MonadicASTNode);107 });108 });109 describe("Parser.parseStatement()", () => {110 it("should correctly parse a valid statement", () => {111 let statement = Parser["parseStatement"](generateReturn(generateConstant()));112 expect(statement).to.be.an.instanceof(ReturnStatementASTNode);113 expect(statement.childNodes).to.be.an.instanceof(ConstantASTNode);114 statement = Parser["parseStatement"](generateReturn(generateFactor()));115 expect(statement).to.be.an.instanceof(ReturnStatementASTNode);116 expect(statement.childNodes).to.be.an.instanceof(MonadicASTNode);117 statement = Parser["parseStatement"](generateReturn(generateExpression()));118 expect(statement).to.be.an.instanceof(ReturnStatementASTNode);119 expect(statement.childNodes).to.be.an.instanceof(DiadicASTNode);120 });121 it("should throw an error if the statement does not end in a semicolon", () => {122 let toks = generateReturn(generateConstant()).slice(0, 2);123 let bind = Parser["parseStatement"].bind(Parser, toks);124 expect(bind).to.throw("Expected " + TokenType.Semicolon + " but found <EOF>");125 toks = generateReturn(generateConstant()).slice(0, 2).concat([126 new Token(1, 1, TokenType.Keyword, "int")127 ]);128 bind = Parser["parseStatement"].bind(Parser, toks);129 expect(bind).to.throw("Expected " + TokenType.Semicolon + " but found int");130 });131 it("should throw an error if the statement does not begin with a keyword", () => {132 let toks = generateReturn(generateConstant()).slice(1);133 let bind = Parser["parseStatement"].bind(Parser, toks);134 expect(bind).to.throw("Expected statement but found ");135 toks = [136 new Token(1, 1, TokenType.Semicolon)137 ].concat(generateReturn(generateConstant()).slice(1));138 bind = Parser["parseStatement"].bind(Parser, toks);139 expect(bind).to.throw("Expected statement but found ;");140 });141 });...
Activity.ts
Source:Activity.ts
...32 referencedColumnName: "id"33 }34 })35 tickets: Ticket[];36 private static generateReturn(activity: Activity) {37 return {38 id: activity.id,39 duration: activity.duration,40 date: activity.date,41 name: activity.name,42 local: activity.local,43 freeSpots: activity.vacancies - activity.tickets.length,44 tickets: activity.tickets,45 };46 }47 static async getAll() {48 const activities = await this.find({ relations: ["local", "tickets"] });49 return activities.map(activity => (this.generateReturn(activity)));50 }51 static async saveTicketToActivity(ticket: Ticket, activityId: number) {52 const activity = await Activity.findOne( { where: { id: activityId, }, relations: ["tickets"] });53 const isSubscribed = activity.tickets.find((tix) => tix.id === ticket.id);54 55 if (isSubscribed) {56 throw new ConflictError("Você já está registrado nesta atividade!", this.generateReturn(activity));57 }58 59 if (!activity) {60 throw new NotFoundError();61 }62 if (activity.vacancies <= activity.tickets.length) {63 throw new NoVacanciesError(this.generateReturn(activity));64 }65 const activityStart = dayjs(activity.date);66 const activityEnd = activityStart.add(activity.duration - 1, "minutes");67 function timeConflictVerify(start: Dayjs, end: Dayjs) { 68 if ((start <= activityStart && end >= activityStart) || (start >= activityStart && end <= activityEnd) || (start <= activityEnd && end >= activityEnd )) {69 return true;70 }71 return false;72 }73 const conflictingActivity = ticket.activities.find((act) => {74 const actStart = dayjs(act.date);75 const actEnd = actStart.add(act.duration - 1, "minutes");76 return timeConflictVerify(actStart, actEnd);77 });78 79 if (conflictingActivity) {80 throw new ConflictError("Você já está registrado em outra atividade com o mesmo horário.", this.generateReturn(activity));81 }82 83 activity.tickets.push(ticket);84 await activity.save();85 }86 static async removeActivityFromTicket(ticket: Ticket, activityId: number) {87 const activity = await Activity.findOne( { where: { id: activityId, }, relations: ["tickets"] });88 89 if (!activity) {90 throw new NotFoundError();91 }92 93 const signOutTimeLimit = dayjs(activity.date).subtract(12, "hours");94 95 if (dayjs() > signOutTimeLimit) {96 throw new UnsubscribeTimeOverError();97 }98 activity.tickets = activity.tickets.filter((tix) => tix.id !== ticket.id);99 await activity.save();100 return this.generateReturn(activity);101 }...
go-function.ts
Source:go-function.ts
...20 });21 return name22 }23 get(): string{24 let r = this.generateReturn("");25 let input = this.generateInputs("");26 return`func ${this.structName()}(${input})${r}{\n ${this.body}\n}\n\n`27 }28 generateInputs(i: string): string{29 return i30 }31 generateReturn(r: string): string{32 if(this.returnTypes.length > 0){33 r += "(";34 for (let i = 0; i < this.returnTypes.length; i++) {35 r+= this.returnTypes[i].type;36 if(i != this.returnTypes.length - 1){37 r += ","38 }39 }40 r += ")";41 }42 return r;43 }...
Using AI Code Generation
1import { generateReturn } from 'ng-mocks';2import { MyService } from './my-service';3import { MyComponent } from './my-component';4describe('MyComponent', () => {5 let component: MyComponent;6 let service: MyService;7 beforeEach(() => {8 service = new MyService();9 component = new MyComponent(service);10 });11 it('should call service method', () => {12 spyOn(service, 'get').and.returnValue(generateReturn({ id: 1 }));13 component.ngOnInit();14 expect(component.data.id).toEqual(1);15 });16});17import { Component, OnInit } from '@angular/core';18import { MyService } from './my-service';19@Component({20})21export class MyComponent implements OnInit {22 data: any;23 constructor(private service: MyService) {}24 ngOnInit() {25 this.service.get().subscribe((data) => {26 this.data = data;27 });28 }29}30import { Injectable } from '@angular/core';31import { Observable } from 'rxjs';32@Injectable()33export class MyService {34 get(): Observable<any> {35 return new Observable((observer) => {36 observer.next({ id: 1 });37 });38 }39}
Using AI Code Generation
1import { generateReturn } from 'ng-mocks';2describe('generateReturn', () => {3 it('should return a function that returns a value', () => {4 const value = 'test';5 const returnValue = generateReturn(value);6 expect(returnValue()).toEqual(value);7 });8});
Using AI Code Generation
1import {generateReturn} from 'ng-mocks';2import {mockService} from 'ng-mocks';3import {mockComponent} from 'ng-mocks';4import {mockPipe} from 'ng-mocks';5import {mockDirective} from 'ng-mocks';6import {mockModule} from 'ng-mocks';7import {mockProvider} from 'ng-mocks';8import {mockRender} from 'ng-mocks';9import {mockReset} from 'ng-mocks';10import {mockInstance} from 'ng-mocks';11import {mockProvider} from 'ng-mocks';12import {mockPipe} from 'ng-mocks';13import {mockDirective} from 'ng-mocks';14import {mockComponent} from 'ng-mocks';15import {mockService} from 'ng-mocks';16import {mockNg} from 'ng-mocks';17import {mockNgOne} from 'ng-mocks';18import {mockNgAll} from 'ng-mocks';19import {mockNgDeep} from 'ng-mocks';20import {mockNgRender} from 'ng-mocks';21import {mockNgReset} from 'ng-mocks';22import {mockNgInstance} from 'ng-mocks';23import {mockNgProvider} from 'ng-mocks';24import {mockNgPipe} from 'ng
Using AI Code Generation
1import {generateReturn} from 'ng-mocks';2export class Test {3 public generateReturn() {4 return generateReturn('test');5 }6}7import {Test} from './test';8describe('test', () => {9 it('should return "test"', () => {10 const test = new Test();11 expect(test.generateReturn()).toBe('test');12 });13});14import {generateReturn} from 'ng-mocks';15import 'ng-mocks';16export class Test {17 public generateReturn() {18 return generateReturn('test');19 }20}21import {generateReturn} from 'ng-mocks';22import 'ng-mocks';23export class Test {24 public generateReturn() {25 return generateReturn('test');26 }27}28import {generateReturn} from 'ng-mocks';29import 'ng-mocks';30export class Test {31 public generateReturn() {32 return generateReturn('test');33 }34}
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!!