Best JavaScript code snippet using apimocker
InMemoryLinkIndex.deadLinks.test.ts
Source:InMemoryLinkIndex.deadLinks.test.ts
1const _path = require('path');2import * as tmoq from 'typemoq';3import { InMemoryLinkIndex } from "./InMemoryLinkIndex";4import { MockFile } from "../mocks/MockFile";5import { DefaultMultiIndex } from "./DefaultMultiIndex";6import { createFileSystem, FileSystem } from "../utils/FileSystem";7describe('InMemoryLinkIndex, dead links, mocked filesystem', () => {8 let fileSystem: tmoq.IMock<FileSystem>;9 let linkIndex: InMemoryLinkIndex;10 const setupLinks = (fileLinks: MockFile[]) => {11 for (const file of fileLinks) {12 linkIndex.addFile(file.path(), file.text());13 fileSystem.setup(f => f.fileExists(file.path())).returns(() => true);14 }15 linkIndex.finalise();16 };17 describe('posix paths, markdown links', () => {18 if (process.platform === 'win32') { return; }19 beforeEach(() => {20 fileSystem = tmoq.Mock.ofType<FileSystem>();21 linkIndex = new InMemoryLinkIndex();22 });23 it('finds dead link', () => {24 setupLinks([25 new MockFile('/a.md', '[](/b.txt)')26 ]);27 const deadLinks = linkIndex.findAllDeadLinks();28 expect(deadLinks).toHaveLength(1);29 expect(deadLinks[0].sourcePath).toBe('/a.md');30 expect(deadLinks[0].targetPath).toBe('/b.txt');31 });32 it('finds no dead links', () => {33 setupLinks([34 new MockFile('/a.md', '[](/b.txt)'),35 new MockFile('/b.txt', '')36 ]);37 const deadLinks = linkIndex.findAllDeadLinks();38 expect(deadLinks).toHaveLength(0);39 });40 it('links to subdirs work', () => {41 setupLinks([42 new MockFile('/a.md', '[](/b/c/e.txt)'),43 new MockFile('/b/c/e.txt', '')44 ]);45 const deadLinks = linkIndex.findAllDeadLinks();46 expect(deadLinks).toHaveLength(0);47 });48 it('links to parent dirs work', () => {49 setupLinks([50 new MockFile('/b/c/e.txt', '[](/a.md)'),51 new MockFile('/a.md', '')52 ]);53 const deadLinks = linkIndex.findAllDeadLinks();54 expect(deadLinks).toHaveLength(0);55 });56 it('supports relative links to parent dirs', () => {57 setupLinks([58 new MockFile('/b/c/e.txt', '[](../../a.md)'),59 new MockFile('/a.md', '')60 ]);61 const deadLinks = linkIndex.findAllDeadLinks();62 expect(deadLinks).toHaveLength(0);63 });64 it('supports relative links to subdirs', () => {65 setupLinks([66 new MockFile('/a/b.md', '[](c/d.txt)'),67 new MockFile('/a/c/d.txt', '')68 ]);69 const deadLinks = linkIndex.findAllDeadLinks();70 expect(deadLinks).toHaveLength(0);71 });72 it('supports non-note files', () => {73 setupLinks([74 new MockFile('/a/b.md', '[](c.png)'),75 new MockFile('/a/c.png', '')76 ]);77 const deadLinks = linkIndex.findAllDeadLinks();78 expect(deadLinks).toHaveLength(0);79 });80 });81 describe('posix paths, wiki links', () => {82 if (process.platform === 'win32') { return; }83 beforeEach(() => {84 fileSystem = tmoq.Mock.ofType<FileSystem>();85 linkIndex = new InMemoryLinkIndex();86 });87 it('finds dead link', () => {88 setupLinks([89 new MockFile('/a.md', '[[blah]]')90 ]);91 const deadLinks = linkIndex.findAllDeadLinks();92 expect(deadLinks).toHaveLength(1);93 expect(deadLinks[0].sourcePath).toBe('/a.md');94 expect(deadLinks[0].targetPath).toBe('blah');95 });96 it('finds no dead links', () => {97 setupLinks([98 new MockFile('/a.md', '[[b]]'),99 new MockFile('/b.txt', '')100 ]);101 const deadLinks = linkIndex.findAllDeadLinks();102 expect(deadLinks).toHaveLength(0);103 });104 it('links to subdirs work', () => {105 setupLinks([106 new MockFile('/a.md', '[[e]]'),107 new MockFile('/b/c/e.txt', '')108 ]);109 const deadLinks = linkIndex.findAllDeadLinks();110 expect(deadLinks).toHaveLength(0);111 });112 it('links to parent dirs work', () => {113 setupLinks([114 new MockFile('/b/c/e.txt', '[[a]]'),115 new MockFile('/a.md', '')116 ]);117 const deadLinks = linkIndex.findAllDeadLinks();118 expect(deadLinks).toHaveLength(0);119 });120 });121 describe('windows paths, markdown links', () => {122 if (process.platform !== 'win32') { return; }123 beforeEach(() => {124 fileSystem = tmoq.Mock.ofType<FileSystem>();125 linkIndex = new InMemoryLinkIndex();126 });127 it('finds dead link', () => {128 setupLinks([129 new MockFile('c:\\a.md', '[](c:\\b.txt)')130 ]);131 const deadLinks = linkIndex.findAllDeadLinks();132 expect(deadLinks).toHaveLength(1);133 expect(deadLinks[0].sourcePath).toBe('c:\\a.md');134 expect(deadLinks[0].targetPath).toBe('c:\\b.txt');135 });136 it('finds no dead links', () => {137 setupLinks([138 new MockFile('c:\\a.md', '[](c:\\b.txt)'),139 new MockFile('c:\\b.txt', '')140 ]);141 const deadLinks = linkIndex.findAllDeadLinks();142 expect(deadLinks).toHaveLength(0);143 });144 it('links to subdirs work', () => {145 setupLinks([146 new MockFile('c:\\a.md', '[](c:\\b\\c\\e.txt)'),147 new MockFile('c:\\b\\c\\e.txt', '')148 ]);149 const deadLinks = linkIndex.findAllDeadLinks();150 expect(deadLinks).toHaveLength(0);151 });152 it('links to parent dirs work', () => {153 setupLinks([154 new MockFile('c:\\b\\c\\e.txt', '[](c:\\a.md)'),155 new MockFile('c:\\a.md', '')156 ]);157 const deadLinks = linkIndex.findAllDeadLinks();158 expect(deadLinks).toHaveLength(0);159 });160 it('supports relative links to parent dirs', () => {161 setupLinks([162 new MockFile('c:\\b\\c\\e.txt', '[](..\\..\\a.md)'),163 new MockFile('c:\\a.md', '')164 ]);165 const deadLinks = linkIndex.findAllDeadLinks();166 expect(deadLinks).toHaveLength(0);167 });168 it('supports relative links to subdirs', () => {169 setupLinks([170 new MockFile('c:\\a\\b.md', '[](c\\d.txt)'),171 new MockFile('c:\\a\\c\\d.txt', '')172 ]);173 const deadLinks = linkIndex.findAllDeadLinks();174 expect(deadLinks).toHaveLength(0);175 });176 it('supports non-note files', () => {177 setupLinks([178 new MockFile('c:\\a\\b.md', '[](c.png)'),179 new MockFile('c:\\a\\c.png', '')180 ]);181 const deadLinks = linkIndex.findAllDeadLinks();182 expect(deadLinks).toHaveLength(0);183 });184 });185 describe('windows paths, wiki links', () => {186 if (process.platform !== 'win32') { return; }187 beforeEach(() => {188 fileSystem = tmoq.Mock.ofType<FileSystem>();189 linkIndex = new InMemoryLinkIndex();190 });191 it('finds dead link', () => {192 setupLinks([193 new MockFile('c:\\a.md', '[[blah]]')194 ]);195 const deadLinks = linkIndex.findAllDeadLinks();196 expect(deadLinks).toHaveLength(1);197 expect(deadLinks[0].sourcePath).toBe('c:\\a.md');198 expect(deadLinks[0].targetPath).toBe('blah');199 });200 it('finds no dead links', () => {201 setupLinks([202 new MockFile('c:\\a.md', '[[b]]'),203 new MockFile('c:\\b.txt', '')204 ]);205 const deadLinks = linkIndex.findAllDeadLinks();206 expect(deadLinks).toHaveLength(0);207 });208 it('links to subdirs work', () => {209 setupLinks([210 new MockFile('c:\\a.md', '[[e]]'),211 new MockFile('c:\\b\\c\\e.txt', '')212 ]);213 const deadLinks = linkIndex.findAllDeadLinks();214 expect(deadLinks).toHaveLength(0);215 });216 it('links to parent dirs work', () => {217 setupLinks([218 new MockFile('c:\\b\\c\\e.txt', '[[a]]'),219 new MockFile('c:\\a.md', '')220 ]);221 const deadLinks = linkIndex.findAllDeadLinks();222 expect(deadLinks).toHaveLength(0);223 });224 });...
files.controller.spec.ts
Source:files.controller.spec.ts
1import {2 ForbiddenException,3 NotFoundException,4 StreamableFile,5} from '@nestjs/common';6import { ConfigService } from '@nestjs/config';7import { Test, TestingModule } from '@nestjs/testing';8import { getRepositoryToken } from '@nestjs/typeorm';9import { CommonConfigService } from '../common/common.config';10import { CommonService } from '../common/common.service';11import { File } from './entities/file.entity';12import { FilesController } from './files.controller';13import { FilesService } from './files.service';14import { Readable } from 'node:stream';15const mockRes = {16 set: jest.fn(),17};18describe('FilesController', () => {19 let controller: FilesController;20 let service: FilesService;21 beforeEach(async () => {22 const module: TestingModule = await Test.createTestingModule({23 controllers: [FilesController],24 providers: [25 FilesService,26 CommonService,27 CommonConfigService,28 ConfigService,29 {30 provide: getRepositoryToken(File),31 useValue: {},32 },33 ],34 }).compile();35 controller = module.get<FilesController>(FilesController);36 service = module.get<FilesService>(FilesService);37 });38 it('should be defined', () => {39 expect(controller).toBeDefined();40 expect(service).toBeDefined();41 });42 describe('findOne', () => {43 it('should return a file', async () => {44 const mockFile = new File();45 mockFile.deleteKey = 'abcdef';46 mockFile.deletePass = 'ghijkl';47 mockFile.fileName = 'fileName.txt';48 mockFile.fileType = 'text/plain';49 mockFile.id = 0;50 mockFile.stringId = 'abcdef';51 jest.spyOn(service, 'findOne').mockResolvedValue(mockFile);52 jest53 .spyOn(service, 'streamFile')54 .mockReturnValue(new StreamableFile(Buffer.from('')));55 expect(await controller.findOne('abcdef', mockRes)).toBeInstanceOf(56 StreamableFile,57 );58 });59 describe('otherwise', () => {60 it('should throw the "NotFoundException"', async () => {61 jest.spyOn(service, 'findOne').mockReturnValue(null);62 await expect(63 controller.findOne('abcdef', mockRes),64 ).rejects.toBeInstanceOf(NotFoundException);65 });66 });67 });68 describe('create', () => {69 it('should create a file', async () => {70 const file = new File();71 file.deleteKey = 'abcdef';72 file.deletePass = 'ghijkl';73 file.fileName = 'fileName.txt';74 file.fileType = 'text/plain';75 file.id = 0;76 file.stringId = 'abcdef';77 jest.spyOn(service, 'create').mockResolvedValue(file);78 const mockFile: Express.Multer.File = {79 buffer: Buffer.from(''),80 destination: './',81 fieldname: 'file',82 filename: 'alksjdhfaksjdfhasfd',83 mimetype: 'text/plain',84 originalname: 'file.txt',85 path: './uploads/files/alksjdhfaksjdfhasfd',86 size: 123123,87 stream: new Readable(),88 encoding: 'utf-8',89 };90 await expect(controller.create(mockFile)).resolves.toBeInstanceOf(File);91 });92 });93 describe('deleteCode', () => {94 it('should return a file by delete key', async () => {95 const mockFile = new File();96 mockFile.deleteKey = 'abcdef';97 mockFile.deletePass = 'ghijkl';98 mockFile.fileName = 'fileName.txt';99 mockFile.fileType = 'text/plain';100 mockFile.id = 0;101 mockFile.stringId = 'abcdef';102 jest.spyOn(service, 'findOneByDeleteKey').mockResolvedValue(mockFile);103 expect(await controller.deleteCode('abcdef')).toBe('ghijkl');104 });105 });106 describe('delete', () => {107 it('should delete a file by delete key', async () => {108 const mockFile = new File();109 mockFile.deleteKey = 'abcdef';110 mockFile.deletePass = 'ghijkl';111 mockFile.fileName = 'fileName.txt';112 mockFile.fileType = 'text/plain';113 mockFile.id = 0;114 mockFile.stringId = 'abcdef';115 jest.spyOn(service, 'delete').mockResolvedValue();116 jest.spyOn(service, 'deleteFile').mockResolvedValue();117 jest.spyOn(service, 'findOneByDeleteKey').mockResolvedValue(mockFile);118 await expect(controller.delete('abcdef', 'ghijkl')).resolves.toBe(119 'Deleted',120 );121 });122 it('reject if missing password', async () => {123 const mockFile = new File();124 mockFile.deleteKey = 'abcdef';125 mockFile.deletePass = 'ghijkl';126 mockFile.fileName = 'fileName.txt';127 mockFile.fileType = 'text/plain';128 mockFile.id = 0;129 mockFile.stringId = 'abcdef';130 jest.spyOn(service, 'delete').mockResolvedValue();131 jest.spyOn(service, 'findOneByDeleteKey').mockResolvedValue(mockFile);132 await expect(controller.delete('abcdef', '')).rejects.toBeInstanceOf(133 ForbiddenException,134 );135 });136 describe('otherwise', () => {137 it('should throw the "NotFoundException"', async () => {138 jest139 .spyOn(service, 'findOneByDeleteKey')140 .mockRejectedValue(new NotFoundException());141 await expect(142 controller.delete('mnopqr', 'ghijkl'),143 ).rejects.toBeInstanceOf(NotFoundException);144 });145 });146 });...
helpers.ts
Source:helpers.ts
1import * as fs from "fs";2import fsExtra from "fs-extra";3import path from "path";4import { DependencyGraph } from "../../../src/internal/solidity/dependencyGraph";5import { Parser } from "../../../src/internal/solidity/parse";6import {7 ResolvedFile,8 Resolver,9} from "../../../src/internal/solidity/resolver";10import * as taskTypes from "../../../src/types/builtin-tasks";11const projectRoot = fs.realpathSync(".");12export class MockFile {13 public readonly sourceName: string;14 public readonly absolutePath: string;15 constructor(16 public name: string,17 public versionPragmas: string[],18 public libraryName?: string19 ) {20 this.sourceName = `contracts/${name}.sol`;21 this.absolutePath = path.join(projectRoot, "contracts", `${name}.sol`);22 }23}24export async function createMockData(25 files: Array<{26 file: MockFile;27 dependencies?: MockFile[];28 }>29): Promise<[taskTypes.DependencyGraph, ResolvedFile[]]> {30 const filesMap = new Map<31 MockFile,32 {33 dependencies: MockFile[];34 }35 >();36 for (const { file, dependencies } of files) {37 filesMap.set(file, {38 dependencies: dependencies ?? [],39 });40 }41 const mockFileToResolvedFile: Map<MockFile, ResolvedFile> = new Map();42 const importsMap = new Map<string, ResolvedFile>();43 const resolvedFiles = [...filesMap.keys()].map((mockFile) => {44 const resolvedFile = new ResolvedFile(45 mockFile.sourceName,46 mockFile.absolutePath,47 {48 rawContent: "mock file",49 imports: filesMap50 .get(mockFile)!51 .dependencies.map((dependency) => `./${dependency.name}.sol`),52 versionPragmas: mockFile.versionPragmas,53 },54 "<content-hash-mock-file>",55 new Date(),56 mockFile.libraryName,57 mockFile.libraryName === undefined ? undefined : "1.2.3"58 );59 mockFileToResolvedFile.set(mockFile, resolvedFile);60 importsMap.set(`./${mockFile.name}.sol`, resolvedFile);61 return resolvedFile;62 });63 const resolver = new Resolver(64 projectRoot,65 new Parser(),66 (absolutePath: string) =>67 fsExtra.readFile(absolutePath, { encoding: "utf8" })68 );69 resolver.resolveImport = async (from: ResolvedFile, imported: string) => {70 const importedFile = importsMap.get(imported);71 if (importedFile === undefined) {72 throw new Error(`${imported} is not mocked`);73 }74 return importedFile;75 };76 const dependencyGraph = await DependencyGraph.createFromResolvedFiles(77 resolver,78 resolvedFiles79 );80 return [dependencyGraph, resolvedFiles];...
Using AI Code Generation
1var apimocker = require('apimocker');2var path = require('path');3var fs = require('fs');4var http = require('http');5var https = require('https');6var express = require('express');7var app = express();8var bodyParser = require('body-parser');9var cors = require('cors');10var config = {11 defaultResponseHeaders: {12 },13 watchOptions: {14 },15};16app.use(cors());17app.use(bodyParser.urlencoded({ extended: false }))18app.use(bodyParser.json())19app.get('/api/mock', function(req, res) {20 apimocker.mockFile(req, res, config.mockDirectory + '/mock.json');21});22app.get('/api/mock/:id', function(req, res) {23 apimocker.mockFile(req, res, config.mockDirectory + '/mock.json');24});25app.post('/api/mock', function(req, res) {26 apimocker.mockFile(req, res, config.mockDirectory + '/mock.json');27});28app.put('/api/mock/:id', function(req, res) {29 apimocker.mockFile(req, res, config.mockDirectory + '/mock.json');30});31app.delete('/api/mock/:id', function(req, res) {32 apimocker.mockFile(req, res, config.mockDirectory + '/mock.json');33});34var server;35if (config.ssl) {36 server = https.createServer({37 key: fs.readFileSync(config.sslKey),38 cert: fs.readFileSync(config.sslCert),39 }, app);40} else {41 server = http.createServer(app);42}43server.listen(config.port, function() {44 console.log('Server started on port: ' + config.port);
Using AI Code Generation
1var mockFile = require('apimocker').mockFile;2var mockServer = require('apimocker').mockServer;3var mockData = require('apimocker').mockData;4var mockServerPort = 8080;5var mockServerHost = 'localhost';6mockServer({7});8mockFile('/api/getUsers', 'getUsers.json');
Using AI Code Generation
1var mockFile = require('apimocker').mockFile;2var express = require('express');3var app = express();4app.use(mockFile('mocks'));5app.listen(3000);6var mockFile = require('apimocker').mockFile;7var express = require('express');8var app = express();9app.use(mockFile('mocks'));10app.listen(3000);11var mockDir = require('apimocker').mockDir;12var express = require('express');13var app = express();14app.use(mockDir('mocks'));15app.listen(3000);16var mockDir = require('apimocker').mockDir;17var express = require('express');18var app = express();19app.use(mockDir('mocks'));20app.listen(3000);21var mockDir = require('apimocker').mockDir;22var express = require('express');23var app = express();24app.use(mockDir('mocks'));25app.listen(3000);26var mockDir = require('apimocker').mockDir;27var express = require('express');28var app = express();29app.use(mockDir('mocks'));30app.listen(3000);31var mockDir = require('apimocker').mockDir;32var express = require('express');33var app = express();34app.use(mockDir('mocks'));35app.listen(3000);
Using AI Code Generation
1var mockFile = require('apimocker').mockFile;2mockFile('/api/v1/contacts', 'contacts.json');3### .mockFile(path, filename)4### .mockFile(path, filename, statusCode)5### .mockResponse(path, response)6### .mockResponse(path, response, statusCode)7### .mockResponse(path, response, statusCode, headers)8### .mockError(path, error)9### .mockError(path, error, statusCode)10### .mockError(path, error, statusCode, headers)11### .mockStatusCode(path, statusCode)12### .mockStatusCode(path, statusCode, headers)13### .mockStatusCode(path, statusCode, headers, body)14### .mockHeaders(path, headers)15### .mockHeaders(path, headers, statusCode)16### .mockHeaders(path, headers, statusCode, body)17### .mockBody(path, body)18### .mockBody(path, body, statusCode)19### .mockBody(path, body, statusCode, headers)
Using AI Code Generation
1var mockFile = require('apimocker').mockFile;2var mockFolder = 'mocks';3mockFile(mockFolder, '/api/v1.0/users', 'get', 'users.json', 200);4mockFile(mockFolder, '/api/v1.0/users', 'post', 'users.json', 200);5mockFile(mockFolder, '/api/v1.0/users', 'delete', 'users.json', 200);6mockFile(mockFolder, '/api/v1.0/users', 'put', 'users.json', 200);7mockFile(mockFolder, '/api/v1.0/users/:id', 'get', 'users.json', 200);8mockFile(mockFolder, '/api/v1.0/users/:id', 'post', 'users.json', 200);9mockFile(mockFolder, '/api/v1.0/users/:id', 'delete', 'users.json', 200);10mockFile(mockFolder, '/api/v1.0/users/:id', 'put', 'users.json', 200);11mockFile(mockFolder, '/api/v1.0/users/:id/roles', 'get', 'users.json', 200);12mockFile(mockFolder, '/api/v1.0/users/:id/roles', 'post', 'users.json', 200);13mockFile(mockFolder, '/api/v1.0/users/:id/roles', 'delete', 'users.json', 200);14mockFile(mockFolder, '/api/v1.0/users/:id/roles', 'put', 'users.json', 200);15mockFile(mockFolder, '/api/v1.0/users/:id/roles/:roleId', 'get', 'users.json', 200);16mockFile(mockFolder, '/api/v1.0/users/:id/roles/:roleId', 'post', 'users.json', 200);17mockFile(mockFolder, '/api/v1.0/users/:id/roles/:roleId', 'delete', 'users.json', 200);18mockFile(mockFolder, '/api/v1.0/users/:id/roles/:roleId', 'put', 'users.json', 200);
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!!