Best JavaScript code snippet using ng-mocks
scanner-store.ts
Source:scanner-store.ts
1import { ScannerConfig, Manga, ScanSource, Chapter } from '../database/entity';2import { ScannerV2 } from './ScannerV2';3import PQueue from 'p-queue/dist';4import moment from 'moment';5import { Database } from '../database/Database';6import logger from '../logger';7import { ScannerNotifier } from '../events/ScannerNotifier';8import { ChapterScannerFactory } from './ChapterScannerFactory';9/**10 * Scan a configuration and Store in the database11 * @param config the configuration to scan12 */13export async function scanAndStore(config: ScannerConfig) {14 const scanner = new ScannerV2(config);15 const storageQueue = new PQueue({16 concurrency: 1,17 autoStart: false18 });19 const db = new Database();20 db.connect(config.name).then( () => {21 storageQueue.start();22 logger.info(`Scan start ${config.name}`);23 }).catch(e => {24 logger.error(`: scanAndStore -> ${e.message} : ${e.stack}`);25 });26 try {27 const notifier = new ScannerNotifier(db);28 const startTime = moment();29 const mangas = await scanner.listMangas();30 for (const manga of mangas) {31 const m = new Manga();32 m.name = manga.name;33 const s = new ScanSource();34 s.name = config.name;35 s.scannerConfig = config;36 s.link = manga.link;37 s.manga = m;38 const [source, tags] = await scanner.scanMangaSource(s, false);39 logger.debug('scanned manga : ', source, tags);40 storageQueue.add( () => createOrUpdate(41 db,42 notifier,43 source as ScanSource,44 tags as string[])45 );46 }47 // close after usage48 storageQueue.onEmpty().then( () => {49 if ( db.connection ) {50 db.connection.close();51 logger.info(`Scan finished ${config.name} in : ${moment.duration(moment().diff(startTime)).humanize()}`);52 }53 }).catch(e => {54 logger.error(`: scanAndStore -> ${e.message} : ${e.stack}`);55 });56 } catch(e) {57 logger.error(`: scanAndStore -> ${e.message} : ${e.stack}`);58 }59}60export async function scanSiteAndStoreFavorites(config: ScannerConfig) {61 const scanner = new ScannerV2(config);62 const storageQueue = new PQueue({63 concurrency: 1,64 autoStart: false65 });66 const db = new Database();67 // start queue after database connection68 db.connect(config.name).then( () => {69 storageQueue.start();70 logger.info(`Scan start ${config.name}`);71 }).catch(e => {72 logger.error(`: scanSiteAndStoreFavorites -> ${e.message} : ${e.stack}`);73 });74 try {75 const notifier = new ScannerNotifier(db);76 const startTime = moment();77 // TODO: scan new mangas and favorite manga78 const mangas = await scanner.listMangas();79 logger.debug(`scaned manga ${mangas.length}`);80 for (const manga of mangas) {81 const m = new Manga();82 m.name = manga.name;83 const s = new ScanSource();84 s.name = config.name;85 s.scannerConfig = config;86 s.link = manga.link;87 s.manga = m;88 logger.debug(`source manga : ${s.name} - ${s.link}`);89 storageQueue.add( () => findAndUpdateFavoritesOrNew(90 db,91 scanner,92 notifier,93 s as ScanSource)94 );95 }96 // close after usage97 storageQueue.onEmpty().then( () => {98 if ( db.connection ) {99 db.connection.close();100 logger.info(`Scan finished ${config.name} in : ${moment.duration(moment().diff(startTime)).humanize()}`);101 }102 }).catch(e => {103 logger.error(`: scanSiteAndStoreFavorites -> ${e.message} : ${e.stack}`);104 });105 } catch (e) {106 logger.error(`: scanSiteAndStoreFavorites -> ${e.message} : ${e.stack}`);107 }108}109export async function createOrUpdate(database: Database, notifier: ScannerNotifier, source: ScanSource, tags: string[]) {110 try {111 const dbSource = await retrieveSource(database, notifier, source);112 logger.debug(`source updated : ${dbSource.manga.name}`);113 await updateOrAddChapter(database, notifier, dbSource, source.chapters);114 logger.debug(`chapters updated : ${dbSource.manga.name}`);115 await updateTags(database, dbSource.manga, tags);116 logger.debug(`tags updated : ${dbSource.manga.name}`);117 } catch (e) {118 console.warn(`${e}`);119 }120}121/**122 * find favorites manga and update details.123 * Update chapters for this source.124 * @param database125 * @param notifier126 * @param source the source 127 */128async function findAndUpdateFavoritesOrNew(database: Database, scanner: ScannerV2, notifier: ScannerNotifier, source: ScanSource) {129 try {130 let dbSource = await database.findSourceByLink(source.link);131 if (!dbSource) {132 const dbManga = await database.findMangaByName(source.manga.name);133 if (dbManga) {134 dbSource = await database.addSourceToManga(dbManga, source);135 notifier.newMangaSource(dbManga, dbSource);136 } else {137 dbSource = await database.createMangaAndSource(source);138 notifier.newManga(dbSource.manga);139 }140 // scan manga page141 const [scanSource, tags] = await scanner.scanMangaSource(source, false);142 await createOrUpdate(database, notifier, scanSource as ScanSource, tags as string[]);143 } else {144 // if manga in favorite of a profile145 const shouldBeScanned = await database.mangaIsIncludeInFavorites(dbSource.manga);146 // scan manga page147 if (shouldBeScanned) {148 const [scanSource, tags] = await scanner.scanMangaSource(source, false);149 await createOrUpdate(database, notifier, scanSource as ScanSource, tags as string[]);150 }151 // else do nothing...152 }153 } catch (e) {154 console.warn(`${e}`);155 }156}157/**158 * Get or create the source159 * @param database current connected database160 * @param source source to retrieve161 */162async function retrieveSource(database: Database, notifier: ScannerNotifier, source: ScanSource) {163 // retreave source164 let dbSource = await database.findSourceByLink(source.link);165 if (!dbSource) {166 const dbManga = await database.findMangaByName(source.manga.name);167 if (dbManga) {168 dbSource = await database.addSourceToManga(dbManga, source);169 if (notifier) notifier.newMangaSource(dbManga, dbSource);170 } else {171 dbSource = await database.createMangaAndSource(source);172 if (notifier) notifier.newManga(dbSource.manga);173 }174 } else {175 // source.id = dbSource.id;176 dbSource.coverLink = source.coverLink;177 dbSource.description = source.description;178 dbSource.lastScan = moment().toDate();179 dbSource = await database.updateScanSource(dbSource);180 }181 return dbSource;182}183async function updateOrAddChapter(database: Database, notifier: ScannerNotifier, source: ScanSource, chapters: Chapter[]) {184 for (const chapter of chapters) {185 let dbChapter = await database.findChapterByLink(chapter.link);186 if (!dbChapter) {187 dbChapter = await database.addChapterToSource(source, chapter);188 // send update...189 let scanPages = false;190 if (notifier) {191 scanPages = await notifier.newChapterNotif(source, dbChapter);192 }193 if (scanPages) {194 await scanChapterPages([dbChapter]);195 }196 }197 }198}199/**200 * Update tags values in manga201 * @param database current connected database202 * @param manga manga to update203 * @param tags tag value list204 */205async function updateTags(database: Database, manga: Manga, tags: string[]) {206 await database.associateMangaWithTags(manga, tags);207}208/**209 * Parse pages for specified chapters210 * @param chapters chapters to parse211 */212export async function scanChapterPages(chapters: Chapter[]) {213 // add config214 const scanQueue = new PQueue({ concurrency: 10 });215 try {216 const db = new Database();217 db.connect('chapter-scanner').then( async () => {218 const notifier = new ScannerNotifier(db);219 for (const chapter of chapters) {220 const dbChapter = await db.findChapterById(chapter.id);221 if (dbChapter) {222 scanQueue.add( () => scanPagesAndUpdateChapter(db, notifier, dbChapter) );223 } else {224 logger.warn(`chapter not found: ${chapter.link}`);225 }226 }227 scanQueue.start();228 });229 } catch (e) {230 logger.error(`: scanChapterPages -> ${e.message} : ${e.stack}`);231 }232}233/**234 * Launch page scanner and update chapter with pages as JSON235 * @param database the connected database236 * @param scanner the scanner237 * @param chapter the chapter to scan238 */239async function scanPagesAndUpdateChapter(database: Database, notifier: ScannerNotifier, chapter: Chapter) {240 const scanner = ChapterScannerFactory.from(chapter.link);241 const pages = await scanner.scan(chapter.link);242 chapter.pages = pages;243 chapter.scanned = true;244 await database.chapterRepository.save(chapter);245 notifier.chapterScanFinish(chapter);...
index-generator.js
Source:index-generator.js
...26 * @param isEntry: bool27 */28function generate(filePathToIndex, isEntry) {29 isEntry = isEntry == undefined ? true : isEntry;30 if (!shouldBeScanned(filePathToIndex) || isIndex(filePathToIndex))31 return;32 let stat = fs.lstatSync(filePathToIndex);33 let folderPath = stat.isDirectory() ? path.resolve(filePathToIndex) : path.dirname(path.resolve(filePathToIndex));34 let shouldScanDeep = stat.isDirectory() && isEntry;35 fs.readdir(folderPath, (err, files) => {36 let exports = [];37 files.forEach((file) => {38 let filePath = path.join(folderPath, file);39 if (!shouldBeScanned(filePath) || isIndex(file))40 return;41 let stat = fs.lstatSync(filePath);42 if (stat.isDirectory() && shouldScanDeep) {43 generate(filePath, false);44 return;45 }46 if (stat.isFile()) {47 let r = parseFile(filePath);48 exports = exports.concat(r);49 }50 });51 let content = generateExports(exports);52 saveIndex(folderPath, content);53 });54}55function parseFile(content) {56 let exports = [];57 let ast = babylon.parse(content, {58 sourceType: 'module',59 allowImportExportEverywhere: true,60 plugins: [61 'jsx',62 'asyncFunctions',63 'classConstructorCall',64 'doExpressions',65 'trailingFunctionCommas',66 'objectRestSpread',67 'decorators',68 'classProperties',69 'exportExtensions',70 'exponentiationOperator',71 'asyncGenerators',72 'functionBind',73 'functionSent'74 ]75 });76 ast.program.body.forEach((rootItem) => {77 let exprt;78 try {79 if (rootItem.type == 'ExportDefaultDeclaration') {80 exprt = {81 name: rootItem.declaration.id ? rootItem.declaration.id.name : path.basename(filePath, path.extname(filePath)),82 isDefault: true83 };84 } else if (rootItem.type == 'ExportNamedDeclaration') {85 if (rootItem.declaration.type == 'VariableDeclaration') {86 exprt = {87 name: rootItem.declaration.declarations.find(x => x.type == 'VariableDeclarator').id.name88 }89 } else {90 exprt = {91 name: rootItem.declaration.id.name92 }93 }94 }95 if (exprt) {96 exprt.type = rootItem.type;97 exprt.file = path.basename(filePath);98 exports.push(exprt);99 }100 } catch (e) {101 console.log('------------------', filePath, '------------------');102 console.log(e);103 console.log(util.inspect(rootItem, { showHidden: false, depth: null }));104 }105 });106 return exports;107}108function generateExports(exports) {109 let lines = [];110 exports.forEach((exprt) => {111 let text = '';112 if (exprt.type == 'ExportDefaultDeclaration')113 text = `{ default as ${exprt.name} }`;114 else if (exprt.type == 'ExportNamedDeclaration')115 text = `{ ${exprt.name} }`;116 lines.push(`export ${text} from './${exprt.file}';`);117 });118 return lines.join(endOfLine);119}120function saveIndex(folder, content) {121 let indexPath = path.join(folder, 'index.js');122 content = `/* auto-generated by indexer */${endOfLine}/* eslint-disable */${endOfLine}${content}`;123 fs.writeFile(indexPath, content, { encoding: 'utf8' }, (err) => {124 if (err) throw err;125 cache[indexPath] = '';126 let relativeIndexPath = indexPath.substr(path.resolve('.').length);127 console.log(`${relativeIndexPath} saved`);128 });129}130function shouldBeScanned(scanPath) {131 let fullScanPath = path.resolve(scanPath);132 return includedPathes.some((include) => fullScanPath.indexOf(include) > -1)133 && !excludePathes.some((exclude) => fullScanPath.indexOf(exclude) > -1);134}135function isIndex(filePath) {136 let fileName = path.basename(filePath);137 return fileName == 'index.js';138}139function run() {140 includedPathes.forEach((path => {141 generate(path);142 }));143}144function init(include, exclude) {...
func.get-from-node-scan.ts
Source:func.get-from-node-scan.ts
...58 const node = normalize(nodes[index]);59 if (isNotObject(node)) {60 continue;61 }62 if (shouldBeScanned(scanned, node)) {63 scan({ result, el, nodes: node, normalize, proto }, gather, scanned);64 }65 gather = detectGatherFlag(gather, el, node);66 if (!gather) {67 continue;68 }69 if (result.indexOf(node) === -1 && node instanceof proto) {70 result.push(node);71 }72 }73};...
Using AI Code Generation
1import { shouldBeScanned } from 'ng-mocks';2import { MyComponent } from './my.component';3describe('MyComponent', () => {4 it('should be scanned', () => {5 expect(shouldBeScanned(MyComponent)).toEqual(true);6 });7});8import { Component } from '@angular/core';9@Component({10})11export class MyComponent {}12import { MyComponent } from './my.component';13import { mock } from 'ng-mocks';14describe('MyComponent', () => {15 it('should be mocked', () => {16 expect(mock(MyComponent)).toBeDefined();17 });18});19import { MyComponent } from './my.component';20import { mock } from 'ng-mocks';21describe('MyComponent', () => {22 it('should be mocked', () => {23 expect(mock(MyComponent)).toBeDefined();24 });25});26import { MyComponent } from './my.component';27import { mock } from 'ng-mocks';28describe('MyComponent', () => {29 it('should be mocked', () => {30 expect(mock(MyComponent)).toBeDefined();31 });32});33import { MyComponent } from './my.component';34import { mock } from 'ng-mocks';35describe('MyComponent', () => {36 it('should be mocked', () => {37 expect(mock(MyComponent)).toBeDefined();38 });39});40import { MyComponent } from './my.component';41import { mock } from 'ng-mocks';42describe('MyComponent', () => {43 it('should be mocked', () => {44 expect(mock(MyComponent)).toBeDefined();45 });46});47import { MyComponent } from './my.component';48import { mock } from 'ng-mocks';49describe('MyComponent', () => {50 it('should be mocked', () => {51 expect(mock(MyComponent)).toBeDefined();52 });53});
Using AI Code Generation
1import { shouldBeScanned } from 'ng-mocks';2import { MockBuilder, MockRender } from 'ng-mocks';3import { MockInstance } from 'ng-mocks';4import { MockService } from 'ng-mocks';5import { MockRender } from 'ng-mocks';6import { MockBuilder } from 'ng-mocks';7import { MockProvider } from 'ng-mocks';8import { MockRender } from 'ng-mocks';9import { MockDirective } from 'ng-mocks';10import { MockRender } from 'ng-mocks';11import { MockPipe } from 'ng-mocks';12import { MockRender } from 'ng-mocks';13import { MockComponent } from 'ng-mocks';14import { MockRender } from 'ng-mocks';
Using AI Code Generation
1import { shouldBeScanned } from 'ng-mocks';2describe('MyComponent', () => {3 it('should be scanned', () => {4 expect(shouldBeScanned(MyComponent)).toBe(true);5 });6});7@Component({8})9export class MyComponent {}10import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';11beforeEach(() => MockBuilder(MyComponent));12it('has a span', () => {13 const fixture = MockRender(MyComponent);14 expect(ngMocks.find('span')).not.toBeNull();15});16import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';17beforeEach(() => MockBuilder(MyComponent));18it('has a span', () => {19 const fixture = MockRender(MyComponent);20 expect(ngMocks.find('span')).not.toBeNull();21});22import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';23beforeEach(() => MockBuilder(MyComponent));24it('has a span', () => {25 const fixture = MockRender(MyComponent);26 expect(ngMocks.find('span')).not.toBeNull();27});28import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';29beforeEach(() => MockBuilder(MyComponent));30it('has a span', () => {31 const fixture = MockRender(MyComponent);32 expect(ngMocks.find('span')).not.toBeNull();33});34import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';35beforeEach(() => MockBuilder(MyComponent));36it('has a span', () => {37 const fixture = MockRender(MyComponent);38 expect(ngMocks.find('span')).not.toBeNull();39});40import { Mock
Using AI Code Generation
1import { shouldBeScanned } from 'ng-mocks';2describe('ng-mocks', () => {3 it('should be scanned', () => {4 expect(shouldBeScanned('test')).toBe(true);5 });6});7import { MockBuilder, MockRender } from 'ng-mocks';8describe('ng-mocks', () => {9 beforeEach(() => MockBuilder().mock(TestComponent));10 it('should render', () => {11 const fixture = MockRender(TestComponent);12 expect(fixture.point.componentInstance).toBeDefined();13 });14});15import { MockBuilder, MockRender } from 'ng-mocks';16describe('ng-mocks', () => {17 beforeEach(() => MockBuilder().mock(TestComponent));18 it('should render', () => {19 const fixture = MockRender(TestComponent);20 expect(fixture.point.componentInstance).toBeDefined();21 });22});23import { MockBuilder, MockRender } from 'ng-mocks';24describe('ng-mocks', () => {25 beforeEach(() => MockBuilder().mock(TestComponent));26 it('should render', () => {27 const fixture = MockRender(TestComponent);28 expect(fixture.point.componentInstance).toBeDefined();29 });30});31import { MockBuilder, MockRender } from 'ng-mocks';32describe('ng-mocks', () => {33 beforeEach(() => MockBuilder().mock(TestComponent));34 it('should render', () => {35 const fixture = MockRender(TestComponent);36 expect(fixture.point.componentInstance).toBeDefined();37 });38});39import { MockBuilder, MockRender } from 'ng-mocks';40describe('ng-mocks', () => {41 beforeEach(() => MockBuilder().mock(TestComponent));42 it('should render', () => {43 const fixture = MockRender(TestComponent);44 expect(fixture.point.componentInstance).toBeDefined();45 });46});47import { MockBuilder, MockRender } from 'ng-mocks';48describe('ng-mocks', () => {49 beforeEach(() => MockBuilder().mock(TestComponent));50 it('should render', () => {
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!!