Best JavaScript code snippet using ts-auto-mock
local-repository-dropbox.service.ts
Source:local-repository-dropbox.service.ts
1import { Injectable } from "@angular/core";2import { User } from "../_model/user";3import { Observable } from "rxjs";4import { LocalRepository } from "../_model/local-repository";5import { ClassInstance } from "../_model/meta/class";6import { Dropbox } from "dropbox";7import { LocalRepositoryService } from "./local-repository.service";8@Injectable({9 providedIn: "root",10})11export class LocalRepositoryDropboxService extends LocalRepositoryService {12 FILE_PATH: string = "/db.json";13 localRepositorys: LocalRepository[] = [];14 constructor() {15 super();16 }17 private findByVolunteer(volunteer: User) {18 const observable = new Observable((subscriber) => {19 const successFunction = (localRepository: LocalRepository) => {20 subscriber.next(localRepository);21 subscriber.complete();22 };23 const failureFunction = (error: any) => {24 subscriber.error(error);25 subscriber.complete();26 };27 try {28 if (volunteer.dropboxToken) {29 let dbx = new Dropbox({ accessToken: volunteer.dropboxToken });30 dbx.filesListFolder({ path: "" }).then((filesList) => {31 if (32 filesList.entries.findIndex(33 (entry) => entry.name === "db.json"34 ) == -135 ) {36 // create and read37 dbx38 .filesUpload({39 contents: JSON.stringify({ repository: [] }, null, 2),40 path: this.FILE_PATH,41 mode: { ".tag": "overwrite" },42 autorename: false,43 mute: false,44 })45 .then(() => {46 dbx.filesDownload({ path: this.FILE_PATH }).then((file) => {47 let reader = new FileReader();48 let blob: Blob = (<any>file).fileBlob;49 reader.addEventListener("loadend", () => {50 this.localRepositorys = [];51 if (this.isValidJson(<string>reader.result)) {52 let parsedJSON = JSON.parse(<string>reader.result);53 parsedJSON.repository.forEach((lr: LocalRepository) => {54 this.localRepositorys.push(lr);55 });56 }57 if (58 this.localRepositorys.findIndex(59 (l) => l.id === volunteer.id60 ) === -161 ) {62 let newRepo = new LocalRepository(63 volunteer.id,64 volunteer.username65 );66 this.localRepositorys.push(newRepo);67 this.saveToDropbox(volunteer);68 successFunction(newRepo);69 } else {70 successFunction(71 this.localRepositorys.find(72 (localRepository: LocalRepository) => {73 return localRepository.id === volunteer.id;74 }75 )76 );77 }78 });79 reader.readAsText(blob);80 });81 })82 .catch((error) => {83 console.error(error);84 alert("Failed to save to dropbox");85 });86 } else {87 // only read88 dbx.filesDownload({ path: this.FILE_PATH }).then((file) => {89 let reader = new FileReader();90 let blob: Blob = (<any>file).fileBlob;91 reader.addEventListener("loadend", () => {92 this.localRepositorys = [];93 if (this.isValidJson(<string>reader.result)) {94 let parsedJSON = JSON.parse(<string>reader.result);95 parsedJSON.repository.forEach((lr: LocalRepository) => {96 this.localRepositorys.push(lr);97 });98 }99 if (100 this.localRepositorys.findIndex(101 (l) => l.id === volunteer.id102 ) === -1103 ) {104 let newRepo = new LocalRepository(105 volunteer.id,106 volunteer.username107 );108 this.localRepositorys.push(newRepo);109 this.saveToDropbox(volunteer);110 successFunction(newRepo);111 } else {112 successFunction(113 this.localRepositorys.find(114 (localRepository: LocalRepository) => {115 return localRepository.id === volunteer.id;116 }117 )118 );119 }120 });121 reader.readAsText(blob);122 });123 }124 });125 } else {126 failureFunction(null);127 }128 } catch (error) {129 failureFunction(error);130 }131 });132 return observable;133 }134 public findClassInstancesByVolunteer(volunteer: User) {135 const observable = new Observable((subscriber) => {136 const failureFunction = (error: any) => {137 subscriber.error(error);138 subscriber.complete();139 };140 const successFunction = (localRepository: LocalRepository) => {141 if (!localRepository) {142 subscriber.next([]);143 } else {144 subscriber.next(localRepository.classInstances);145 subscriber.complete();146 }147 };148 this.findByVolunteer(volunteer)149 .toPromise()150 .then((localRepository: LocalRepository) =>151 successFunction(localRepository)152 )153 .catch((error: any) => failureFunction(error));154 });155 return observable;156 }157 public synchronizeSingleClassInstance(158 volunteer: User,159 classInstance: ClassInstance160 ) {161 const observable = new Observable((subscriber) => {162 const failureFunction = (error: any) => {163 subscriber.error(error);164 subscriber.complete();165 };166 this.findByVolunteer(volunteer)167 .toPromise()168 .then((localRepository: LocalRepository) => {169 try {170 localRepository.classInstances.push(classInstance);171 this.localRepositorys.forEach((lr, index) => {172 if (lr.id == localRepository.id) {173 this.localRepositorys[index] = localRepository;174 }175 });176 this.saveToDropbox(volunteer);177 subscriber.next(localRepository.classInstances);178 subscriber.complete();179 } catch (error) {180 failureFunction(error);181 }182 })183 .catch((error: any) => failureFunction(error));184 });185 return observable;186 }187 public getSingleClassInstance(volunteer: User, classInstanceId: string) {188 const observable = new Observable((subscriber) => {189 const failureFunction = (error: any) => {190 subscriber.error(error);191 subscriber.complete();192 };193 this.findByVolunteer(volunteer)194 .toPromise()195 .then((localRepository: LocalRepository) => {196 let classInstance = localRepository.classInstances.find((ci) => {197 return ci.id === classInstanceId;198 });199 subscriber.next(classInstance);200 subscriber.complete();201 })202 .catch((error: any) => failureFunction(error));203 });204 return observable;205 }206 public synchronizeClassInstances(207 volunteer: User,208 classInstances: ClassInstance[]209 ) {210 const observable = new Observable((subscriber) => {211 const failureFunction = (error: any) => {212 subscriber.error(error);213 subscriber.complete();214 };215 this.findByVolunteer(volunteer)216 .toPromise()217 .then((localRepository: LocalRepository) => {218 try {219 localRepository.classInstances = [220 ...localRepository.classInstances,221 ...classInstances,222 ];223 this.localRepositorys.forEach((lr, index) => {224 if (lr.id == localRepository.id) {225 this.localRepositorys[index] = localRepository;226 }227 });228 this.saveToDropbox(volunteer);229 subscriber.next(localRepository.classInstances);230 subscriber.complete();231 } catch (error) {232 failureFunction(error);233 }234 })235 .catch((error: any) => failureFunction(error));236 });237 return observable;238 }239 public overrideClassInstances(240 volunteer: User,241 classInstances: ClassInstance[]242 ) {243 const observable = new Observable((subscriber) => {244 const failureFunction = (error: any) => {245 subscriber.error(error);246 subscriber.complete();247 };248 this.findByVolunteer(volunteer)249 .toPromise()250 .then((localRepository: LocalRepository) => {251 try {252 localRepository.classInstances = classInstances;253 this.localRepositorys.forEach((lr, index) => {254 if (lr.id == localRepository.id) {255 this.localRepositorys[index] = localRepository;256 }257 });258 this.saveToDropbox(volunteer);259 subscriber.next(localRepository.classInstances);260 subscriber.complete();261 } catch (error) {262 failureFunction(error);263 }264 })265 .catch((error: any) => failureFunction(error));266 });267 return observable;268 }269 public removeSingleClassInstance(volunteer: User, classInstanceId: string) {270 const observable = new Observable((subscriber) => {271 const failureFunction = (error: any) => {272 subscriber.error(error);273 subscriber.complete();274 };275 this.findByVolunteer(volunteer)276 .toPromise()277 .then((localRepository: LocalRepository) => {278 try {279 localRepository.classInstances.forEach((ci, index, object) => {280 if (ci.id === classInstanceId) {281 object.splice(index, 1);282 }283 });284 this.localRepositorys.forEach((lr, index) => {285 if (lr.id == localRepository.id) {286 this.localRepositorys[index] = localRepository;287 }288 });289 this.saveToDropbox(volunteer);290 subscriber.next(localRepository.classInstances);291 subscriber.complete();292 } catch (error) {293 failureFunction(error);294 }295 })296 .catch((error: any) => failureFunction(error));297 });298 return observable;299 }300 public removeClassInstances(volunteer: User, classInstanceIds: string[]) {301 const observable = new Observable((subscriber) => {302 const failureFunction = (error: any) => {303 subscriber.error(error);304 subscriber.complete();305 };306 this.findByVolunteer(volunteer)307 .toPromise()308 .then((localRepository: LocalRepository) => {309 try {310 localRepository.classInstances = localRepository.classInstances.filter(311 (c) => classInstanceIds.indexOf(c.id) < 0312 );313 this.localRepositorys.forEach((lr, index) => {314 if (lr.id == localRepository.id) {315 this.localRepositorys[index] = localRepository;316 }317 });318 this.saveToDropbox(volunteer);319 subscriber.next(localRepository.classInstances);320 subscriber.complete();321 } catch (error) {322 failureFunction(error);323 }324 })325 .catch((error: any) => failureFunction(error));326 });327 return observable;328 }329 private saveToDropbox(volunteer: User) {330 let dbx = new Dropbox({ accessToken: volunteer.dropboxToken });331 let content = { repository: this.localRepositorys };332 dbx333 .filesUpload({334 contents: JSON.stringify(content, null, 2),335 path: this.FILE_PATH,336 mode: { ".tag": "overwrite" },337 autorename: false,338 mute: false,339 })340 .then(() => {341 // console.error("successfully written to dropbox");342 })343 .catch((error) => {344 console.error(error);345 alert("Failed to save to dropbox");346 });347 }348 isValidJson(str) {349 try {350 JSON.parse(str);351 } catch (e) {352 return false;353 }354 return true;355 }356 isConnected(credentials: any) {357 throw new Error("Method not implemented.");358 }...
pr-checkout-controller.test.js
Source:pr-checkout-controller.test.js
1import React from 'react';2import {shallow} from 'enzyme';3import {BarePullRequestCheckoutController} from '../../lib/controllers/pr-checkout-controller';4import {cloneRepository, buildRepository} from '../helpers';5import BranchSet from '../../lib/models/branch-set';6import Branch, {nullBranch} from '../../lib/models/branch';7import RemoteSet from '../../lib/models/remote-set';8import Remote from '../../lib/models/remote';9import {GitError} from '../../lib/git-shell-out-strategy';10import {repositoryBuilder} from '../builder/graphql/repository';11import {pullRequestBuilder} from '../builder/graphql/pr';12import * as reporterProxy from '../../lib/reporter-proxy';13import repositoryQuery from '../../lib/controllers/__generated__/prCheckoutController_repository.graphql';14import pullRequestQuery from '../../lib/controllers/__generated__/prCheckoutController_pullRequest.graphql';15describe('PullRequestCheckoutController', function() {16 let localRepository, children;17 beforeEach(async function() {18 localRepository = await buildRepository(await cloneRepository());19 children = sinon.spy();20 });21 function buildApp(override = {}) {22 const branches = new BranchSet([23 new Branch('master', nullBranch, nullBranch, true),24 ]);25 const remotes = new RemoteSet([26 new Remote('origin', 'git@github.com:atom/github.git'),27 ]);28 const props = {29 repository: repositoryBuilder(repositoryQuery).build(),30 pullRequest: pullRequestBuilder(pullRequestQuery).build(),31 localRepository,32 isAbsent: false,33 isLoading: false,34 isPresent: true,35 isMerging: false,36 isRebasing: false,37 branches,38 remotes,39 children,40 ...override,41 };42 return <BarePullRequestCheckoutController {...props} />;43 }44 it('is disabled if the repository is loading or absent', function() {45 const wrapper = shallow(buildApp({isAbsent: true}));46 const [op] = children.lastCall.args;47 assert.isFalse(op.isEnabled());48 assert.strictEqual(op.getMessage(), 'No repository found');49 wrapper.setProps({isAbsent: false, isLoading: true});50 const [op1] = children.lastCall.args;51 assert.isFalse(op1.isEnabled());52 assert.strictEqual(op1.getMessage(), 'Loading');53 wrapper.setProps({isAbsent: false, isLoading: false, isPresent: false});54 const [op2] = children.lastCall.args;55 assert.isFalse(op2.isEnabled());56 assert.strictEqual(op2.getMessage(), 'No repository found');57 });58 it('is disabled if the local repository is merging or rebasing', function() {59 const wrapper = shallow(buildApp({isMerging: true}));60 const [op0] = children.lastCall.args;61 assert.isFalse(op0.isEnabled());62 assert.strictEqual(op0.getMessage(), 'Merge in progress');63 wrapper.setProps({isMerging: false, isRebasing: true});64 const [op1] = children.lastCall.args;65 assert.isFalse(op1.isEnabled());66 assert.strictEqual(op1.getMessage(), 'Rebase in progress');67 });68 it('is disabled if the pullRequest has no headRepository', function() {69 shallow(buildApp({70 pullRequest: pullRequestBuilder(pullRequestQuery).nullHeadRepository().build(),71 }));72 const [op] = children.lastCall.args;73 assert.isFalse(op.isEnabled());74 assert.strictEqual(op.getMessage(), 'Pull request head repository does not exist');75 });76 it('is disabled if the current branch already corresponds to the pull request', function() {77 const upstream = Branch.createRemoteTracking('remotes/origin/feature', 'origin', 'refs/heads/feature');78 const branches = new BranchSet([79 new Branch('current', upstream, upstream, true),80 ]);81 const remotes = new RemoteSet([82 new Remote('origin', 'git@github.com:aaa/bbb.git'),83 ]);84 const pullRequest = pullRequestBuilder(pullRequestQuery)85 .headRefName('feature')86 .headRepository(r => {87 r.owner(o => o.login('aaa'));88 r.name('bbb');89 })90 .build();91 shallow(buildApp({92 pullRequest,93 branches,94 remotes,95 }));96 const [op] = children.lastCall.args;97 assert.isFalse(op.isEnabled());98 assert.strictEqual(op.getMessage(), 'Current');99 });100 it('recognizes a current branch even if it was pulled from the refs/pull/... ref', function() {101 const upstream = Branch.createRemoteTracking('remotes/origin/pull/123/head', 'origin', 'refs/pull/123/head');102 const branches = new BranchSet([103 new Branch('current', upstream, upstream, true),104 ]);105 const remotes = new RemoteSet([106 new Remote('origin', 'git@github.com:aaa/bbb.git'),107 ]);108 const repository = repositoryBuilder(repositoryQuery)109 .owner(o => o.login('aaa'))110 .name('bbb')111 .build();112 const pullRequest = pullRequestBuilder(pullRequestQuery)113 .number(123)114 .headRefName('feature')115 .headRepository(r => {116 r.owner(o => o.login('ccc'));117 r.name('ddd');118 })119 .build();120 shallow(buildApp({121 repository,122 pullRequest,123 branches,124 remotes,125 }));126 const [op] = children.lastCall.args;127 assert.isFalse(op.isEnabled());128 assert.strictEqual(op.getMessage(), 'Current');129 });130 it('creates a new remote, fetches a PR branch, and checks it out into a new local branch', async function() {131 const upstream = Branch.createRemoteTracking('remotes/origin/current', 'origin', 'refs/heads/current');132 const branches = new BranchSet([133 new Branch('current', upstream, upstream, true),134 ]);135 const remotes = new RemoteSet([136 new Remote('origin', 'git@github.com:aaa/bbb.git'),137 ]);138 sinon.stub(localRepository, 'addRemote').resolves(new Remote('ccc', 'git@github.com:ccc/ddd.git'));139 sinon.stub(localRepository, 'fetch').resolves();140 sinon.stub(localRepository, 'checkout').resolves();141 const pullRequest = pullRequestBuilder(pullRequestQuery)142 .number(456)143 .headRefName('feature')144 .headRepository(r => {145 r.owner(o => o.login('ccc'));146 r.name('ddd');147 })148 .build();149 shallow(buildApp({150 pullRequest,151 branches,152 remotes,153 }));154 sinon.spy(reporterProxy, 'incrementCounter');155 const [op] = children.lastCall.args;156 await op.run();157 assert.isTrue(localRepository.addRemote.calledWith('ccc', 'git@github.com:ccc/ddd.git'));158 assert.isTrue(localRepository.fetch.calledWith('refs/heads/feature', {remoteName: 'ccc'}));159 assert.isTrue(localRepository.checkout.calledWith('pr-456/ccc/feature', {160 createNew: true,161 track: true,162 startPoint: 'refs/remotes/ccc/feature',163 }));164 assert.isTrue(reporterProxy.incrementCounter.calledWith('checkout-pr'));165 });166 it('fetches a PR branch from an existing remote and checks it out into a new local branch', async function() {167 sinon.stub(localRepository, 'fetch').resolves();168 sinon.stub(localRepository, 'checkout').resolves();169 const branches = new BranchSet([170 new Branch('current', nullBranch, nullBranch, true),171 ]);172 const remotes = new RemoteSet([173 new Remote('origin', 'git@github.com:aaa/bbb.git'),174 new Remote('existing', 'git@github.com:ccc/ddd.git'),175 ]);176 const pullRequest = pullRequestBuilder(pullRequestQuery)177 .number(789)178 .headRefName('clever-name')179 .headRepository(r => {180 r.owner(o => o.login('ccc'));181 r.name('ddd');182 })183 .build();184 shallow(buildApp({185 pullRequest,186 branches,187 remotes,188 }));189 sinon.spy(reporterProxy, 'incrementCounter');190 const [op] = children.lastCall.args;191 await op.run();192 assert.isTrue(localRepository.fetch.calledWith('refs/heads/clever-name', {remoteName: 'existing'}));193 assert.isTrue(localRepository.checkout.calledWith('pr-789/ccc/clever-name', {194 createNew: true,195 track: true,196 startPoint: 'refs/remotes/existing/clever-name',197 }));198 assert.isTrue(reporterProxy.incrementCounter.calledWith('checkout-pr'));199 });200 it('checks out an existing local branch that corresponds to the pull request', async function() {201 sinon.stub(localRepository, 'pull').resolves();202 sinon.stub(localRepository, 'checkout').resolves();203 const currentUpstream = Branch.createRemoteTracking('remotes/origin/current', 'origin', 'refs/heads/current');204 const branches = new BranchSet([205 new Branch('current', currentUpstream, currentUpstream, true),206 new Branch('existing', Branch.createRemoteTracking('remotes/upstream/pull/123', 'upstream', 'refs/heads/yes')),207 new Branch('wrong/remote', Branch.createRemoteTracking('remotes/wrong/pull/123', 'wrong', 'refs/heads/yes')),208 new Branch('wrong/ref', Branch.createRemoteTracking('remotes/upstream/pull/123', 'upstream', 'refs/heads/no')),209 ]);210 const remotes = new RemoteSet([211 new Remote('origin', 'git@github.com:aaa/bbb.git'),212 new Remote('upstream', 'git@github.com:ccc/ddd.git'),213 new Remote('wrong', 'git@github.com:eee/fff.git'),214 ]);215 const pullRequest = pullRequestBuilder(pullRequestQuery)216 .number(456)217 .headRefName('yes')218 .headRepository(r => {219 r.owner(o => o.login('ccc'));220 r.name('ddd');221 })222 .build();223 shallow(buildApp({224 pullRequest,225 branches,226 remotes,227 }));228 sinon.spy(reporterProxy, 'incrementCounter');229 const [op] = children.lastCall.args;230 await op.run();231 assert.isTrue(localRepository.checkout.calledWith('existing'));232 assert.isTrue(localRepository.pull.calledWith('refs/heads/yes', {remoteName: 'upstream', ffOnly: true}));233 assert.isTrue(reporterProxy.incrementCounter.calledWith('checkout-pr'));234 });235 it('squelches git errors', async function() {236 sinon.stub(localRepository, 'addRemote').rejects(new GitError('handled by the pipeline'));237 shallow(buildApp({}));238 // Should not throw239 const [op] = children.lastCall.args;240 await op.run();241 assert.isTrue(localRepository.addRemote.called);242 });243 it('propagates non-git errors', async function() {244 sinon.stub(localRepository, 'addRemote').rejects(new Error('not handled by the pipeline'));245 shallow(buildApp({}));246 const [op] = children.lastCall.args;247 await assert.isRejected(op.run(), /not handled by the pipeline/);248 assert.isTrue(localRepository.addRemote.called);249 });...
local-repository-jsonServer.service.ts
Source:local-repository-jsonServer.service.ts
1import { Injectable } from "@angular/core";2import { HttpClient } from "@angular/common/http";3import { Observable } from "rxjs";4import { LocalRepository } from "../_model/local-repository";5import { isNullOrUndefined } from "util";6import { ClassInstance } from "../_model/meta/class";7import { User } from "../_model/user";8import { LocalRepositoryService } from "./local-repository.service";9import { environment } from "environments/environment";10@Injectable({11 providedIn: "root",12})13export class LocalRepositoryJsonServerService extends LocalRepositoryService {14 private apiUrl = environment.JSON_SERVER_URL;15 constructor(private http: HttpClient) {16 super();17 }18 public async isConnected() {19 try {20 await this.http.get(this.apiUrl).toPromise();21 return true;22 } catch (error) {23 return false;24 }25 }26 private findByVolunteer(volunteer: User) {27 const observable = new Observable((subscriber) => {28 const successFunction = (localRepository: LocalRepository) => {29 subscriber.next(localRepository);30 subscriber.complete();31 };32 const failureFunction = (error: any) => {33 subscriber.error(error);34 subscriber.complete();35 };36 this.http37 .get(this.apiUrl)38 .toPromise()39 .then((localRepositorys: LocalRepository[]) => {40 if (localRepositorys.findIndex((l) => l.id === volunteer.id) === -1) {41 let newRepo = new LocalRepository(volunteer.id, volunteer.username);42 this.http.post(this.apiUrl, newRepo).toPromise();43 successFunction(newRepo);44 } else {45 successFunction(46 localRepositorys.find((localRepository: LocalRepository) => {47 return localRepository.id === volunteer.id;48 })49 );50 }51 })52 .catch((error: any) => {53 failureFunction(error);54 });55 });56 return observable;57 }58 public findClassInstancesByVolunteer(volunteer: User) {59 const observable = new Observable((subscriber) => {60 const failureFunction = (error: any) => {61 subscriber.error(error);62 subscriber.complete();63 };64 const successFunction = (localRepository: LocalRepository) => {65 if (isNullOrUndefined(localRepository)) {66 subscriber.next([]);67 } else {68 subscriber.next(localRepository.classInstances);69 subscriber.complete();70 }71 };72 this.findByVolunteer(volunteer)73 .toPromise()74 .then((localRepository: LocalRepository) =>75 successFunction(localRepository)76 )77 .catch((error: any) => failureFunction(error));78 });79 return observable;80 }81 public synchronizeSingleClassInstance(82 volunteer: User,83 classInstance: ClassInstance84 ) {85 const observable = new Observable((subscriber) => {86 const failureFunction = (error: any) => {87 subscriber.error(error);88 subscriber.complete();89 };90 this.findByVolunteer(volunteer)91 .toPromise()92 .then((localRepository: LocalRepository) => {93 localRepository.classInstances.push(classInstance);94 this.http95 .put(`${this.apiUrl}/${localRepository.id}`, localRepository)96 .toPromise()97 .then(() => subscriber.complete())98 .catch((error: any) => failureFunction(error));99 subscriber.next(localRepository.classInstances);100 })101 .catch((error: any) => failureFunction(error));102 });103 return observable;104 }105 public getSingleClassInstance(volunteer: User, classInstanceId: string) {106 const observable = new Observable((subscriber) => {107 const failureFunction = (error: any) => {108 subscriber.error(error);109 subscriber.complete();110 };111 this.findByVolunteer(volunteer)112 .toPromise()113 .then((localRepository: LocalRepository) => {114 let classInstance = localRepository.classInstances.find((ci) => {115 return ci.id === classInstanceId;116 });117 subscriber.next(classInstance);118 subscriber.complete();119 })120 .catch((error: any) => failureFunction(error));121 });122 return observable;123 }124 public synchronizeClassInstances(125 volunteer: User,126 classInstances: ClassInstance[]127 ) {128 const observable = new Observable((subscriber) => {129 const failureFunction = (error: any) => {130 subscriber.error(error);131 subscriber.complete();132 };133 this.findByVolunteer(volunteer)134 .toPromise()135 .then((localRepository: LocalRepository) => {136 localRepository.classInstances = [137 ...localRepository.classInstances,138 ...classInstances,139 ];140 this.http141 .put(`${this.apiUrl}/${localRepository.id}`, localRepository)142 .toPromise()143 .then(() => subscriber.complete())144 .catch((error: any) => failureFunction(error));145 subscriber.next(localRepository.classInstances);146 })147 .catch((error: any) => failureFunction(error));148 });149 return observable;150 }151 public overrideClassInstances(152 volunteer: User,153 classInstances: ClassInstance[]154 ) {155 const observable = new Observable((subscriber) => {156 const failureFunction = (error: any) => {157 subscriber.error(error);158 subscriber.complete();159 };160 this.findByVolunteer(volunteer)161 .toPromise()162 .then((localRepository: LocalRepository) => {163 localRepository.classInstances = classInstances;164 this.http165 .put(`${this.apiUrl}/${localRepository.id}`, localRepository)166 .toPromise()167 .then(() => subscriber.complete())168 .catch((error: any) => failureFunction(error));169 subscriber.next(localRepository.classInstances);170 })171 .catch((error: any) => failureFunction(error));172 });173 return observable;174 }175 public removeSingleClassInstance(volunteer: User, classInstanceId: string) {176 const observable = new Observable((subscriber) => {177 const failureFunction = (error: any) => {178 subscriber.error(error);179 subscriber.complete();180 };181 this.findByVolunteer(volunteer)182 .toPromise()183 .then((localRepository: LocalRepository) => {184 localRepository.classInstances.forEach((ci, index, object) => {185 if (ci.id === classInstanceId) {186 object.splice(index, 1);187 }188 });189 this.http190 .put(`${this.apiUrl}/${localRepository.id}`, localRepository)191 .toPromise()192 .then(() => subscriber.complete())193 .catch((error: any) => failureFunction(error));194 subscriber.next(localRepository.classInstances);195 })196 .catch((error: any) => failureFunction(error));197 });198 return observable;199 }200 public removeClassInstances(volunteer: User, classInstanceIds: string[]) {201 const observable = new Observable((subscriber) => {202 const failureFunction = (error: any) => {203 subscriber.error(error);204 subscriber.complete();205 };206 this.findByVolunteer(volunteer)207 .toPromise()208 .then((localRepository: LocalRepository) => {209 localRepository.classInstances = localRepository.classInstances.filter(210 (c) => classInstanceIds.indexOf(c.id) < 0211 );212 this.http213 .put(`${this.apiUrl}/${localRepository.id}`, localRepository)214 .toPromise()215 .then(() => subscriber.complete())216 .catch((error: any) => failureFunction(error));217 subscriber.next(localRepository.classInstances);218 })219 .catch((error: any) => failureFunction(error));220 });221 return observable;222 }...
Using AI Code Generation
1import {localRepository} from 'ts-auto-mock';2import {createMock} from 'ts-auto-mock';3const mock:MyInterface = createMock<MyInterface>();4const mock2:MyInterface = localRepository.get<MyInterface>('MyInterface');5const mock3:MyInterface = createMock<MyInterface>();6const mock4:MyInterface = localRepository.get<MyInterface>('MyInterface');7import {createMock} from 'ts-auto-mock';8const mock:MyInterface = createMock<MyInterface>();9import {createMock} from 'ts-auto-mock';10const mock:MyInterface = createMock<MyInterface>('MyInterface');11import {createMock} from 'ts-auto-mock';12const mock:MyInterface = createMock<MyInterface>('MyInterface', {13 method: () => 'my custom implementation'14});15import {createMock} from 'ts-auto-mock';16const mock:MyInterface = createMock<MyInterface>({17 method: () => 'my custom implementation'18});
Using AI Code Generation
1import { localRepository } from 'ts-auto-mock';2const mock = localRepository.getMock<TestInterface>();3import { localRepository } from 'ts-auto-mock';4const mock = localRepository.getMock<TestInterface>();5type FunctionMock<T extends (...args: any[]) => any> = T & {6 mock: Mock<ReturnType<T>>;7};8type TestInterface = {9 test: (a: string, b: number) => boolean;10};11const mock: FunctionMock<TestInterface['test']> = jest.fn();12mock.mockReturnValue(true);13type ClassMock<T extends new (...args: any[]) => any> = T & {14 mock: Mock<InstanceType<T>>;15};16class TestClass {17 test(a: string, b: number): boolean {18 return true;19 }20}21const mock: ClassMock<typeof TestClass> = jest.fn();22mock.mockReturnValue(true);23type PrivateClassMock<T extends new (...args: any[]) => any> = T & {24 mock: Mock<InstanceType<T>>;25};26class TestClass {27 private constructor() {}28 test(a: string, b: number): boolean {29 return true;30 }31}32const mock: PrivateClassMock<typeof TestClass> = jest.fn();33mock.mockReturnValue(true);
Using AI Code Generation
1import { localRepository } from 'ts-auto-mock';2import { User } from './user';3describe('User', () => {4 it('should be defined', () => {5 expect(User).toBeDefined();6 });7 it('should be created', () => {8 const user = localRepository(User);9 expect(user).toBeDefined();10 });11});
Using AI Code Generation
1import { localRepository } from 'ts-auto-mock/localRepository';2import { Test1 } from './test1';3describe('Test1', () => {4 it('should create an instance', () => {5 const repository = localRepository<Test1>();6 expect(repository).toBeTruthy();7 });8});9import { localRepository } from 'ts-auto-mock/localRepository';10import { Test2 } from './test2';11describe('Test2', () => {12 it('should create an instance', () => {13 const repository = localRepository<Test2>();14 expect(repository).toBeTruthy();15 });16});17 at Object.<anonymous> (src/app/test1.spec.ts:5:25)18 at Object.asyncJestTest (node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:102:37)19 at resolve (node_modules/jest-jasmine2/build/queueRunner.js:46:12)20 at new Promise (<anonymous>)21 at mapper (node_modules/jest-jasmine2/build/queueRunner.js:34:19)22 at processTicksAndRejections (internal/process/task_queues.js:93:5)23import { localRepository } from 'ts-auto-mock/localRepository';24import { Test1 } from './test1';25import { Test1Repository } from './test1.repository';26describe('Test1', () => {27 it('should create an instance', () =>
Using AI Code Generation
1import {Mock} from 'ts-auto-mock';2import {TestClass} from './test2';3describe('test', () => {4 it('should create a mock', () => {5 const mock: TestClass = Mock.ofType<TestClass>();6 expect(mock).toBeDefined();7 });8});9import {Mock} from 'ts-auto-mock';10import {TestClass} from './test3';11describe('test', () => {12 it('should create a mock', () => {13 const mock: TestClass = Mock.ofType<TestClass>();14 expect(mock).toBeDefined();15 });16});17import {Mock} from 'ts-auto-mock';18import {TestClass} from './test1';19describe('test', () => {20 it('should create a mock', () => {21 const mock: TestClass = Mock.ofType<TestClass>();22 expect(mock).toBeDefined();23 });24});25 at getMock (node_modules/ts-auto-mock/dist/utils/mock.ts:13:15)26 at getMock (node_modules/ts-auto-mock/dist/utils/mock.ts:13:15)27 at getMock (node_modules/ts-auto-mock/dist/utils/mock.ts:13:15)28 at getMock (node_modules/ts-auto-mock/dist/utils/mock.ts:13:15)29 at getMock (node_modules/ts-auto-mock/dist/utils/mock.ts:13:15)30 at getMock (node_modules/ts-auto-mock/dist/utils/mock.ts:13:15)31 at getMock (node_modules/ts-auto-mock/dist/utils/mock.ts:13:15)32 at getMock (node_modules/ts-auto-mock/dist/utils/mock.ts:13:15)33 at getMock (node_modules/ts-auto-mock/dist/utils/mock.ts:13:15)34 at getMock (node_modules/ts-auto-mock/dist/utils/mock.ts:13:15)35"paths": {36 }
Using AI Code Generation
1import { localRepository } from 'ts-auto-mock';2const repository = localRepository({3});4console.log(repository.get('name'));5console.log(repository.get('age'));6import { localRepository } from 'ts-auto-mock';7class Person {8 constructor(public name: string, public age: number) {}9}10const repository = localRepository(Person);11console.log(repository.get('name'));12console.log(repository.get('age'));13import { localRepository } from 'ts-auto-mock';14class Person {15 constructor(public name: string, public age: number) {}16}17const repository = localRepository(Person, {18});19console.log(repository.get('name'));20console.log(repository.get('age'));21import { localRepository } from 'ts-auto-mock';22class Person {23 constructor(public name: string, public age: number) {}24}25const repository = localRepository(Person, {26});27console.log(repository.get('name'));28console.log(repository.get('age'));29import { localRepository, MockRepository } from 'ts-auto-mock';30class Person {31 constructor(public name: string, public age: number) {}32}33const repository = localRepository(Person, {34});35console.log(repository.get('name'));36console.log(repository.get('age'));
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!!