How to use moduleConfig method in ng-mocks

Best JavaScript code snippet using ng-mocks

data_recognizer.js

Source:data_recognizer.js Github

copy

Full Screen

1/*2 * ELASTICSEARCH CONFIDENTIAL3 *4 * Copyright (c) 2017 Elasticsearch BV. All Rights Reserved.5 *6 * Notice: this software, and all information contained7 * therein, is the exclusive property of Elasticsearch BV8 * and its licensors, if any, and is protected under applicable9 * domestic and foreign law, and international treaties.10 *11 * Reproduction, republication or distribution without the12 * express written consent of Elasticsearch BV is13 * strictly prohibited.14 */15import fs from 'fs';16import Boom from 'boom';17import { prefixDatafeedId } from '../../../common/util/job_utils';18const ML_DIR = 'ml';19const KIBANA_DIR = 'kibana';20const INDEX_PATTERN_ID = 'INDEX_PATTERN_ID';21const INDEX_PATTERN_NAME = 'INDEX_PATTERN_NAME';22export class DataRecognizer {23 constructor(callWithRequest) {24 this.callWithRequest = callWithRequest;25 this.modulesDir = `${__dirname}/modules`;26 this.savedObjectsClient = null;27 }28 // list all directories under the given directory29 async listDirs(dirName) {30 const dirs = [];31 return new Promise((resolve, reject) => {32 fs.readdir(dirName, (err, fileNames) => {33 if (err) {34 reject(err);35 }36 fileNames.forEach((fileName) => {37 const path = `${dirName}/${fileName}`;38 if (fs.lstatSync(path).isDirectory()) {39 dirs.push(fileName);40 }41 });42 resolve(dirs);43 });44 });45 }46 async readFile(fileName) {47 return new Promise((resolve, reject) => {48 fs.readFile(fileName, 'utf-8', (err, content) => {49 if (err) {50 reject(err);51 } else {52 resolve(content);53 }54 });55 });56 }57 async loadManifestFiles() {58 const configs = [];59 const dirs = await this.listDirs(this.modulesDir);60 await Promise.all(dirs.map(async (dir) => {61 const file = await this.readFile(`${this.modulesDir}/${dir}/manifest.json`);62 configs.push({63 dirName: dir,64 json: JSON.parse(file)65 });66 }));67 return configs;68 }69 // get the manifest.json file for a specified id, e.g. "nginx"70 async getManifestFile(id) {71 const manifestFiles = await this.loadManifestFiles();72 return manifestFiles.find(i => i.json.id === id);73 }74 // called externally by an endpoint75 async findMatches(indexPattern) {76 const manifestFiles = await this.loadManifestFiles();77 const results = [];78 await Promise.all(manifestFiles.map(async (i) => {79 const moduleConfig = i.json;80 const match = await this.searchForFields(moduleConfig, indexPattern);81 if (match) {82 let logo = null;83 if (moduleConfig.logoFile) {84 try {85 logo = await this.readFile(`${this.modulesDir}/${i.dirName}/${moduleConfig.logoFile}`);86 logo = JSON.parse(logo);87 } catch(e) {88 logo = null;89 }90 }91 results.push({92 id: moduleConfig.id,93 title: moduleConfig.title,94 query: moduleConfig.query,95 description: moduleConfig.description,96 logo97 });98 }99 }));100 return results;101 }102 async searchForFields(moduleConfig, indexPattern) {103 const index = indexPattern;104 const size = 0;105 const body = {106 query: moduleConfig.query107 };108 const resp = await this.callWithRequest('search', { index, size, body });109 return (resp.hits.total !== 0);110 }111 // called externally by an endpoint112 // supplying an optional prefix will add the prefix113 // to the job and datafeed configs114 async getModule(id, prefix = '') {115 let manifestJSON = null;116 let dirName = null;117 const manifestFile = await this.getManifestFile(id);118 if (manifestFile !== undefined) {119 manifestJSON = manifestFile.json;120 dirName = manifestFile.dirName;121 }122 else {123 return Boom.notFound(`Module with the id "${id}" not found`);124 }125 const jobs = [];126 const datafeeds = [];127 const kibana = {};128 // load all of the job configs129 await Promise.all(manifestJSON.jobs.map(async (job) => {130 const jobConfig = await this.readFile(`${this.modulesDir}/${dirName}/${ML_DIR}/${job.file}`);131 // use the file name for the id132 jobs.push({133 id: `${prefix}${job.id}`,134 config: JSON.parse(jobConfig)135 });136 }));137 // load all of the datafeed configs138 await Promise.all(manifestJSON.datafeeds.map(async (datafeed) => {139 const datafeedConfig = await this.readFile(`${this.modulesDir}/${dirName}/${ML_DIR}/${datafeed.file}`);140 const config = JSON.parse(datafeedConfig);141 // use the job id from the manifestFile142 config.job_id = `${prefix}${datafeed.job_id}`;143 datafeeds.push({144 id: prefixDatafeedId(datafeed.id, prefix),145 config146 });147 }));148 // load all of the kibana saved objects149 const kKeys = Object.keys(manifestJSON.kibana);150 await Promise.all(kKeys.map(async (key) => {151 kibana[key] = [];152 await Promise.all(manifestJSON.kibana[key].map(async (obj) => {153 const kConfig = await this.readFile(`${this.modulesDir}/${dirName}/${KIBANA_DIR}/${key}/${obj.file}`);154 // use the file name for the id155 const kId = obj.file.replace('.json', '');156 const config = JSON.parse(kConfig);157 kibana[key].push({158 id: kId,159 title: config.title,160 config161 });162 }));163 }));164 return {165 jobs,166 datafeeds,167 kibana168 };169 }170 // called externally by an endpoint171 // takes a module config id, an optional jobPrefix and the request object172 // creates all of the jobs, datafeeds and savedObjects listed in the module config.173 // if any of the savedObjects already exist, they will not be overwritten.174 async setupModuleItems(moduleId, jobPrefix, groups, indexPatternName, request) {175 this.savedObjectsClient = request.getSavedObjectsClient();176 this.indexPatterns = await this.loadIndexPatterns();177 // load the config from disk178 const moduleConfig = await this.getModule(moduleId, jobPrefix);179 const manifestFile = await this.getManifestFile(moduleId);180 if (indexPatternName === undefined &&181 manifestFile && manifestFile.json &&182 manifestFile.json.defaultIndexPattern === undefined) {183 return Boom.badRequest(`No index pattern configured in "${moduleId}" configuration file and no index pattern passed to the endpoint`);184 }185 this.indexPatternName = (indexPatternName === undefined) ? manifestFile.json.defaultIndexPattern : indexPatternName;186 this.indexPatternId = this.getIndexPatternId(this.indexPatternName);187 // create an empty results object188 const results = this.createResultsTemplate(moduleConfig);189 const saveResults = {190 jobs: [],191 datafeeds: [],192 savedObjects: []193 };194 this.updateDatafeedIndices(moduleConfig);195 this.updateJobUrlIndexPatterns(moduleConfig);196 // create the jobs197 if (moduleConfig.jobs && moduleConfig.jobs.length) {198 if (Array.isArray(groups)) {199 // update groups list for each job200 moduleConfig.jobs.forEach(job => job.config.groups = groups);201 }202 saveResults.jobs = await this.saveJobs(moduleConfig.jobs);203 }204 // create the datafeeds205 if (moduleConfig.datafeeds && moduleConfig.datafeeds.length) {206 saveResults.datafeeds = await this.saveDatafeeds(moduleConfig.datafeeds);207 }208 // create the savedObjects209 if (moduleConfig.kibana) {210 // update the saved objects with the index pattern id211 this.updateSavedObjectIndexPatterns(moduleConfig);212 const savedObjects = await this.createSavedObjectsToSave(moduleConfig);213 // update the exists flag in the results214 this.updateKibanaResults(results.kibana, savedObjects);215 // create the savedObjects216 saveResults.savedObjects = await this.saveKibanaObjects(savedObjects);217 }218 // merge all the save results219 this.updateResults(results, saveResults);220 return results;221 }222 async loadIndexPatterns() {223 return await this.savedObjectsClient.find({ type: 'index-pattern', perPage: 1000 });224 }225 // returns a id based on an index pattern name226 getIndexPatternId(name) {227 if (this.indexPatterns && this.indexPatterns.saved_objects) {228 const ip = this.indexPatterns.saved_objects.find((i) => i.attributes.title === name);229 return (ip !== undefined) ? ip.id : undefined;230 } else {231 return undefined;232 }233 }234 // create a list of objects which are used to save the savedObjects.235 // each has an exists flag and those which do not already exist236 // contain a savedObject object which is sent to the server to save237 async createSavedObjectsToSave(moduleConfig) {238 // first check if the saved objects already exist.239 const savedObjectExistResults = await this.checkIfSavedObjectsExist(moduleConfig.kibana, this.request);240 // loop through the kibanaSaveResults and update241 Object.keys(moduleConfig.kibana).forEach((type) => {242 // type e.g. dashboard, search ,visualization243 moduleConfig.kibana[type].forEach((configItem) => {244 const existsResult = savedObjectExistResults.find(o => o.id === configItem.id);245 if (existsResult !== undefined) {246 configItem.exists = existsResult.exists;247 if (existsResult.exists === false) {248 // if this object doesn't already exist, create the savedObject249 // which will be used to create it250 existsResult.savedObject = {251 type,252 id: configItem.id,253 attributes: configItem.config254 };255 }256 }257 });258 });259 return savedObjectExistResults;260 }261 // update the exists flags in the kibana results262 updateKibanaResults(kibanaSaveResults, objectExistResults) {263 Object.keys(kibanaSaveResults).forEach((type) => {264 kibanaSaveResults[type].forEach((resultItem) => {265 const i = objectExistResults.find(o => (o.id === resultItem.id && o.type === type));266 resultItem.exists = (i !== undefined);267 });268 });269 }270 // loop through each type (dashboard, search, visualization)271 // load existing savedObjects for each type and compare to find out if272 // items with the same id already exist.273 // returns a flat list of objects with exists flags set274 async checkIfSavedObjectsExist(kibanaObjects) {275 const types = Object.keys(kibanaObjects);276 const results = await Promise.all(types.map(async (type) => {277 const existingObjects = await this.loadExistingSavedObjects(type);278 return kibanaObjects[type].map((obj) => {279 const existingObject = existingObjects.saved_objects.find(o => (o.attributes && o.attributes.title === obj.title));280 return {281 id: obj.id,282 type,283 exists: (existingObject !== undefined)284 };285 });286 }));287 // merge all results288 return [].concat(...results);289 }290 // find all existing savedObjects for a given type291 loadExistingSavedObjects(type) {292 return this.savedObjectsClient.find({ type, perPage: 1000 });293 }294 // save the savedObjects if they do not exist already295 async saveKibanaObjects(objectExistResults) {296 let results = [];297 const filteredSavedObjects = objectExistResults.filter(o => o.exists === false).map(o => o.savedObject);298 if (filteredSavedObjects.length) {299 results = await this.savedObjectsClient.bulkCreate(filteredSavedObjects);300 }301 return results;302 }303 // save the jobs.304 // if any fail (e.g. it already exists), catch the error and mark the result305 // as success: false306 async saveJobs(jobs) {307 return await Promise.all(jobs.map(async (job) => {308 const jobId = job.id;309 try {310 job.id = jobId;311 await this.saveJob(job);312 return { id: jobId, success: true };313 } catch (error) {314 return { id: jobId, success: false, error };315 }316 }));317 }318 async saveJob(job) {319 const { id: jobId, config: body } = job;320 return this.callWithRequest('ml.addJob', { jobId, body });321 }322 // save the datafeeds.323 // if any fail (e.g. it already exists), catch the error and mark the result324 // as success: false325 async saveDatafeeds(datafeeds) {326 return await Promise.all(datafeeds.map(async (datafeed) => {327 const datafeedId = datafeed.id;328 try {329 datafeed.id = datafeedId;330 await this.saveDatafeed(datafeed);331 return { id: datafeedId, success: true };332 } catch (error) {333 return { id: datafeedId, success: false, error };334 }335 }));336 }337 async saveDatafeed(datafeed) {338 const { id: datafeedId, config: body } = datafeed;339 return this.callWithRequest('ml.addDatafeed', { datafeedId, body });340 }341 // merge all of the save results into one result object342 // which is returned from the endpoint343 async updateResults(results, saveResults) {344 // update job results345 results.jobs.forEach((j) => {346 saveResults.jobs.forEach((j2) => {347 if (j.id === j2.id) {348 j.success = j2.success;349 if (j2.error !== undefined) {350 j.error = j2.error;351 }352 }353 });354 });355 // update datafeed results356 results.datafeeds.forEach((d) => {357 saveResults.datafeeds.forEach((d2) => {358 if (d.id === d2.id) {359 d.success = d2.success;360 if (d2.error !== undefined) {361 d.error = d2.error;362 }363 }364 });365 });366 // update savedObjects results367 Object.keys(results.kibana).forEach((category) => {368 results.kibana[category].forEach((item) => {369 const result = saveResults.savedObjects.find(o => o.id === item.id);370 if (result !== undefined) {371 item.exists = result.exists;372 if (result.error === undefined) {373 item.success = true;374 } else {375 item.success = false;376 item.error = result.error;377 }378 }379 });380 });381 }382 // creates an empty results object,383 // listing each job/datafeed/savedObject with a save success boolean384 createResultsTemplate(moduleConfig) {385 const results = {};386 function createResultsItems(configItems, resultItems, index) {387 resultItems[index] = [];388 configItems.forEach((j) => {389 resultItems[index].push({390 id: j.id,391 success: false392 });393 });394 }395 Object.keys(moduleConfig).forEach((i) => {396 if (Array.isArray(moduleConfig[i])) {397 createResultsItems(moduleConfig[i], results, i);398 } else {399 results[i] = {};400 Object.keys(moduleConfig[i]).forEach((k) => {401 createResultsItems(moduleConfig[i][k], results[i], k);402 });403 }404 });405 return results;406 }407 // if an override index pattern has been specified,408 // update all of the datafeeds.409 updateDatafeedIndices(moduleConfig) {410 // only use the override index pattern if it actually exists in kibana411 const idxId = this.getIndexPatternId(this.indexPatternName);412 if (idxId !== undefined) {413 moduleConfig.datafeeds.forEach((df) => {414 df.config.indexes = df.config.indexes.map(idx => (idx === INDEX_PATTERN_NAME ? this.indexPatternName : idx));415 });416 }417 }418 // loop through the custom urls in each job and replace the INDEX_PATTERN_ID419 // marker for the id of the specified index pattern420 updateJobUrlIndexPatterns(moduleConfig) {421 if (moduleConfig.jobs && moduleConfig.jobs.length) {422 // find the job associated with the datafeed423 moduleConfig.jobs.forEach((job) => {424 // if the job has custom_urls425 if (job.config.custom_settings && job.config.custom_settings.custom_urls) {426 // loop through each url, replacing the INDEX_PATTERN_ID marker427 job.config.custom_settings.custom_urls.forEach((cUrl) => {428 const url = cUrl.url_value;429 if (url.match(INDEX_PATTERN_ID)) {430 const newUrl = url.replace(new RegExp(INDEX_PATTERN_ID, 'g'), this.indexPatternId);431 // update the job's url432 cUrl.url_value = newUrl;433 }434 });435 }436 });437 }438 }439 // loop through each kibana saved objects and replace the INDEX_PATTERN_ID440 // marker for the id of the specified index pattern441 updateSavedObjectIndexPatterns(moduleConfig) {442 if (moduleConfig.kibana) {443 Object.keys(moduleConfig.kibana).forEach((category) => {444 moduleConfig.kibana[category].forEach((item) => {445 let jsonString = item.config.kibanaSavedObjectMeta.searchSourceJSON;446 if (jsonString.match(INDEX_PATTERN_ID)) {447 jsonString = jsonString.replace(new RegExp(INDEX_PATTERN_ID, 'g'), this.indexPatternId);448 item.config.kibanaSavedObjectMeta.searchSourceJSON = jsonString;449 }450 });451 });452 }453 }...

Full Screen

Full Screen

module-config.js

Source:module-config.js Github

copy

Full Screen

1/**2 * Gulp utils for module configuration.3 */4const os = require("os");5const clientPackages = require("./client-packages");6const regExUtils = require("./regex-utils");7function createRequireConfig(uniteConfig, moduleConfig, mapBase) {8 for (const key in moduleConfig.paths) {9 moduleConfig.paths[key] = regExUtils.replaceLeadingSlash(moduleConfig.paths[key], "");10 }11 for (const key in moduleConfig.map) {12 moduleConfig.map[key] = regExUtils.replaceLeadingSlash(moduleConfig.map[key], "");13 }14 const rjsConfig = {15 baseUrl: mapBase,16 paths: moduleConfig.paths,17 packages: moduleConfig.packages,18 map: {19 "*": {}20 }21 };22 Object.keys(moduleConfig.map).forEach(key => {23 rjsConfig.map["*"][key] = moduleConfig.map[key];24 });25 return rjsConfig;26}27function createRequireJS(uniteConfig, includeModes, isBundle, mapBase) {28 const moduleConfig = clientPackages.buildModuleConfig(uniteConfig, includeModes, isBundle);29 const rjsConfig = createRequireConfig(uniteConfig, moduleConfig, mapBase);30 const jsonConfig = JSON.stringify(rjsConfig, undefined, "\t");31 const jsonPreload = JSON.stringify(moduleConfig.preload, undefined, "\t");32 let config = `require.config(${jsonConfig});${os.EOL}`;33 config += `preloadModules = ${jsonPreload};${os.EOL}`;34 return config;35}36function createSystemConfig(uniteConfig, moduleConfig, mapBase) {37 let format = null;38 const moduleTypeLower = uniteConfig.moduleType.toLowerCase();39 if (moduleTypeLower === "amd") {40 format = "amd";41 } else if (moduleTypeLower === "commonjs") {42 format = "cjs";43 } else if (moduleTypeLower === "systemjs") {44 format = "system";45 }46 const sjsConfig = {47 baseURL: mapBase,48 paths: moduleConfig.paths,49 packages: {},50 map: {},51 meta: {52 "dist/*.js": {53 format54 },55 "dist/app-module-config.js": {56 format: "global"57 }58 }59 };60 sjsConfig.packages[""] = {61 defaultExtension: "js"62 };63 Object.keys(moduleConfig.paths).forEach(key => {64 moduleConfig.paths[key] = regExUtils.stripLeadingSlash(moduleConfig.paths[key]);65 });66 Object.keys(moduleConfig.map).forEach(key => {67 moduleConfig.map[key] = regExUtils.replaceLeadingSlash(moduleConfig.map[key], mapBase);68 if (moduleConfig.paths[moduleConfig.map[key]]) {69 const distKey = `dist/*/${moduleConfig.paths[moduleConfig.map[key]]}.js`;70 sjsConfig.meta[distKey] = {71 format: "global"72 };73 }74 });75 moduleConfig.packages.forEach((pkg) => {76 moduleConfig.paths[pkg.name] = regExUtils.replaceLeadingSlash(pkg.location, "");77 if (pkg.mainLib) {78 pkg.mainLib.forEach(childPackage => {79 sjsConfig.packages[`${pkg.name}/${childPackage}`] = {80 main: pkg.main,81 defaultExtension: pkg.libExtension82 };83 });84 }85 sjsConfig.packages[pkg.name] = {86 main: pkg.main,87 defaultExtension: pkg.libExtension88 };89 });90 Object.keys(moduleConfig.map).forEach(key => {91 sjsConfig.map[key] = moduleConfig.map[key];92 });93 Object.keys(moduleConfig.loaders).forEach(key => {94 sjsConfig.meta[key] = {95 loader: moduleConfig.loaders[key]96 };97 });98 return sjsConfig;99}100function createSystemJS(uniteConfig, includeModes, isBundle, mapBase) {101 const moduleConfig = clientPackages.buildModuleConfig(uniteConfig, includeModes, isBundle);102 const sjsConfig = createSystemConfig(uniteConfig, moduleConfig, mapBase);103 const jsonConfig = JSON.stringify(sjsConfig, undefined, "\t");104 const jsonPreload = JSON.stringify(moduleConfig.preload, undefined, "\t");105 let config = `SystemJS.config(${jsonConfig});${os.EOL}`;106 config += `preloadModules = ${jsonPreload};${os.EOL}`;107 return config;108}109exports.createSystemJS = createSystemJS;110function create(uniteConfig, includeModes, isBundle, mapBase) {111 let loader = null;112 const bundlerLower = uniteConfig.bundler.toLowerCase();113 if (bundlerLower === "requirejs") {114 loader = "rjs";115 } else if ((isBundle && bundlerLower === "systemjsbuilder") ||116 (!isBundle && (bundlerLower === "browserify" ||117 bundlerLower === "systemjsbuilder" ||118 bundlerLower === "webpack"))) {119 loader = "sjs";120 }121 if (loader === "rjs") {122 return createRequireJS(uniteConfig, includeModes, isBundle, mapBase);123 } else if (loader === "sjs") {124 return createSystemJS(uniteConfig, includeModes, isBundle, mapBase);125 }126 return "";127}128exports.create = create;...

Full Screen

Full Screen

moduleHandler.js

Source:moduleHandler.js Github

copy

Full Screen

1const fs = require('fs');2var events = [];3var commands = [];4module.exports = {5 loadModules: function(client, clientConfig) {6 if(!fs.existsSync('./modules')) return info('No modules installed, skipping!');7 var modulesContents = fs.readdirSync('./modules');8 const ce = require('./extentions/constantExtentions');9 const se = require('./extentions/serverExtentions');10 for(var i in modulesContents) {11 if(fs.lstatSync(`./modules/${modulesContents[i]}`).isDirectory()) {12 13 if(!fs.existsSync(`./modules/${modulesContents[i]}/${modulesContents[i]}.json`)) {warn(`Module '${modulesContents[i]}' dosen't have a json file attached. Skipping load.`); continue;}14 try{var moduleData = JSON.parse(fs.readFileSync(`./modules/${modulesContents[i]}/${modulesContents[i]}.json`).toString()); } catch (err) {warn(`Module '${modulesContents[i]}' dosen't have a valid json file. Skipping load. (${err.message})`); continue;}15 16 for(var j in moduleData) {17 var moduleConfig = moduleData[j];18 if(!moduleConfig.name || !moduleConfig.type || !moduleConfig.target) {warn(`Module '${modulesContents[i]}' dosen't have a valid json file. Skipping load. (Missing name, type or target)`); continue;}19 else if(moduleConfig.type != "constant" && !moduleConfig.command && !moduleConfig.event) {warn(`Module '${modulesContents[i]}' dosen't have a valid json file. Skipping load. (Missing module type)`); continue;}20 else if(moduleConfig.type != "command" && moduleConfig.type != "event" && moduleConfig.type != "constant") {warn(`Module '${modulesContents[i]}' dosen't have a valid json file. Skipping load. (Invalid module type)`); continue;}21 else if(moduleConfig.type == "command" && !moduleConfig.usage) {warn(`Module '${modulesContents[i]}' dosen't have a valid json file. Skipping load. (Missing command usage)`); continue;}22 else if(!fs.existsSync(`./modules/${modulesContents[i]}/${moduleConfig.target}`)) {warn(`Module '${modulesContents[i]}' target ('${moduleConfig.target}') dosen't exist`); continue;}23 try {24 if(moduleConfig.type == "command") {25 var module = require(`../../modules/${modulesContents[i]}/${moduleConfig.target}`);26 commands.push({name: moduleConfig.name, target: `/${modulesContents[i]}/${moduleConfig.target}`, command: moduleConfig.command, description: moduleConfig.description, usage: moduleConfig.usage});27 module.load(moduleConfig);28 }29 30 else if(moduleConfig.type == "event") {31 var module = require(`../../modules/${modulesContents[i]}/${moduleConfig.target}`);32 events.push({name: moduleConfig.name, target: `/${modulesContents[i]}/${moduleConfig.target}`, event: moduleConfig.event});33 module.load(moduleConfig);34 } 35 else if(moduleConfig.type == "constant") {36 var module = require(`../../modules/${modulesContents[i]}/${moduleConfig.target}`);37 module.load(moduleConfig, clientConfig, client, {clientExtentions: ce, serverExtentions: se});38 }39 40 } catch (err) {41 return warn(`Error instantiating module '${modulesContents[i]}':\n${err.stack}`);42 }43 } 44 }45 }46 },47 getModuleFromCommand: function(command) {48 for(var i in commands) {49 if(commands[i].command == command) return commands[i];50 }51 return false;52 },53 getModuleFromEvent: function(event) {54 for(var i in events) {55 if(events[i].event == event) return events[i];56 }57 return false;58 },59 getCommands: function() {60 if(!commands[0]) return false;61 else return commands;62 },63 getEvents: function() {64 if(!events[0]) return false;65 else return events;66 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { moduleConfig } from 'ng-mocks';2import { MyModule } from './my-module';3moduleConfig(MyModule, {4});5import { MyComponent } from './my-component';6import { MyModule } from './my-module';7describe('MyComponent', () => {8 beforeEach(() => {9 TestBed.configureTestingModule({10 imports: [11 }).compileComponents();12 });13 it('should create', () => {14 const fixture = TestBed.createComponent(MyComponent);15 const component = fixture.componentInstance;16 expect(component).toBeTruthy();17 });18});19import { moduleConfig } from 'ng-mocks';20import { MyModule } from './my-module';21moduleConfig(MyModule, {22 {23 useValue: {24 getData: () => 'mocked data',25 },26 },27});28import { MyComponent } from './my-component';29import { MyModule } from './my-module';30import { MyService } from './my-service';31describe('MyComponent', () => {32 beforeEach(() => {33 TestBed.configureTestingModule({34 imports: [35 }).compileComponents();36 });37 it('should create', () => {38 const fixture = TestBed.createComponent(MyComponent);39 const component = fixture.componentInstance;40 expect(component).toBeTruthy();41 });42});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { moduleConfig } from 'ng-mocks';2import { MyModule } from './my.module';3describe('MyModule', () => {4 moduleConfig(MyModule);5});6import { NgModule } from '@angular/core';7@NgModule({8 imports: [9})10export class MyModule {}

Full Screen

Using AI Code Generation

copy

Full Screen

1import { moduleConfig } from 'ng-mocks';2import { Component } from '@angular/core';3@Component({ selector: 'app', template: 'template' })4export class AppComponent {}5import { mockModule } from 'ng-mocks';6describe('AppComponent', () => {7 beforeEach(() => {8 mockModule(AppComponent);9 });10});11import { mockProvider } from 'ng-mocks';12describe('AppComponent', () => {13 beforeEach(() => {14 mockProvider(ProviderClass);15 });16});17import { mockPipe } from 'ng-mocks';18describe('AppComponent', () => {19 beforeEach(() => {20 mockPipe(PipeClass);21 });22});23import { mockComponent } from 'ng-mocks';24describe('AppComponent', () => {25 beforeEach(() => {26 mockComponent(ComponentClass);27 });28});29import { mockDirective } from 'ng-mocks';30describe('AppComponent', () => {31 beforeEach(() => {32 mockDirective(DirectiveClass);33 });34});35import { mockRender } from 'ng-mocks';36describe('AppComponent', () => {37 beforeEach(() => {38 mockRender(AppComponent);39 });40});41import { mockInstance } from 'ng-mocks';42describe('AppComponent', () => {43 beforeEach(() => {44 mockInstance(InstanceClass);45 });46});47import { mockImport } from 'ng-mocks';48describe('AppComponent', () => {49 beforeEach(() => {50 mockImport(ImportClass);51 });52});53import { mockReset } from 'ng-mocks';54describe('AppComponent', () => {55 beforeEach(() => {56 mockReset();57 });58});59import { mockConsole } from 'ng-mocks';60describe('AppComponent', () => {61 beforeEach(() => {62 mockConsole();63 });64});65import { mockDeep } from 'ng

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ng-mocks automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful