How to use mockClass method in ng-mocks

Best JavaScript code snippet using ng-mocks

state.spec.ts

Source:state.spec.ts Github

copy

Full Screen

1/*2Licensed under the Apache License, Version 2.0 (the "License");3you may not use this file except in compliance with the License.4You may obtain a copy of the License at5http://www.apache.org/licenses/LICENSE-2.06Unless required by applicable law or agreed to in writing, software7distributed under the License is distributed on an "AS IS" BASIS,8WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.9See the License for the specific language governing permissions and10limitations under the License.11*/12import * as chai from 'chai';13import 'reflect-metadata';14import * as sinon from 'sinon';15import * as sinonChai from 'sinon-chai';16import { HistoricState, State } from './state';17// tslint:disable:max-classes-per-file18const should = chai.should();19chai.use(sinonChai);20describe ('#State', () => {21 let sandbox: sinon.SinonSandbox;22 beforeEach(() => {23 sandbox = sinon.createSandbox();24 });25 afterEach(() => {26 sandbox.restore();27 });28 describe ('serialize', () => {29 it ('should create buffer from JSON serialized object', () => {30 State.serialize({some: 'object'}).should.deep.equal(Buffer.from('{"some":"object"}'));31 });32 });33 describe ('deserialize', () => {34 it ('should throw an error if class not found', () => {35 const classMap = new Map();36 classMap.set('some class name', 'some class');37 (() => {38 State.deserialize(Buffer.from('{"some":"object","class":"unknown class"}'), classMap);39 }).should.throw('Unknown class of unknown class');40 });41 it ('should return call constructor', () => {42 const classMap = new Map();43 classMap.set('some class name', 'some class');44 const callConstructorStub = sandbox.stub(State as any, 'callConstructor').returns('something');45 State.deserialize(46 Buffer.from('{"some":"object","class":"some class name"}'), classMap,47 ).should.deep.equal('something');48 callConstructorStub.should.have.been.calledOnceWithExactly('some class', {49 class: 'some class name',50 some: 'object',51 });52 });53 });54 describe ('makeKey', () => {55 it ('should join the key parts with a colon', () => {56 State.makeKey(['some', 'key', 'parts']).should.deep.equal('some:key:parts');57 });58 });59 describe ('splitKey', () => {60 it ('should split the key parts on a colon', () => {61 State.splitKey('some:key:parts').should.deep.equal(['some', 'key', 'parts']);62 });63 });64 describe ('callConstructor', () => {65 it ('should throw an error if class is not instance of state', () => {66 class MockClass {}67 (() => {68 (State as any).callConstructor(MockClass, {some: 'object'});69 }).should.throw('Cannot use MockClass as type State');70 });71 it ('should throw an error if json is missing param name found in the constructor', () => {72 class MockClass extends State {73 constructor(property1: string, property2: string) {74 super('mockClass', ['key', 'parts']);75 }76 }77 (() => {78 (State as any).callConstructor(MockClass, {some: 'object'});79 }).should.throw('Could not deserialize JSON. Missing required fields. ["property1","property2"]');80 });81 it ('should create new instance of the class passed', () => {82 class MockClass extends State {83 public property1: string;84 public property2: string;85 constructor(property1: string, property2: string) {86 super('mockClass', ['key', 'parts']);87 this.property1 = property1;88 this.property2 = property2;89 }90 }91 const mockClass = (State as any).callConstructor(92 MockClass, {some: 'object', property1: 'some property', property2: 'some other property'},93 );94 // tslint:disable-next-line:no-unused-expression95 (mockClass instanceof MockClass).should.be.true;96 mockClass.property1.should.deep.equal('some property');97 mockClass.property2.should.deep.equal('some other property');98 });99 it ('should use metadata when set', () => {100 class MockClass extends State {101 public property1: string;102 public property2: string;103 constructor(property1: string, property2: string) {104 super('mockClass', ['key', 'parts']);105 this.property1 = property1;106 this.property2 = property2;107 }108 }109 Reflect.defineMetadata(110 'contract:function', ['property1', 'property2', 'property3'], MockClass.prototype, 'constructor',111 );112 (() => {113 (State as any).callConstructor(114 MockClass, {some: 'object', property1: 'some property', property2: 'some other property'},115 );116 }).should.throw('Could not deserialize JSON. Missing required fields. ["property3"]');117 });118 it ('should handle optional properties', () => {119 class MockClass extends State {120 public property1: string;121 public property2: string;122 constructor(property1: string, property2?: string) {123 super('mockClass', ['key', 'parts']);124 this.property1 = property1;125 if (property2) {126 this.property2 = 'was set';127 }128 }129 }130 Reflect.defineMetadata(131 'contract:function', ['property1', 'property2?'], MockClass.prototype, 'constructor',132 );133 const mockClass = (State as any).callConstructor(134 MockClass, {some: 'object', property1: 'some property'},135 );136 // tslint:disable-next-line:no-unused-expression137 (mockClass instanceof MockClass).should.be.true;138 mockClass.property1.should.deep.equal('some property');139 should.equal(mockClass.property2, undefined);140 const mockClass2 = (State as any).callConstructor(141 MockClass, {some: 'object', property1: 'some property', property2: 'hello'},142 );143 // tslint:disable-next-line:no-unused-expression144 (mockClass2 instanceof MockClass).should.be.true;145 mockClass2.property1.should.deep.equal('some property');146 mockClass2.property2.should.deep.equal('was set');147 });148 });149 describe ('getClass', () => {150 it ('should return the class', () => {151 const state = new State('some class', ['key', 'parts']);152 state.getClass().should.deep.equal('some class');153 });154 });155 describe ('getKey', () => {156 it ('should return the key', () => {157 sandbox.stub(State, 'makeKey').returns('some:joined:key');158 const state = new State('some class', ['key', 'parts']);159 state.getKey().should.deep.equal('some:joined:key');160 });161 });162 describe ('getSplitKey', () => {163 it ('should return split key', () => {164 sandbox.stub(State, 'makeKey').returns('some:joined:key');165 const staticSplit = sandbox.stub(State, 'splitKey').returns(['some', 'split', 'key']);166 const state = new State('some class', ['key', 'parts']);167 state.getSplitKey().should.deep.equal(['some', 'split', 'key']);168 staticSplit.should.have.been.calledOnceWithExactly('some:joined:key');169 });170 });171 describe ('serialize', () => {172 it ('should return serialized state', () => {173 const expected = Buffer.from(JSON.stringify({some: 'serialized', object: 'woo'}));174 const staticSerialize = sandbox.stub(State, 'serialize').returns(expected);175 const state = new State('some class', ['key', 'parts']);176 state.serialize().should.deep.equal(expected);177 staticSerialize.should.have.been.calledOnceWithExactly(state);178 });179 });180});181describe ('#HistoricState', () => {182 class MockClass {183 // tslint:disable-next-line:no-empty184 constructor() {}185 public serialize(): Buffer {186 return Buffer.from('some value');187 }188 }189 let sandbox: sinon.SinonSandbox;190 beforeEach(() => {191 sandbox = sinon.createSandbox();192 });193 afterEach(() => {194 sandbox.restore();195 });196 describe ('constructor', () => {197 it ('should set values', () => {198 const mockClass = new MockClass();199 const historicState = new HistoricState(12345, 'some tx id', mockClass as any);200 historicState.timestamp.should.deep.equal(12345);201 historicState.txId.should.deep.equal('some tx id');202 historicState.value.should.deep.equal(mockClass);203 });204 });205 describe ('serialize', () => {206 it ('should serialize its data and use serialized data from value', () => {207 const mockClass = new MockClass();208 const expectedSerializedValue = Buffer.from(JSON.stringify({some: 'object'}));209 const serializeStub = sandbox.stub(mockClass, 'serialize').returns(expectedSerializedValue);210 const historicState = new HistoricState(12345, 'some tx id', mockClass as any);211 const expectedSerialized = Buffer.from(JSON.stringify({212 timestamp: 12345,213 txId: 'some tx id',214 value: {215 some: 'object',216 },217 }));218 historicState.serialize().should.deep.equal(expectedSerialized);219 serializeStub.should.have.been.calledOnceWithExactly();220 });221 });...

