Best JavaScript code snippet using ng-mocks
index.spec.ts
Source:index.spec.ts
1import { Eip1193Bridge } from '@ethersproject/experimental'2import { Web3Provider } from '@ethersproject/providers'3import { createWeb3ReactStoreAndActions } from '@web3-react/store'4import type { Actions, ProviderRpcError, RequestArguments, Web3ReactStore } from '@web3-react/types'5import { EventEmitter } from 'node:events'6import { EIP1193 } from '.'7export async function yieldThread() {8 await new Promise((resolve) => setTimeout(resolve, 0))9}10class MockProviderRpcError extends Error {11 public code: number12 constructor() {13 super('Mock Provider RPC Error')14 this.code = 420015 }16}17export class MockEIP1193Provider extends EventEmitter {18 public chainId?: string19 public accounts?: string[]20 public eth_chainId = jest.fn((chainId?: string) => chainId)21 public eth_accounts = jest.fn((accounts?: string[]) => accounts)22 public eth_requestAccounts = jest.fn((accounts?: string[]) => accounts)23 public request(x: RequestArguments): Promise<unknown> {24 // make sure to throw if we're "not connected"25 if (!this.chainId) return Promise.reject(new Error())26 switch (x.method) {27 case 'eth_chainId':28 return Promise.resolve(this.eth_chainId(this.chainId))29 case 'eth_accounts':30 return Promise.resolve(this.eth_accounts(this.accounts))31 case 'eth_requestAccounts':32 return Promise.resolve(this.eth_requestAccounts(this.accounts))33 default:34 throw new Error()35 }36 }37 public emitConnect(chainId: string) {38 this.emit('connect', { chainId })39 }40 public emitDisconnect(error: ProviderRpcError) {41 this.emit('disconnect', error)42 }43 public emitChainChanged(chainId: string) {44 this.emit('chainChanged', chainId)45 }46 public emitAccountsChanged(accounts: string[]) {47 this.emit('accountsChanged', accounts)48 }49}50const chainId = '0x1'51const accounts: string[] = []52describe('EIP1193', () => {53 let mockProvider: MockEIP1193Provider54 let store: Web3ReactStore55 let actions: Actions56 let connector: EIP119357 beforeEach(() => {58 mockProvider = new MockEIP1193Provider()59 ;[store, actions] = createWeb3ReactStoreAndActions()60 })61 describe('ethers', () => {62 afterEach(() => {63 expect(mockProvider.eth_chainId.mock.calls.length).toBe(1)64 expect(mockProvider.eth_accounts.mock.calls.length).toBe(0)65 expect(mockProvider.eth_requestAccounts.mock.calls.length).toBe(1)66 })67 test('works', async () => {68 mockProvider.chainId = chainId69 mockProvider.accounts = accounts70 const web3Provider = new Web3Provider(mockProvider)71 const wrapped = new Eip1193Bridge(web3Provider.getSigner(), web3Provider)72 connector = new EIP1193(actions, wrapped, false)73 await connector.activate()74 expect(store.getState()).toEqual({75 chainId: 1,76 accounts,77 activating: false,78 error: undefined,79 })80 })81 })82 describe('functions', () => {83 describe('connectEagerly = true', () => {84 beforeEach(() => {85 expect(mockProvider.eth_chainId.mock.calls.length).toBe(0)86 expect(mockProvider.eth_accounts.mock.calls.length).toBe(0)87 expect(mockProvider.eth_requestAccounts.mock.calls.length).toBe(0)88 })89 // suppress console.debugs in this block90 beforeEach(() => {91 jest.spyOn(console, 'debug').mockImplementation(() => {})92 })93 afterEach(() => {94 jest.clearAllMocks()95 })96 test('fails silently', async () => {97 connector = new EIP1193(actions, mockProvider, true)98 await yieldThread()99 expect(store.getState()).toEqual({100 chainId: undefined,101 accounts: undefined,102 activating: false,103 error: undefined,104 })105 expect(mockProvider.eth_chainId.mock.calls.length).toBe(0)106 expect(mockProvider.eth_accounts.mock.calls.length).toBe(0)107 expect(mockProvider.eth_requestAccounts.mock.calls.length).toBe(0)108 })109 test('succeeds', async () => {110 mockProvider.chainId = chainId111 mockProvider.accounts = accounts112 connector = new EIP1193(actions, mockProvider, true)113 await yieldThread()114 expect(store.getState()).toEqual({115 chainId: 1,116 accounts,117 activating: false,118 error: undefined,119 })120 expect(mockProvider.eth_chainId.mock.calls.length).toBe(1)121 expect(mockProvider.eth_accounts.mock.calls.length).toBe(1)122 expect(mockProvider.eth_requestAccounts.mock.calls.length).toBe(0)123 })124 })125 describe('connectEagerly = false', () => {126 beforeEach(() => {127 connector = new EIP1193(actions, mockProvider, false)128 })129 beforeEach(() => {130 expect(mockProvider.eth_chainId.mock.calls.length).toBe(0)131 expect(mockProvider.eth_accounts.mock.calls.length).toBe(0)132 expect(mockProvider.eth_requestAccounts.mock.calls.length).toBe(0)133 })134 test('before', () => {135 expect(store.getState()).toEqual({136 chainId: undefined,137 accounts: undefined,138 activating: false,139 error: undefined,140 })141 })142 describe('#activate', () => {143 afterEach(() => {144 expect(mockProvider.eth_chainId.mock.calls.length).toBe(1)145 expect(mockProvider.eth_accounts.mock.calls.length).toBe(0)146 expect(mockProvider.eth_requestAccounts.mock.calls.length).toBe(1)147 })148 test(`chainId = ${chainId}`, async () => {149 mockProvider.chainId = chainId150 mockProvider.accounts = accounts151 await connector.activate()152 expect(store.getState()).toEqual({153 chainId: 1,154 accounts,155 activating: false,156 error: undefined,157 })158 })159 test("chainId = '0x01'", async () => {160 mockProvider.chainId = '0x01'161 mockProvider.accounts = accounts162 await connector.activate()163 expect(store.getState()).toEqual({164 chainId: 1,165 accounts,166 activating: false,167 error: undefined,168 })169 })170 test("accounts = ['0x0000000000000000000000000000000000000000']", async () => {171 const chainId = '0x1'172 const accounts: string[] = ['0x0000000000000000000000000000000000000000']173 mockProvider.chainId = chainId174 mockProvider.accounts = accounts175 await connector.activate()176 expect(store.getState()).toEqual({177 chainId: 1,178 accounts,179 activating: false,180 error: undefined,181 })182 })183 test("accounts = ['0x0000000000000000000000000000000000000000', '0x0000000000000000000000000000000000000001']", async () => {184 const chainId = '0x1'185 const accounts: string[] = [186 '0x0000000000000000000000000000000000000000',187 '0x0000000000000000000000000000000000000001',188 ]189 mockProvider.chainId = chainId190 mockProvider.accounts = accounts191 await connector.activate()192 expect(store.getState()).toEqual({193 chainId: 1,194 accounts,195 activating: false,196 error: undefined,197 })198 })199 })200 })201 })202 describe('events', () => {203 beforeEach(() => {204 connector = new EIP1193(actions, mockProvider, false)205 })206 afterEach(() => {207 expect(mockProvider.eth_chainId.mock.calls.length).toBe(0)208 expect(mockProvider.eth_accounts.mock.calls.length).toBe(0)209 expect(mockProvider.eth_requestAccounts.mock.calls.length).toBe(0)210 })211 const chainId = '0x1'212 const accounts: string[] = []213 const error = new MockProviderRpcError()214 test('#connect', async () => {215 mockProvider.emitConnect(chainId)216 expect(store.getState()).toEqual({217 chainId: 1,218 accounts: undefined,219 activating: false,220 error: undefined,221 })222 })223 test('#disconnect', async () => {224 mockProvider.emitDisconnect(error)225 expect(store.getState()).toEqual({226 chainId: undefined,227 accounts: undefined,228 activating: false,229 error,230 })231 })232 test('#chainChanged', async () => {233 mockProvider.emitChainChanged(chainId)234 expect(store.getState()).toEqual({235 chainId: 1,236 accounts: undefined,237 activating: false,238 error: undefined,239 })240 })241 test('#accountsChanged', async () => {242 mockProvider.emitAccountsChanged(accounts)243 expect(store.getState()).toEqual({244 chainId: undefined,245 accounts,246 activating: false,247 error: undefined,248 })249 })250 test('initializes with connect', async () => {251 mockProvider.emitConnect(chainId)252 mockProvider.emitAccountsChanged(accounts)253 expect(store.getState()).toEqual({254 chainId: 1,255 accounts,256 activating: false,257 error: undefined,258 })259 })260 test('initializes with chainChanged', async () => {261 mockProvider.emitChainChanged(chainId)262 mockProvider.emitAccountsChanged(accounts)263 expect(store.getState()).toEqual({264 chainId: 1,265 accounts,266 activating: false,267 error: undefined,268 })269 })270 })...
ObjectAPISpec.js
Source:ObjectAPISpec.js
1import ObjectAPI from './ObjectAPI.js';2describe("The Object API", () => {3 let objectAPI;4 let mockDomainObject;5 const TEST_NAMESPACE = "test-namespace";6 const FIFTEEN_MINUTES = 15 * 60 * 1000;7 beforeEach(() => {8 objectAPI = new ObjectAPI();9 mockDomainObject = {10 identifier: {11 namespace: TEST_NAMESPACE,12 key: "test-key"13 },14 name: "test object",15 type: "test-type"16 };17 });18 describe("The save function", () => {19 it("Rejects if no provider available", () => {20 let rejected = false;21 return objectAPI.save(mockDomainObject)22 .catch(() => rejected = true)23 .then(() => expect(rejected).toBe(true));24 });25 describe("when a provider is available", () => {26 let mockProvider;27 beforeEach(() => {28 mockProvider = jasmine.createSpyObj("mock provider", [29 "create",30 "update"31 ]);32 mockProvider.create.and.returnValue(Promise.resolve(true));33 objectAPI.addProvider(TEST_NAMESPACE, mockProvider);34 });35 it("Calls 'create' on provider if object is new", () => {36 objectAPI.save(mockDomainObject);37 expect(mockProvider.create).toHaveBeenCalled();38 expect(mockProvider.update).not.toHaveBeenCalled();39 });40 it("Calls 'update' on provider if object is not new", () => {41 mockDomainObject.persisted = Date.now() - FIFTEEN_MINUTES;42 mockDomainObject.modified = Date.now();43 objectAPI.save(mockDomainObject);44 expect(mockProvider.create).not.toHaveBeenCalled();45 expect(mockProvider.update).toHaveBeenCalled();46 });47 it("Does not persist if the object is unchanged", () => {48 mockDomainObject.persisted =49 mockDomainObject.modified = Date.now();50 objectAPI.save(mockDomainObject);51 expect(mockProvider.create).not.toHaveBeenCalled();52 expect(mockProvider.update).not.toHaveBeenCalled();53 });54 });55 });56 describe("The get function", () => {57 describe("when a provider is available", () => {58 let mockProvider;59 let mockInterceptor;60 let anotherMockInterceptor;61 let notApplicableMockInterceptor;62 beforeEach(() => {63 mockProvider = jasmine.createSpyObj("mock provider", [64 "get"65 ]);66 mockProvider.get.and.returnValue(Promise.resolve(mockDomainObject));67 mockInterceptor = jasmine.createSpyObj("mock interceptor", [68 "appliesTo",69 "invoke"70 ]);71 mockInterceptor.appliesTo.and.returnValue(true);72 mockInterceptor.invoke.and.callFake((identifier, object) => {73 return Object.assign({74 changed: true75 }, object);76 });77 anotherMockInterceptor = jasmine.createSpyObj("another mock interceptor", [78 "appliesTo",79 "invoke"80 ]);81 anotherMockInterceptor.appliesTo.and.returnValue(true);82 anotherMockInterceptor.invoke.and.callFake((identifier, object) => {83 return Object.assign({84 alsoChanged: true85 }, object);86 });87 notApplicableMockInterceptor = jasmine.createSpyObj("not applicable mock interceptor", [88 "appliesTo",89 "invoke"90 ]);91 notApplicableMockInterceptor.appliesTo.and.returnValue(false);92 notApplicableMockInterceptor.invoke.and.callFake((identifier, object) => {93 return Object.assign({94 shouldNotBeChanged: true95 }, object);96 });97 objectAPI.addProvider(TEST_NAMESPACE, mockProvider);98 objectAPI.addGetInterceptor(mockInterceptor);99 objectAPI.addGetInterceptor(anotherMockInterceptor);100 objectAPI.addGetInterceptor(notApplicableMockInterceptor);101 });102 it("Caches multiple requests for the same object", () => {103 expect(mockProvider.get.calls.count()).toBe(0);104 objectAPI.get(mockDomainObject.identifier);105 expect(mockProvider.get.calls.count()).toBe(1);106 objectAPI.get(mockDomainObject.identifier);107 expect(mockProvider.get.calls.count()).toBe(1);108 });109 it("applies any applicable interceptors", () => {110 expect(mockDomainObject.changed).toBeUndefined();111 objectAPI.get(mockDomainObject.identifier).then((object) => {112 expect(object.changed).toBeTrue();113 expect(object.alsoChanged).toBeTrue();114 expect(object.shouldNotBeChanged).toBeUndefined();115 });116 });117 });118 });...
Provider.spec.ts
Source:Provider.spec.ts
1import { Address } from "../../../../src/domain/entities/Address/Address";2import { Contact } from "../../../../src/domain/entities/Contact";3import { Provider } from "../../../../src/domain/entities/Provider";4import { EducationEnum } from "../../../../src/domain/enums/EducationEnum";5import { GenderEnum } from "../../../../src/domain/enums/GenderEnum";6import { MaritalStatusEnum } from "../../../../src/domain/enums/MaritalStatusEnum";7describe("Create provider", () => {8 it("Should be able to create a new provider", () => {9 const mockAddress: Address = {10 "publicArea": "TestPublicArea",11 "city": "TestCity",12 "state": "TestState",13 "postalCode": "TestPostalCode"14 };15 const mockContact: Contact = {16 "phoneNumber": 1133445566,17 "cellNumber": 11922334455,18 "emailAddress": "TestEmailAddress"19 };20 const mockProvider: Provider = {21 "firstName": "TestFirstName",22 "lastName": "TestLastName",23 "cpf": 11122233344,24 "birthDate": "1/11/1990",25 "gender": GenderEnum.OTHER,26 "maritalStatus": MaritalStatusEnum.ENGAGED,27 "education": EducationEnum.BACHELORS_DEGREE,28 "address": mockAddress,29 "contact": mockContact30 };31 const provider = new Provider(mockProvider);32 expect(provider).toBeInstanceOf(Provider);33 expect(provider.address).toBeInstanceOf(Address);34 expect(provider.contact).toBeInstanceOf(Contact);35 expect(typeof provider.birthDate).toBe('string');36 expect(typeof provider.firstName).toBe('string');37 expect(typeof provider.lastName).toBe('string');38 expect(typeof provider.cpf).toBe('number');39 expect(provider.firstName).toEqual(mockProvider.firstName);40 expect(provider.lastName).toEqual(mockProvider.lastName);41 expect(provider.cpf).toEqual(mockProvider.cpf);42 expect(provider.birthDate).toEqual(mockProvider.birthDate);43 expect(provider.gender).toEqual(mockProvider.gender);44 expect(provider.maritalStatus).toEqual(mockProvider.maritalStatus);45 expect(provider.education).toEqual(mockProvider.education);46 expect(provider.address).toEqual(mockProvider.address);47 expect(provider.contact).toEqual(mockProvider.contact);48 });...
Using AI Code Generation
1import { MockProvider } from 'ng-mocks';2import { MyService } from './my.service';3describe('MyService', () => {4 let service: MyService;5 beforeEach(() => {6 service = new MyService(MockProvider(MyService));7 });8 it('should be created', () => {9 expect(service).toBeTruthy();10 });11});
Using AI Code Generation
1import { MockProvider } from 'ng-mocks';2import { HttpClient } from '@angular/common/http';3describe('Test', () => {4 it('test', () => {5 const httpClient = MockProvider(HttpClient);6 expect(httpClient).toBeDefined();7 });8});9import { MockProvider } from 'ng-mocks';10import { HttpClient } from '@angular/common/http';11describe('Test', () => {12 it('test', () => {13 const httpClient = MockProvider(HttpClient);14 expect(httpClient).toBeDefined();15 });16});17import { MockProvider } from 'ng-mocks';18import { HttpClient } from '@angular/common/http';19describe('Test', () => {20 it('test', () => {21 const httpClient = MockProvider(HttpClient);22 expect(httpClient).toBeDefined();23 });24});25import { MockProvider } from 'ng-mocks';26import { HttpClient } from '@angular/common/http';27describe('Test', () => {28 it('test', () => {29 const httpClient = MockProvider(HttpClient);30 expect(httpClient).toBeDefined();31 });32});33import { MockProvider } from 'ng-mocks';34import { HttpClient } from '@angular/common/http';35describe('Test', () => {36 it('test', () => {37 const httpClient = MockProvider(HttpClient);38 expect(httpClient).toBeDefined();39 });40});41import { MockProvider } from 'ng-mocks';42import { HttpClient } from '@angular/common/http';43describe('Test', () => {44 it('test', () => {45 const httpClient = MockProvider(HttpClient);46 expect(httpClient).toBeDefined();47 });48});49import { MockProvider } from 'ng-mocks';50import { HttpClient } from '@angular/common/http';51describe('Test', () => {52 it('test', () => {53 const httpClient = MockProvider(HttpClient);54 expect(httpClient).toBeDefined();55 });
Using AI Code Generation
1import { MockProvider } from 'ng-mocks';2import { HttpClient } from '@angular/common/http';3import { Observable, of } from 'rxjs';4import { TestBed } from '@angular/core/testing';5describe('MockProvider', () => {6 it('should mock the http client', () => {7 const mockHttpClient = MockProvider(HttpClient, {8 get: () => of(['one', 'two', 'three']),9 });10 TestBed.configureTestingModule({11 { provide: HttpClient, useValue: mockHttpClient },12 });13 const httpClient = TestBed.inject(HttpClient);14 httpClient.get<string[]>('/someUrl').subscribe((result) => {15 expect(result).toEqual(['one', 'two', 'three']);16 });17 });18});19import { MockProvider } from 'ng-mocks';20import { HttpClient } from '@angular/common/http';21import { Observable, of } from 'rxjs';22import { TestBed } from '@angular/core/testing';23describe('MockProvider', () => {24 it('should mock the http client', () => {25 const mockHttpClient = MockProvider(HttpClient, {26 get: () => of(['one', 'two', 'three']),27 });28 TestBed.configureTestingModule({29 { provide: HttpClient, useValue: mockHttpClient },30 });31 const httpClient = TestBed.inject(HttpClient);32 httpClient.get<string[]>('/someUrl').subscribe((result) => {33 expect(result).toEqual(['one', 'two', 'three']);34 });35 });36});37import { MockProvider } from 'ng-mocks';38import { HttpClient } from '@angular/common/http';39import { Observable, of } from 'rxjs';40import {
Using AI Code Generation
1import { MockProvider } from 'ng-mocks';2import { MyService } from './my.service';3beforeEach(() => {4 TestBed.configureTestingModule({5 MockProvider(MyService, {6 method: () => 'mocked',7 }),8 });9});10import { Injectable } from '@angular/core';11@Injectable()12export class MyService {13 public method(): string {14 return 'real';15 }16}17import { MockProvider } from 'ng-mocks';18import { MyService } from './my.service';19describe('MyService', () => {20 it('should return mocked string', () => {21 const service = MockProvider(MyService, {22 method: () => 'mocked',23 });24 expect(service.method()).toEqual('mocked');25 });26});27import { MockProvider } from 'ng-mocks';28import { MyService } from './my.service';29describe('MyService', () => {30 it('should return mocked string', () => {31 const service = MockProvider(MyService, {32 method: () => 'mocked',33 });34 expect(service.method()).toEqual('mocked');35 });36});37import { MockProvider } from 'ng-mocks';38import { MyService } from './my.service';39describe('MyService', () => {40 it('should return mocked string', () => {41 const service = MockProvider(MyService, {42 method: () => 'mocked',43 });44 expect(service.method()).toEqual('mocked');45 });46});47import { MockProvider } from 'ng-mocks';48import { MyService } from './my.service';49describe('MyService', () => {50 it('should return mocked string', () => {51 const service = MockProvider(MyService, {52 method: () => 'mocked',53 });54 expect(service.method()).toEqual('mocked');55 });56});57import { MockProvider } from 'ng-m
Using AI Code Generation
1import { MockBuilder, MockRender, MockReset, MockInstance } from 'ng-mocks';2import { AppComponent } from './app.component';3import { TestService } from './test.service';4import { TestServiceMock } from './test.service.mock';5describe('AppComponent', () => {6 beforeEach(() => MockBuilder(AppComponent, TestService).mock(TestService, TestServiceMock));7 it('should create the app', () => {8 const fixture = MockRender(AppComponent);9 const app = fixture.point.componentInstance;10 expect(app).toBeTruthy();11 });12});13import { MockInstance } from 'ng-mocks';14import { TestService } from './test.service';15export const TestServiceMock = MockInstance(TestService, 'test', () => 'mocked test');16import { Injectable } from '@angular/core';17@Injectable({18})19export class TestService {20 constructor() { }21 test(): string {22 return 'test';23 }24}25import { Component, OnInit } from '@angular/core';26import { TestService } from './test.service';27@Component({28})29export class AppComponent implements OnInit {30 title = 'ng-mocks-test';31 test = '';32 constructor(private testService: TestService) { }33 ngOnInit(): void {34 this.test = this.testService.test();35 }36}37 {{title}}38 {{test}}
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!!