Best JavaScript code snippet using ng-mocks
index.ts
Source:index.ts  
1import bodyParser from 'body-parser'2import cors from 'cors'3import express from 'express'4import { createProxyMiddleware, fixRequestBody } from 'http-proxy-middleware'5import { Server } from 'node:http'6import {7  Moxy,8  Mock,9  LoggedRequest,10  HTTPMethod,11  MockResponseSetter,12  HTTP_METHODS,13} from './types'14const RES_MOCK_REGEX = /(\/.+)\/_mocks\/([a-z]+)$/15const RES_MOCKS_REGEX = /(\/.+)\/_mocks$/16export default function moxy(config?: {17  port?: number18  forward?: string19}): Moxy {20  const forward = config?.forward21  const port = config?.port ?? 800122  const app = express()23  let server: Server24  let mocks: Mock[] = []25  let requestLog: LoggedRequest[] = []26  function findMock(path: string, method: string): Mock | null {27    const mock = mocks.find(28      (m) => m.path === path && m.method === method.toLowerCase()29    )30    return mock || null31  }32  app.use(bodyParser.json())33  app.use(cors())34  app.get('/_log', (req, res) => {35    res.json({ log: moxyApi.log() })36  })37  app.get(/(\/.+)\/_log$/, (req, res) => {38    const path = req.params[0]39    res.json({ log: moxyApi.log(path), path })40  })41  app.delete('/_log', (req, res) => {42    moxyApi.clearLog()43    res.status(204).end()44  })45  app.put(RES_MOCK_REGEX, (req, res) => {46    const method = req.params[1].toLowerCase() as HTTPMethod47    const path = req.params[0]48    // Validate method49    if (!HTTP_METHODS.includes(method)) {50      res.status(400).json({ error: 'Invalid method' })51    }52    const existingMock = findMock(path, method)53    moxyApi.setMock(54      path,55      method,56      req.body.response as MockResponseSetter | undefined57    )58    if (existingMock) {59      // If mock overwritten60      res.status(200).end()61    } else {62      // If new mock63      res.status(201).end()64    }65  })66  // Delete single path-method mock67  app.delete(RES_MOCK_REGEX, (req, res) => {68    moxyApi.removeMock(req.params[0], req.params[1] as HTTPMethod)69    res.status(204).end()70  })71  // Delete all mocks from a path72  app.delete(RES_MOCKS_REGEX, (req, res) => {73    moxyApi.removeMock(req.params[0])74    res.status(204).end()75  })76  // Delete all mocks77  app.delete('/_mocks', (req, res) => {78    moxyApi.removeMock()79    res.status(204).end()80  })81  // Create logEntry and attach to request82  app.use((req, res, next) => {83    req.logEntry = {84      timestamp: new Date(),85      method: req.method,86      path: req.path,87      mocked: false,88      headers: {},89      response: {90        status: 0,91        headers: {},92      },93    }94    requestLog.push(req.logEntry)95    if (Object.keys(req.body).length) {96      req.logEntry.data = req.body97    }98    next()99  })100  app.use((req, res, next) => {101    const mock = findMock(req.path, req.method)102    if (mock) {103      if (req.logEntry) {104        req.logEntry.mocked = true105        req.logEntry.response.status = mock.response.status106        req.logEntry.response.data = mock.response.data107      }108      res.status(mock.response.status)109      res.json(mock.response.data)110    } else {111      next()112    }113  })114  if (forward) {115    app.use(116      createProxyMiddleware({117        target: forward,118        changeOrigin: true,119        logLevel: 'error',120        onProxyReq: fixRequestBody,121        onProxyRes: (proxyRes, req, res) => {122          const logEntry = req.logEntry123          if (logEntry) {124            logEntry.response.status = proxyRes.statusCode!125            logEntry.response.headers = proxyRes.headers126            if (127              proxyRes.headers['content-type']?.startsWith('application/json')128            ) {129              let data = ''130              proxyRes.on('data', (chunk) => {131                data += chunk132              })133              proxyRes.on('end', () => {134                try {135                  logEntry.response.data = JSON.parse(data)136                } catch (err) {137                  // Do nothing138                }139              })140            }141          }142        },143      })144    )145  }146  const moxyApi: Moxy = {147    start: () => {148      server = app.listen(port)149      return server150    },151    stop: async () => {152      return new Promise((resolve) => {153        server.close(() => resolve())154      })155    },156    mocks: <ResData>(path?: string): Mock<ResData>[] => {157      let myMocks = mocks as Mock<ResData>[]158      if (path) {159        myMocks = myMocks.filter((mock) => mock.path === path)160      }161      return myMocks162    },163    log: <ReqData, ResData>(path?: string, method?: HTTPMethod) => {164      let log = requestLog as LoggedRequest<ReqData, ResData>[]165      if (path) {166        log = log.filter((entry) => entry.path === path)167      }168      if (method) {169        log = log.filter((entry) => entry.method.toLowerCase() === method)170      }171      return log172    },173    clearLog: () => {174      requestLog = []175    },176    setMock: <ResData>(177      path: string,178      method: HTTPMethod = 'get',179      response: MockResponseSetter<ResData> = {}180    ) => {181      const existingMock = findMock(path, method)182      if (existingMock) {183        // Remove existing mock184        mocks = mocks.filter((m) => m !== existingMock)185      }186      // Add new mock187      mocks.push({188        method,189        path,190        response: {191          status: response.status ?? 200,192          headers: response.headers ?? [],193          data: response.data ?? null,194        },195      })196      return {197        removeMock: () => moxyApi.removeMock(path, method),198        log: <ReqData>() => moxyApi.log<ReqData, ResData>(path, method),199      }200    },201    removeMock: (path?: string, method?: HTTPMethod) => {202      if (path && method) {203        const existingMock = findMock(path, method)204        mocks = mocks.filter((mock) => mock !== existingMock)205      } else if (path) {206        mocks = mocks.filter((mock) => mock.path !== path)207      } else {208        mocks = []209      }210    },211  }212  return moxyApi213}...mocks.js
Source:mocks.js  
1import Emitter from 'api/emitter';2import EVENTS from 'api/constants/events';3import { PersistentStorage } from 'api/storage';4import { Mock } from 'api/models/mock';5import { Request } from 'api/models/request';6import find from 'lodash/find';7import filter from 'lodash/filter';8import remove from 'lodash/remove';9import isObject from 'lodash/isObject';10import isString from 'lodash/isString';11import isArray from 'lodash/isArray';12import omit from 'lodash/omit';13import cloneDeep from 'lodash/cloneDeep';14import assign from 'lodash/assign';15export class Mocks {16  init() {17    this.loadFromStorage();18    this._registerEvents();19  }20  _registerEvents() {21    Emitter.on(EVENTS.UPDATE_MOCK, this.loadFromStorage, this);22    Emitter.on(EVENTS.IMPORT, this.loadFromStorage, this);23    Emitter.on(EVENTS.STORAGE_PERSIST, this.loadFromStorage, this);24  }25  loadFromStorage() {26    this.all = PersistentStorage.dataTree.mocks27      .map((mock) => new Mock(mock));28    PersistentStorage.dataTree.mocks = this.all;29  }30  setMocks(mocks) {31    this.all = mocks.map((mock) => new Mock(mock));32    PersistentStorage.dataTree.mocks = this.all;33    PersistentStorage.persist();34  }35  find(options) {36    return find(this.all, options);37  }38  findAll(options) {39    const results = filter(this.all, options);40    if (!results) {41      return [];42    }43    return results;44  }45  addMock() {46    const newRequest = new Request({47      method: 'GET',48      url: '/',49      headers: { 'content-type': 'application/json' },50      origin: typeof window !== "undefined" ? window.location.origin : null51    });52    const newMock = this.mockRequest(newRequest);53    PersistentStorage.persist();54    return newMock;55  }56  mockRequest(request) {57    this.findAll({ requestHash: request.requestHash }).forEach((mock) => mock.disable());58    const mock = new Mock(request);59    this.all.push(mock);60    PersistentStorage.persist();61    return mock;62  }63  mergeMocks(mocks, options = {}) {64    for (const mock of mocks) {65      // deserialize json mock request body66      if (isObject(mock.response.body)) {67        mock.response.body = JSON.stringify(mock.response.body);68      }69      if (isObject(mock.params)) {70        mock.params = JSON.stringify(mock.params);71      }72      const existingMock = cloneDeep(find(this.all, { id: mock.id }));73      if (!existingMock) {74        this.all.push(new Mock(mock));75        continue;76      }77      const existingMockClone = cloneDeep(existingMock);78      const newMockClone = cloneDeep(mock);79      if (existingMockClone.response.body) {80        existingMockClone.response.body = existingMockClone.response.body.replace(/\s/g, '');81      }82      if (newMockClone.response.body) {83        newMockClone.response.body = newMockClone.response.body.replace(/\s/g, '');84      }85      const isMockEqual = JSON.stringify(newMockClone) === JSON.stringify(existingMockClone);86      if (existingMock && isMockEqual) {87        continue;88      } else if (existingMock && options.mode === 'append') {89        this.all.push(new Mock(omit(mock, ['id'])));90      } else if (existingMock) {91        const updatedMock = assign({}, existingMock, mock);92        this.updateMock(existingMock.id, updatedMock);93      } else {94        this.all.push(new Mock(mock));95      }96    }97    PersistentStorage.persist();98  }99  recapture(mockIds, cb = () => {}) {100    const done = (id) => {101      PersistentStorage.persist();102      cb(id);103    };104    mockIds.forEach((mockId) => this.find({ id: mockId }).recapture(done));105  }106  toggleMock(mockId) {107    const mock = this.find({ id: mockId });108    if (!mock.active) {109      this.findAll({ requestHash: mock.requestHash }).forEach((mock) => mock.disable());110    }111    mock.toggle();112    PersistentStorage.persist();113  }114  export(arg) {115    if (isString(arg)) {116      return this.find({ id: arg }).export();117    }118    if (isArray(arg)) {119      return arg.map((mockId) => this.find({ id: mockId }).export());120    }121    return this.all.map((mock) => mock.export());122  }123  updateMock(mockId, request) {124    this.find({ id: mockId }).update(request);125    PersistentStorage.persist();126  }127  duplicateMock(mockId, overrides = {}) {128    const mock = this.find({ id: mockId });129    const duplicatedMock = {130      ...omit(cloneDeep(mock), ['id']),131      name: mock.name ? `${mock.name} Copy` : mock.name,132      groupId: mock.groupId,133      ...overrides134    };135    this.mockRequest(duplicatedMock);136  }137  removeMock(mockId) {138    remove(this.all, { id: mockId });139    PersistentStorage.persist();140  }141  renameMock(mockId, newName) {142    this.find({ id: mockId }).rename(newName);143    PersistentStorage.persist();144  }145  getMatchingMocks(request) {146    const matches = [];147    for (let mock of this.all) {148      if (mock.matches({ url: request.url, params: request.body, method: request.method })) {149        matches.push(mock);150      }151    }152    return matches;153  }154}...rr-navigate-spec-migration.js
Source:rr-navigate-spec-migration.js  
1// call on a list of tests effected by rr-navigate-migration.js2// jscodeshift -t zenpayroll/script/rr-navigate-spec-migration.js --parser=tsx [...]3import {4  findJestMockForModule,5  insertAfterLastMockOrImport,6  insertBeforeMockNamed,7} from './jscodeshift-helpers';8/** @typedef { import('@types/jscodeshift').core } core */9/**10 * @param file {core.FileInfo}11 * @param api {core.API}12 **/13export default function transformer(file, api) {14  const j = api.jscodeshift;15  let root = j(file.source);16  // find all instances of expect(Payroll.router.navigate)17  const navigates = root.find(j.MemberExpression, {18    object: { object: { name: 'Payroll' }, property: { name: 'router' } },19    property: { name: 'navigate' },20  });21  let needsMockPush = false;22  let needsMockReplace = false;23  navigates.forEach(p => {24    if (p.parent.value.callee.name === 'expect') {25      if (26        p.parent.parent.value.property.name === 'toHaveBeenCalledWith' &&27        p.parent.parent.parent.value.arguments.length === 2 &&28        p.parent.parent.parent.value.arguments[1].type === 'ObjectExpression'29      ) {30        const options = p.parent.parent.parent.value.arguments[1];31        const jOptions = j(options);32        if (33          jOptions.find(j.ObjectProperty, { key: { name: 'trigger' }, value: { value: false } })34            .length35        ) {36          throw new Error('Cannot handle trigger: false option');37        } else if (38          jOptions.find(j.ObjectProperty, { key: { name: 'replace' }, value: { value: true } })39            .length40        ) {41          needsMockReplace = true;42          p.replace('mockHistoryReplace');43        } else {44          needsMockPush = true;45          p.replace('mockHistoryPush');46        }47      } else {48        needsMockPush = true;49        p.replace('mockHistoryPush');50      }51      const args = p.parent.parent.value.arguments;52      if (args && args.length > 1) {53        p.parent.parent.value.arguments = [args[0]];54      }55    }56  });57  if (needsMockPush || needsMockReplace) {58    let existingMock = findJestMockForModule('react-router-dom', j, root);59    if (existingMock.length) {60      const existingUseHistory = j(existingMock.paths()[0]).find(j.ObjectProperty, {61        key: { name: 'useHistory' },62      });63      if (existingUseHistory.length) {64        // console.log('has existing useHistory');65        const existingPush = j(existingUseHistory.paths()[0]).find(j.ObjectProperty, {66          key: { name: 'push' },67        });68        if (existingPush.length) {69          // console.log('existing push', existingPush.paths()[0].value.value);70          if (existingPush.paths()[0].value.value.name !== 'mockHistoryPush') {71            throw new Error('is already mocked but not called mockHistoryPush');72          }73        } else {74          throw new Error('no existing push');75        }76      } else {77        const properties = [];78        if (needsMockPush) {79          properties.push(j.objectProperty(j.identifier('push'), j.identifier('mockHistoryPush')));80        }81        if (needsMockReplace) {82          properties.push(83            j.objectProperty(j.identifier('replace'), j.identifier('mockHistoryReplace')),84          );85        }86        existingMock87          .paths()[0]88          .value.arguments[1].body.properties.push(89            j.objectProperty(90              j.identifier('useHistory'),91              j.arrowFunctionExpression([], j.objectExpression(properties)),92            ),93          );94        if (needsMockPush) {95          insertBeforeMockNamed(j, root, 'react-router-dom', 'const mockHistoryPush = jest.fn();');96        }97        if (needsMockReplace) {98          insertBeforeMockNamed(99            j,100            root,101            'react-router-dom',102            'const mockHistoryReplace = jest.fn();',103          );104        }105      }106    } else {107      // find mock position: after last mock or after last import108      insertAfterLastMockOrImport(109        j,110        root,111        "const mockHistoryPush = jest.fn();\njest.mock('react-router-dom', () => ({\n  useHistory: () => ({ push: mockHistoryPush }),\n}));",112      );113    }114  }115  return root.toSource();...Using AI Code Generation
1import { existingMock } from 'ng-mocks';2describe('MyComponent', () => {3  beforeEach(() => {4    TestBed.configureTestingModule({5        {6          useValue: existingMock(MyService),7        },8    });9  });10});11import { existingMock } from 'ng-mocks';12describe('MyComponent', () => {13  beforeEach(() => {14    TestBed.configureTestingModule({15        {16          useValue: existingMock(MyService),17        },18    });19  });20});21import { existingMock } from 'ng-mocks';22describe('MyComponent', () => {23  beforeEach(() => {24    TestBed.configureTestingModule({25        {26          useValue: existingMock(MyService),27        },28    });29  });30});31import { existingMock } from 'ng-mocks';32describe('MyComponent', () => {33  beforeEach(() => {34    TestBed.configureTestingModule({35        {36          useValue: existingMock(MyService),37        },38    });39  });40});41import { existingMock } from 'ng-mocks';42describe('MyComponent', () => {43  beforeEach(() => {44    TestBed.configureTestingModule({45        {46          useValue: existingMock(MyService),47        },48    });49  });50});51import { existingMock } from 'ng-mocks';52describe('MyComponent', () => {53  beforeEach(() => {54    TestBed.configureTestingModule({55        {56          useValue: existingMock(MyService),57        },58    });59  });60});61importUsing AI Code Generation
1import {existingMock} from 'ng-mocks';2import {AppComponent} from './app.component';3describe('AppComponent', () => {4  it('should create the app', () => {5    const fixture = existingMock(AppComponent);6    const app = fixture.debugElement.componentInstance;7    expect(app).toBeTruthy();8  });9});10import {existingMock} from 'ng-mocks';11import {AppComponent} from './app.component';12import {TestBed, ComponentFixture} from '@angular/core/testing';13describe('AppComponent', () => {14  let fixture: ComponentFixture<AppComponent>;15  beforeEach(() => {16    TestBed.configureTestingModule({17    });18    fixture = existingMock(AppComponent);19  });20  it('should create the app', () => {21    const app = fixture.debugElement.componentInstance;22    expect(app).toBeTruthy();23  });24});25import {existing} from 'ng-mocks';26import {AppComponent} from './app.component';27import {TestBed, ComponentFixture} from '@angular/core/testing';28describe('AppComponent', () => {29  let fixture: ComponentFixture<AppComponent>;30  beforeEach(() => {31    fixture = existing(AppComponent);32  });33  it('should create the app', () => {34    const app = fixture.debugElement.componentInstance;35    expect(app).toBeTruthy();36  });37});Using AI Code Generation
1import { existingMock, MockBuilder } from 'ng-mocks';2import { MyComponent } from './my.component';3describe('MyComponent', () => {4  beforeEach(() => MockBuilder(MyComponent));5  it('should render', () => {6    const fixture = existingMock(MyComponent);7    fixture.detectChanges();8    expect(fixture.nativeElement.querySelector('h1').textContent).toEqual('Hello World!');9  });10});Using AI Code Generation
1import { existingMock } from 'ng-mocks';2import { MyService } from './my-service';3describe('existingMock', () => {4  it('should return the existing mock', () => {5    const existingMock = existingMock(MyService);6    expect(existingMock).toEqual(jasmine.any(MyService));7  });8});9import { Injectable } from '@angular/core';10@Injectable()11export class MyService {12  constructor() {13    console.log('MyService created');14  }15}16import { MyService } from './my-service';17describe('MyService', () => {18  it('should create', () => {19    const myService = new MyService();20    expect(myService).toBeTruthy();21  });22});23import { existingMock } from 'ng-mocks';24import { MyService } from './my-service';25describe('existingMock', () => {26  it('should return the existing mock', () => {27    const existingMock = existingMock(MyService);28    expect(existingMock).toEqual(jasmine.any(MyService));29  });30});31import { Injectable } from '@angular/core';32@Injectable()33export class MyService {34  constructor() {35    console.log('MyService created');36  }37}38import { MyService } from './my-service';39describe('MyService', () => {40  it('should create', () => {41    const myService = new MyService();42    expect(myService).toBeTruthy();43  });44});45import { existingMock } from 'ng-mocks';46import { MyService } from './my-service';47describe('existingMock', () => {48  it('should return the existing mock', () => {49    const existingMock = existingMock(MyService);50    expect(existingMock).toEqual(jasmine.any(MyService));51  });52});53import { Injectable } from '@angular/core';54@Injectable()55export class MyService {56  constructor() {57    console.log('MyService created');58  }59}Using AI Code Generation
1import {existingMock} from 'ng-mocks';2describe('test', () => {3  it('test', () => {4    const mock = existingMock('mock');5    expect(mock).toBeDefined();6  });7});8import {existingMock} from 'ng-mocks';9describe('test', () => {10  it('test', () => {11    const mock = existingMock('mock');12    expect(mock).toBeDefined();13  });14});15import {existingMock} from 'ng-mocks';16describe('test', () => {17  it('test', () => {18    const mock = existingMock('mock');19    expect(mock).toBeDefined();20  });21});22import {existingMock} from 'ng-mocks';23describe('test', () => {24  it('test', () => {25    const mock = existingMock('mock');26    expect(mock).toBeDefined();27  });28});29import {existingMock} from 'ng-mocks';30describe('test', () => {31  it('test', () => {32    const mock = existingMock('mock');33    expect(mock).toBeDefined();34  });35});36import {existingMock} from 'ng-mocks';37describe('test', () => {38  it('test', () => {39    const mock = existingMock('mock');40    expect(mock).toBeDefined();41  });42});43import {existingMock} from 'ng-mocks';44describe('test', () => {45  it('test', () => {46    const mock = existingMock('mock');47    expect(mock).toBeDefined();48  });49});50import {existingMock} from 'ng-mocks';51describe('test', () => {52  it('test', () => {53    const mock = existingMock('mock');54    expect(mock).toBeDefined();55  });56});Using AI Code Generation
1import { existingMock } from 'ng-mocks';2describe('test', () => {3  it('should use existingMock', () => {4    const mock = existingMock('mock');5    expect(mock).toBeDefined();6  });7});Using AI Code Generation
1const mock = existingMock('MockService');2mock.mockReturnValue('mock value');3const mock = ngMocks.guts('MockService');4mock.mockReturnValue('mock value');5const mock = ngMocks.stub('MockService');6mock.mockReturnValue('mock value');7const mock = ngMocks.mock('MockService');8mock.mockReturnValue('mock value');9const mock = ngMocks.findInstance('MockService');10mock.mockReturnValue('mock value');11const mock = ngMocks.find('MockService');12mock.mockReturnValue('mock value');13const mock = ngMocks.get('MockService');14mock.mockReturnValue('mock value');15const mock = ngMocks.default('MockService');16mock.mockReturnValue('mock value');17const mock = ngMocks.redefine('MockService');18mock.mockReturnValue('mock value');19const mock = ngMocks.override('MockService');20mock.mockReturnValue('mock value');21const mock = ngMocks.replace('MockService');22mock.mockReturnValue('mock value');23const mock = ngMocks.reprovide('MockService');24mock.mockReturnValue('mock value');25const mock = ngMocks.reinstall('MockService');26mock.mockReturnValue('mock value');27const mock = ngMocks.remock('MockService');28mock.mockReturnValue('mock value');29const mock = ngMocks.redefineAll('MockService');30mock.mockReturnValue('mock value');31const mock = ngMocks.overrideAll('MockService');32mock.mockReturnValue('mock value');33const mock = ngMocks.replaceAll('MockService');34mock.mockReturnValue('mock value');35const mock = ngMocks.reprovideAll('MockService');36mock.mockReturnValue('mock value');37const mock = ngMocks.reinstallAll('MockService');38mock.mockReturnValue('mock value');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!!