Full Screen

Full Screen

external-call-service.test.js

Source:external-call-service.test.js Github

copy

Full Screen

1describe('helpers.ExternalCallService', function() {2 var Service;3 var $q, $rootScope;4 var MESSAGE_EXTERNAL_METHOD_ERROR,5 MESSAGE_EXTERNAL_METHOD_INVALID_RETURN;6 // load module7 beforeEach(function() {8 module('AngularDynamicForm');9 });10 // inject services (that we want to test)11 beforeEach(inject(function($injector) {12 Service = $injector.get('AngularDynamicForm.helpers.ExternalCallService');13 $q = $injector.get('$q');14 $rootScope = $injector.get('$rootScope');15 MESSAGE_EXTERNAL_METHOD_ERROR = $injector.get('MESSAGE_EXTERNAL_METHOD_ERROR');16 MESSAGE_EXTERNAL_METHOD_INVALID_RETURN = $injector.get('MESSAGE_EXTERNAL_METHOD_INVALID_RETURN');17 }));18 //--------------------------------------------19 // callExternalMethod20 //--------------------------------------------21 describe('callExternalMethod', function() {22 it('should call method', function() {23 var MockClass = {24 mockMethod: function() {}25 };26 spyOn(MockClass, 'mockMethod').and.returnValue(true);27 Service.callExternalMethod(MockClass.mockMethod);28 expect(MockClass.mockMethod).toHaveBeenCalled();29 });30 it('should call method with provided args', function() {31 var MockClass = {32 mockMethod: function() {}33 };34 spyOn(MockClass, 'mockMethod').and.returnValue(true);35 Service.callExternalMethod(MockClass.mockMethod, ['A']);36 expect(MockClass.mockMethod).toHaveBeenCalledWith(['A']);37 });38 it('should throw an Error if method throws an error', function() {39 var MockClass = {40 mockMethod: function() {}41 };42 spyOn(MockClass, 'mockMethod').and.throwError('');43 expect(function() { Service.callExternalMethod(MockClass.mockMethod); }).toThrowError(MESSAGE_EXTERNAL_METHOD_ERROR);44 });45 it('should throw an Error if method does not return', function() {46 var MockClass = {47 mockMethod: function() {}48 };49 spyOn(MockClass, 'mockMethod');50 expect(function() { Service.callExternalMethod(MockClass.mockMethod); }).toThrowError(MESSAGE_EXTERNAL_METHOD_INVALID_RETURN);51 });52 it('should throw an Error if method returns neither boolean nor promise', function() {53 var MockClass = {54 mockMethod: function() {}55 };56 spyOn(MockClass, 'mockMethod').and.returnValue('adsadsa');57 expect(function() { Service.callExternalMethod(MockClass.mockMethod); }).toThrowError(MESSAGE_EXTERNAL_METHOD_INVALID_RETURN);58 });59 it('should resolve if successful', function() {60 var MockClass = {61 mockMethod: function() {}62 };63 spyOn(MockClass, 'mockMethod').and.returnValue({64 then: function(resolve) {65 resolve('my response');66 }67 });68 var result;69 Service.callExternalMethod(MockClass.mockMethod).then(function(response) {70 result = response;71 });72 $rootScope.$apply();73 expect(result).toBe('my response');74 });75 it('should reject on failure', function() {76 var MockClass = {77 mockMethod: function() {}78 };79 spyOn(MockClass, 'mockMethod').and.returnValue({80 then: function(resolve, reject) {81 reject('my response');82 }83 });84 var result;85 Service.callExternalMethod(MockClass.mockMethod).then(null, function(response) {86 result = response;87 });88 $rootScope.$apply();89 expect(result).toBe('my response');90 });91 it('should resolve if method returns true', function() {92 var MockClass = {93 mockMethod: function() {}94 };95 spyOn(MockClass, 'mockMethod').and.returnValue(true);96 var result;97 Service.callExternalMethod(MockClass.mockMethod).then(function(response) {98 result = response;99 });100 $rootScope.$apply();101 expect(result).toBe(undefined);102 });103 it('should reject if method returns false', function() {104 var MockClass = {105 mockMethod: function() {}106 };107 spyOn(MockClass, 'mockMethod').and.returnValue(false);108 var result;109 Service.callExternalMethod(MockClass.mockMethod).then(null, function(response) {110 result = response;111 });112 $rootScope.$apply();113 expect(result).toBe(undefined);114 });115 });...

Full Screen

Full Screen

_objectStore.test.ts

Source:_objectStore.test.ts Github

copy

Full Screen

1import { expect } from "chai";2import { Identifiable } from "./../../interfaces/identifiable";3import { ObjectStore } from "./../objectStore";4class MockClass implements Identifiable {5 public constructor(public Uid: number, public Label?: string) {}6}7describe("ObjectStore", () => {8 describe("constructor", () => {9 it("should take a list of identifiables as argument and build the lookup dictionary", () => {10 const data = [new MockClass(1), new MockClass(2)];11 const objectStore = new ObjectStore(data);12 expect(objectStore.GetDict()).to.deep.eq({13 1: new MockClass(1),14 2: new MockClass(2),15 });16 });17 it("should throw error if the data contains duplicated Uids", () => {18 const data = [new MockClass(1), new MockClass(1)];19 expect(() => {20 const x = new ObjectStore(data);21 }).to.throw();22 });23 });24 describe("GetOne", () => {25 it("should take a key and return the corresponding data", () => {26 const data = [new MockClass(1, "bob"), new MockClass(2, "ali")];27 const objectStore = new ObjectStore(data);28 expect(objectStore.GetOne(1)).to.deep.eq(new MockClass(1, "bob"));29 });30 it("should return undefined if the key match no data", () => {31 const data = [new MockClass(1, "bob"), new MockClass(2, "ali")];32 const objectStore = new ObjectStore(data);33 expect(objectStore.GetOne(999)).to.eq(undefined);34 });35 });36 describe("GetBunch", () => {37 it("should take a list of keys and return the matching data", () => {38 const data = [39 new MockClass(1, "bob"),40 new MockClass(2, "ali"),41 new MockClass(3, "mari"),42 ];43 const objectStore = new ObjectStore(data);44 expect(objectStore.GetBunch([1, 3])).to.deep.eq([45 new MockClass(1, "bob"),46 new MockClass(3, "mari"),47 ]);48 });49 it("should ignore non-matching key", () => {50 const data = [51 new MockClass(1, "bob"),52 new MockClass(2, "ali"),53 new MockClass(3, "lili"),54 ];55 const objectStore = new ObjectStore(data);56 const result = objectStore.GetBunch([1, 99, 3]);57 expect(result).to.deep.eq([58 new MockClass(1, "bob"),59 new MockClass(3, "lili"),60 ]);61 });62 });63 describe("GetAll", () => {64 it("should return all values of the dict as a list", () => {65 const data = [66 new MockClass(1, "bob"),67 new MockClass(2, "ali"),68 new MockClass(3, "lili"),69 ];70 const x = new ObjectStore(data);71 expect(x.GetAll()).to.deep.eq(data.slice());72 });73 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { mockClass } from 'ng-mocks';2import { MyService } from './my-service';3import { MyServiceMock } from './my-service-mock';4describe('MyService', () => {5 let service: MyService;6 beforeEach(() => {7 service = mockClass(MyService, MyServiceMock);8 });9 it('should return mocked value', () => {10 expect(service.getValue()).toEqual('mocked value');11 });12});13import { Injectable } from '@angular/core';14@Injectable()15export class MyService {16 getValue(): string {17 return 'real value';18 }19}20import { MyService } from './my-service';21export class MyServiceMock extends MyService {22 getValue(): string {23 return 'mocked value';24 }25}26import { MyService } from './my-service';27describe('MyService', () => {28 let service: MyService;29 beforeEach(() => {30 service = new MyService();31 });32 it('should return real value', () => {33 expect(service.getValue()).toEqual('real value');34 });35});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { mockClass } from 'ng-mocks';2import { ClassToMock } from './class-to-mock';3import { ClassToTest } from './class-to-test';4describe('Test', () => {5 it('should test', () => {6 const mock = mockClass(ClassToMock, 'methodOne', () => 'mocked');7 const instance = new ClassToTest(mock);8 expect(instance.methodOne()).toBe('mocked');9 });10});11export class ClassToMock {12 methodOne(): string {13 return 'real';14 }15}16import { ClassToMock } from './class-to-mock';17export class ClassToTest {18 constructor(private mockedClass: ClassToMock) {}19 methodOne(): string {20 return this.mockedClass.methodOne();21 }22}23import { mockClass } from 'ng-mocks';24import { ClassToMock } from './class-to-mock';25import { ClassToTest } from './class-to-test';26describe('Test', () => {27 it('should test', () => {28 const mock = mockClass(ClassToMock, 'methodOne', () => 'mocked');29 const instance = new ClassToTest(mock);30 expect(instance.methodOne()).toBe('mocked');31 });32});33import { AbstractClass } from './abstract-class';34export class ClassToMock extends AbstractClass {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { mockClass } from 'ng-mocks';2describe('mockClass', () => {3 it('should mock class', () => {4 const mockedClass = mockClass(OriginalClass);5 const instance = new mockedClass();6 expect(instance instanceof OriginalClass).toBe(true);7 });8});9export class OriginalClass {10 public testMethod(): number {11 return 42;12 }13}14describe('OriginalClass', () => {15 it('should return 42', () => {16 const instance = new OriginalClass();17 expect(instance.testMethod()).toBe(42);18 });19});20export class MockClass {21 public testMethod(): number {22 return 43;23 }24}25describe('MockClass', () => {26 it('should return 43', () => {27 const instance = new MockClass();28 expect(instance.testMethod()).toBe(43);29 });30});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { mockClass } from 'ng-mocks';2const mock = mockClass(ClassName);3describe('test', () => {4 let mock: ClassName;5 beforeEach(() => {6 mock = mockClass(ClassName);7 });8});9import { mockClass } from 'ng-mocks';10const mock = mockClass(ClassName, 'arg1', 'arg2');11describe('test', () => {12 let mock: ClassName;13 beforeEach(() => {14 mock = mockClass(ClassName, 'arg1', 'arg2');15 });16});17import { mockClass } from 'ng-mocks';18const mock = mockClass(ClassName, mockClass(OtherClassName));19describe('test', () => {20 let mock: ClassName;21 beforeEach(() => {22 mock = mockClass(ClassName, mockClass(OtherClassName));23 });24});25import { mockClass } from 'ng-mocks';26const mock = mockClass(ClassName, mockClass(OtherClassName, 'arg1', 'arg2'));27describe('test', () => {28 let mock: ClassName;29 beforeEach(() => {30 mock = mockClass(ClassName, mockClass(OtherClassName, 'arg1', 'arg2'));31 });32});33import { mockClass } from 'ng-mocks';34const mock = mockClass(ClassName, mockClass(OtherClassName, mockClass(ThirdClassName)));35describe('test', () => {36 let mock: ClassName;37 beforeEach(() => {38 mock = mockClass(ClassName, mockClass(OtherClassName, mockClass(ThirdClassName)));39 });40});

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ng-mocks automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful