How to use updated method in ng-mocks

Best JavaScript code snippet using ng-mocks

language-models.manage.model.ts

Source:language-models.manage.model.ts Github

copy

Full Screen

1import { LocalizationObject, LocalizedString, } from "healthbotcommon/tenantcontent";2import { defaultLocalizationClient, mergeLocalizationObjects } from "healthbotcommon/tenantcontent/localization";3import { tenantContents } from "../../../modules/globals";4import { logLanguageModelsChange, logLocalizationChange } from "../../../services/auditTrailsLogger";5import * as mainModel from "../main.model";6import * as localizationModel from "./configuration.localization.model";7import { QnAMakerKnowledgeBase } from "./qnmaker/QnAMakerKnowledgeBase.class";8const config = require('config');9const _ = require("underscore");10enum MethodType {11 LUIS = "luis",12 RegEx = "regex",13 QnA = "qna"14}15const builtinScenarios = [16 "/builtin/help",17 "/builtin/terms",18 "/builtin/greeting",19 "/builtin/log",20 "/builtin/feedback",21 "/builtin/forget_me",22 "/builtin/need_to_know",23 "/builtin/triage",24 "/builtin/handoff/teams/agentlogin",25 "/builtin/infermedica/triage",26 "/builtin/capita/triage",27 "/medication/information",28 "/builtin/condition/information",29 "/builtin/condition/symptoms",30 "/builtin/condition/causes",31 "/builtin/condition/complications",32 "/builtin/condition/resources",33 "/builtin/condition/specialties",34 "/builtin/nih/condition/information",35 "/builtin/nih/condition/symptoms",36 "/builtin/nih/condition/resources"37];38async function updateLocalizedString(localizedString: LocalizedString, defaultLocalizedStrings: LocalizationObject, systemLocalizedStrings: LocalizationObject, accountId, accountName, user) {39 if (!localizedString.stringId?.trim() || defaultLocalizedStrings.stringIds.includes(localizedString.stringId)) {40 localizedString.stringId = localizationModel.getStringId(localizedString["en-us"]);41 }42 const existingLocalizedString = getLocalizedString(localizedString.stringId, systemLocalizedStrings);43 if (existingLocalizedString["en-us"] !== localizedString["en-us"]) {44 await tenantContents[accountName].localization.system.saveChanges([localizedString]);45 logLocalizationChange(accountName, "modified", user, "system");46 mainModel.updateLocalizationSettings(accountName);47 mainModel.reloadTenant(accountName);48 }49 return localizedString.stringId;50}51function getLocalizedString(stringId, localizedStrings: LocalizationObject) {52 const translation = localizedStrings["en-us"]?.[stringId];53 return translation ?54 { stringId, "en-us": translation } :55 { "stringId": "", "en-us": "" };56}57function updateLocalizedStringExpression(objectToUpdate, localizedStrings: LocalizationObject) {58 for (const key of Object.keys(objectToUpdate)) {59 if (key.startsWith("_convict")) {60 delete objectToUpdate[key];61 continue;62 }63 const model = objectToUpdate[key];64 const currentExpression = model.expression;65 model.expression = getLocalizedString(model.expression, localizedStrings);66 if (model.expression.stringId === "" && model.expression["en-us"] === "") {67 model.expression["en-us"] = currentExpression;68 }69 }70}71export async function getLuisModels(accountName: string) {72 const config = await tenantContents[accountName].config.load();73 return config.get("language_understanding.luis_models");74}75export interface ILanguageUnderstanding {76 custom_regexp_recognizers: Record<string, any>;77 builtin_regexp_recognizers: Record<string, any>;78 builtin_recognizers: IBuiltinRecognizers;79 intent_handler_map: Record<string, any>;80 qna_recognizers: Record<string, any>;81}82export interface IQnAModel {83 enabled: boolean;84 description: string;85 intent: string;86 qnaEndpoint: string;87 kbId: string;88 subscription_key: string;89 threshold?: number;90 api_key?: string;91}92export interface IBuiltinRecognizers {93 triage_recognizer: Record<string, any>;94}95function getLanguageUnderstanding(tenantConfig): ILanguageUnderstanding {96 const language: ILanguageUnderstanding = tenantConfig.get("language_understanding");97 return language;98}99export async function read(account: { id: string; name: string; }) {100 const [systemLocalizedStrings, isLocalizationEnabled] = await Promise.all([101 tenantContents[account.name].localization.system.get(),102 tenantContents[account.name].config.load().then((tenantConfig) => tenantConfig.get("localizationSettings.isLocalizationEnabled"))103 ]);104 const localizedStrings = mergeLocalizationObjects(defaultLocalizationClient.get(), systemLocalizedStrings);105 const tenantConfig = await tenantContents[account.name].config.load({ localizedStrings });106 const language: ILanguageUnderstanding = getLanguageUnderstanding(tenantConfig);107 const scenarios = (await tenantContents[account.name].scenarios.listLightScenarios()).map((scenario) => ({108 name: scenario.name,109 scenario_trigger: scenario.scenario_trigger,110 RowKey: scenario.RowKey111 }));112 if (language.custom_regexp_recognizers) {113 updateLocalizedStringExpression(language.custom_regexp_recognizers, localizedStrings);114 }115 Object.keys(language.builtin_regexp_recognizers).forEach((key) => {116 if (key.startsWith("_convict")) {117 return;118 }119 if (language.builtin_regexp_recognizers[key].hide) {120 delete language.builtin_regexp_recognizers[key];121 }122 });123 Object.keys(language).forEach((key) => {124 cleanUpConvictFields(language[key]);125 });126 return {127 language,128 scenarios: _.sortBy(scenarios, 'scenario_trigger'),129 builtinScenarios,130 isLocalizationEnabled131 };132}133function cleanUpConvictFields(objectToClean: Record<string, any>) {134 for (const key of Object.keys(objectToClean)) {135 if (key.toLowerCase().startsWith("_convict")) {136 delete objectToClean[key];137 }138 }139}140export async function createNewModel(accountId: string, accountName: string, user: string, updatedModel: any) {141 const defaultLocalizedStrings = defaultLocalizationClient.get();142 const [systemLocalizedStrings, isLocalizationEnabled, specific] = await Promise.all([143 tenantContents[accountName].localization.system.get(),144 tenantContents[accountName].config.load().then((tenantConfig) => tenantConfig.get("localizationSettings.isLocalizationEnabled")),145 tenantContents[accountName].config.getOverrides()146 ]);147 specific.language_understanding = specific.language_understanding || {};148 const tenantConfig = await tenantContents[accountName].config.load({ localizedStrings: mergeLocalizationObjects(defaultLocalizedStrings, systemLocalizedStrings) });149 const language: ILanguageUnderstanding = getLanguageUnderstanding(tenantConfig);150 let modelToReturn;151 switch (updatedModel.type) {152 case MethodType.RegEx:153 if (updatedModel.expression.stringId === null) {154 updatedModel.expression.stringId = localizationModel.getStringId(updatedModel.expression["en-us"]);155 await tenantContents[accountName].localization.system.saveChanges([updatedModel.expression]);156 logLocalizationChange(accountName, "modified", user, "system");157 mainModel.updateLocalizationSettings(accountName);158 mainModel.reloadTenant(accountName);159 }160 let updatedStringId = updatedModel.expression.stringId;161 if (!isLocalizationEnabled) {162 updatedStringId = await updateLocalizedString(updatedModel.expression, defaultLocalizedStrings, systemLocalizedStrings, accountId, accountName, user);163 }164 specific.language_understanding.custom_regexp_recognizers = specific.language_understanding.custom_regexp_recognizers || {};165 specific.language_understanding.custom_regexp_recognizers[updatedModel.name] = {166 enabled: true,167 description: updatedModel.description,168 scope: updatedModel.scope,169 intent: updatedModel.intent,170 expression: updatedStringId171 };172 modelToReturn = JSON.parse(JSON.stringify(specific.language_understanding.custom_regexp_recognizers[updatedModel.name]));173 modelToReturn.expression = {174 "stringId": updatedStringId,175 "en-us": updatedModel.expression['en-us']176 };177 specific.language_understanding.intent_handler_map = specific.language_understanding.intent_handler_map || {};178 specific.language_understanding.intent_handler_map[updatedModel.intent] = language.intent_handler_map[updatedModel.intent] || {};179 specific.language_understanding.intent_handler_map[updatedModel.intent].handler = !(typeof (updatedModel.target) === 'string') || updatedModel.target.trim() === "" ? null : updatedModel.target;180 break;181 case MethodType.LUIS:182 specific.language_understanding.luis_models = specific.language_understanding.luis_models || {};183 specific.language_understanding.luis_models[updatedModel.name] = {184 application_id: updatedModel.application_id,185 subscription_key: updatedModel.subscription_key,186 staging: updatedModel.staging,187 verbose: updatedModel.verbose,188 region: updatedModel.region,189 bing_spell_check_subscription_key: updatedModel.bing_spell_check_subscription_key,190 enabled: updatedModel.enabled,191 description: updatedModel.description,192 scope: updatedModel.scope,193 intents: updatedModel.intents.map((intent) => intent.intent),194 };195 modelToReturn = specific.language_understanding.luis_models[updatedModel.name];196 specific.language_understanding.intent_handler_map = specific.language_understanding.intent_handler_map || {};197 for (const intent of updatedModel.intents) {198 specific.language_understanding.intent_handler_map[intent.intent] = language.intent_handler_map[intent.intent] || {};199 specific.language_understanding.intent_handler_map[intent.intent].handler = !intent.target || !intent.target.handler || !(typeof (intent.target.handler) === 'string') || intent.target.handler.trim() === "" ? null : intent.target.handler;200 }201 break;202 case MethodType.QnA:203 specific.language_understanding.qna_recognizers = specific.language_understanding.qna_recognizers || {};204 specific.language_understanding.qna_recognizers[updatedModel.name] = {205 enabled: true,206 description: updatedModel.description,207 intent: updatedModel.intent,208 qnaEndpoint: updatedModel.qnaEndpoint,209 kbId: updatedModel.kbId,210 subscription_key: updatedModel.subscription_key,211 threshold: Number(updatedModel.threshold) || config.get("qna.minimum_score")212 };213 modelToReturn = JSON.parse(JSON.stringify(specific.language_understanding.qna_recognizers[updatedModel.name]));214 specific.language_understanding.intent_handler_map = specific.language_understanding.intent_handler_map || {};215 specific.language_understanding.intent_handler_map[updatedModel.intent] = language.intent_handler_map[updatedModel.intent] || {};216 specific.language_understanding.intent_handler_map[updatedModel.intent].handler = !(typeof (updatedModel.target) === 'string') || updatedModel.target.trim() === "" ? null : updatedModel.target;217 break;218 }219 await tenantContents[accountName].config.save(specific);220 mainModel.reloadTenant(accountName);221 logLanguageModelsChange(accountName, "created", user, updatedModel.name);222 return {223 name: updatedModel.name,224 model: modelToReturn,225 intent_handler_map: (await tenantContents[accountName].config.load()).get("language_understanding.intent_handler_map")226 };227}228export async function resetModels(accountName: string, user: string) {229 const specific = await tenantContents[accountName].config.getOverrides();230 specific.language_understanding = specific.language_understanding || {};231 delete specific.language_understanding.intent_handler_map;232 delete specific.language_understanding.builtin_recognizers;233 delete specific.language_understanding.builtin_regexp_recognizers;234 delete specific.language_understanding.luis_models;235 delete specific.language_understanding.qna_recognizers;236 delete specific.language_understanding.custom_regexp_recognizers;237 await tenantContents[accountName].config.save(specific);238 mainModel.reloadTenant(accountName);239 logLanguageModelsChange(accountName, "deleted", user, 'all');240}241export async function updateQnaModel(accountId: string, accountName: string, modelToUpdate: { model: IQnAModel }) {242 const specific = await tenantContents[accountName].config.getOverrides();243 specific.language_understanding = specific.language_understanding || {};244 const qnaModels = specific.language_understanding.qna_recognizers || {};245 let found = false;246 for (const model of [...Object.values(qnaModels)] as IQnAModel[]) {247 if (model.api_key === modelToUpdate.model.api_key && model.kbId === modelToUpdate.model.kbId) {248 found = true;249 const qnaMakerKnowledgeBase = new QnAMakerKnowledgeBase({250 tenant: {251 id: accountId,252 name: accountName,253 },254 blobURIs: [config.get('qna.covid_19_cdc_knowledge_base')],255 subscriptionKey: model.api_key,256 });257 try {258 const kbs = await qnaMakerKnowledgeBase.getKnowledgeBases();259 const kb = kbs.find((knowledgeBase) => knowledgeBase.id === model.kbId);260 if (!kb) { throw new Error('Knowledgebase id does not match subscription key'); }261 const kbDetails = await qnaMakerKnowledgeBase.getKBDetails(model.kbId);262 await qnaMakerKnowledgeBase.updateKnowledgeBase(model.kbId, kbDetails.urls);263 await qnaMakerKnowledgeBase.publishKnowledgeBase(model.kbId);264 } catch (error) {265 throw new Error('an error occurred, please check your subscription key and try again in a few minutes');266 }267 }268 }269 if (!found) {270 throw new Error("Keys doesn't match");271 }272}273export async function deleteModel(accountName: string, user: string, modelToDelete: any) {274 const specific = await tenantContents[accountName].config.getOverrides();275 specific.language_understanding = specific.language_understanding || {};276 if (modelToDelete.type === 'custom_regexp_recognizers') {277 const intent = specific.language_understanding.custom_regexp_recognizers[modelToDelete.model.name].intent;278 delete specific.language_understanding.custom_regexp_recognizers[modelToDelete.model.name];279 delete specific.language_understanding.intent_handler_map[intent];280 } else if (modelToDelete.type === 'luis_models') {281 for (const intent of modelToDelete.model.intents) {282 if (intent && intent.trim() !== "") {283 delete specific.language_understanding.intent_handler_map[intent];284 }285 }286 delete specific.language_understanding.luis_models[modelToDelete.model.name];287 } else if (modelToDelete.type === 'qna_recognizers') {288 const intent = specific.language_understanding.qna_recognizers[modelToDelete.model.name].intent;289 delete specific.language_understanding.qna_recognizers[modelToDelete.model.name];290 delete specific.language_understanding.intent_handler_map[intent];291 }292 await tenantContents[accountName].config.save(specific);293 mainModel.reloadTenant(accountName);294 logLanguageModelsChange(accountName, "deleted", user, modelToDelete.model.name);295 return {296 name: modelToDelete.model.name,297 intent_handler_map: (await tenantContents[accountName].config.load()).get("language_understanding.intent_handler_map")298 };299}300export async function saveModel(accountId: string, accountName: string, user: string, updatedModel: any) {301 const defaultLocalizedStrings = defaultLocalizationClient.get();302 const [systemLocalizedStrings, isLocalizationEnabled] = await Promise.all([303 tenantContents[accountName].localization.system.get(),304 tenantContents[accountName].config.load().then((tenantConfig) => tenantConfig.get("localizationSettings.isLocalizationEnabled"))305 ]);306 const specific = await tenantContents[accountName].config.getOverrides();307 specific.language_understanding = specific.language_understanding || {};308 const tenantConfig = await tenantContents[accountName].config.load({ localizedStrings: mergeLocalizationObjects(defaultLocalizedStrings, systemLocalizedStrings) });309 const language: ILanguageUnderstanding = getLanguageUnderstanding(tenantConfig);310 let modelToReturn;311 if (updatedModel.type === 'custom_regexp_recognizers') {312 if (updatedModel.model.expression.stringId === null) {313 updatedModel.model.expression.stringId = localizationModel.getStringId(updatedModel.model.expression["en-us"]);314 await tenantContents[accountName].localization.system.saveChanges([updatedModel.model.expression]);315 logLocalizationChange(accountName, "modified", user, "system");316 mainModel.updateLocalizationSettings(accountName);317 mainModel.reloadTenant(accountName);318 }319 let updatedStringId = updatedModel.model.expression.stringId;320 if (!isLocalizationEnabled) {321 updatedStringId = await updateLocalizedString(updatedModel.model.expression, defaultLocalizedStrings, systemLocalizedStrings, accountId, accountName, user);322 }323 const previousIntent = language.custom_regexp_recognizers[updatedModel.model.name].intent;324 specific.language_understanding.custom_regexp_recognizers = specific.language_understanding.custom_regexp_recognizers || {};325 specific.language_understanding.custom_regexp_recognizers[updatedModel.model.name] = {326 enabled: updatedModel.model.enabled,327 description: updatedModel.model.description,328 scope: updatedModel.model.scope,329 intent: updatedModel.model.intent,330 expression: updatedStringId331 };332 modelToReturn = JSON.parse(JSON.stringify(specific.language_understanding.custom_regexp_recognizers[updatedModel.model.name]));333 modelToReturn.expression = {334 "stringId": updatedStringId,335 "en-us": updatedModel.model.expression['en-us']336 };337 specific.language_understanding.intent_handler_map = specific.language_understanding.intent_handler_map || {};338 delete specific.language_understanding.intent_handler_map[previousIntent];339 specific.language_understanding.intent_handler_map[updatedModel.model.intent] = language.intent_handler_map[updatedModel.model.intent] || {};340 specific.language_understanding.intent_handler_map[updatedModel.model.intent].handler = !(typeof (updatedModel.model.target) === 'string') || updatedModel.model.target.trim() === "" ? null : updatedModel.model.target;341 } else if (updatedModel.type === 'builtin_regexp_recognizers') {342 if (updatedModel.model.expression.stringId === null) {343 updatedModel.model.expression.stringId = localizationModel.getStringId(updatedModel.model.expression["en-us"]);344 await tenantContents[accountName].localization.system.saveChanges([updatedModel.model.expression]);345 logLocalizationChange(accountName, "modified", user, "system");346 mainModel.updateLocalizationSettings(accountName);347 mainModel.reloadTenant(accountName);348 }349 let updatedStringId = updatedModel.model.expression.stringId;350 if (!isLocalizationEnabled) {351 updatedStringId = await updateLocalizedString(updatedModel.model.expression, defaultLocalizedStrings, systemLocalizedStrings, accountId, accountName, user);352 }353 specific.language_understanding.builtin_regexp_recognizers = specific.language_understanding.builtin_regexp_recognizers || {};354 specific.language_understanding.builtin_regexp_recognizers[updatedModel.model.name] = specific.language_understanding.builtin_regexp_recognizers[updatedModel.model.name] || {};355 if (language.builtin_regexp_recognizers[updatedModel.model.name].scope !== updatedModel.model.scope) {356 specific.language_understanding.builtin_regexp_recognizers[updatedModel.model.name].scope = updatedModel.model.scope;357 }358 if (language.builtin_regexp_recognizers[updatedModel.model.name].expression.stringId !== updatedStringId) {359 specific.language_understanding.builtin_regexp_recognizers[updatedModel.model.name].expression = updatedStringId;360 }361 if (_.isEmpty(specific.language_understanding.builtin_regexp_recognizers[updatedModel.model.name])) {362 delete specific.language_understanding.builtin_regexp_recognizers[updatedModel.model.name];363 }364 if (_.isEmpty(specific.language_understanding.builtin_regexp_recognizers)) {365 delete specific.language_understanding.builtin_regexp_recognizers;366 }367 modelToReturn = (await tenantContents[accountName].config.load()).get("language_understanding.builtin_regexp_recognizers")[updatedModel.model.name];368 const previousIntent = language.builtin_regexp_recognizers[updatedModel.model.name].intent;369 if (language.intent_handler_map[previousIntent].handler !== updatedModel.model.target) {370 specific.language_understanding.intent_handler_map = specific.language_understanding.intent_handler_map || {};371 delete specific.language_understanding.intent_handler_map[previousIntent];372 specific.language_understanding.intent_handler_map[updatedModel.model.intent] = language.intent_handler_map[updatedModel.model.intent] || {};373 specific.language_understanding.intent_handler_map[updatedModel.model.intent].handler = !(typeof (updatedModel.model.target) === 'string') || updatedModel.model.target.trim() === "" ? null : updatedModel.model.target;374 }375 } else if (updatedModel.type === 'luis_models') {376 specific.language_understanding.luis_models[updatedModel.model.name].scope = updatedModel.model.scope;377 specific.language_understanding.luis_models[updatedModel.model.name].region = updatedModel.model.region;378 specific.language_understanding.luis_models[updatedModel.model.name].bing_spell_check_subscription_key = updatedModel.model.bing_spell_check_subscription_key;379 specific.language_understanding.luis_models[updatedModel.model.name].subscription_key = updatedModel.model.subscription_key;380 specific.language_understanding.luis_models[updatedModel.model.name].staging = updatedModel.model.staging;381 specific.language_understanding.luis_models[updatedModel.model.name].verbose = updatedModel.model.verbose;382 specific.language_understanding.intent_handler_map = specific.language_understanding.intent_handler_map || {};383 for (const intent of specific.language_understanding.luis_models[updatedModel.model.name].intents) {384 if (intent && intent.trim() !== "") {385 delete specific.language_understanding.intent_handler_map[intent];386 }387 }388 specific.language_understanding.luis_models[updatedModel.model.name].intents = updatedModel.model.intents.map((intent) => intent.intent);389 modelToReturn = specific.language_understanding.luis_models[updatedModel.model.name];390 for (const intent of updatedModel.model.intents) {391 specific.language_understanding.intent_handler_map[intent.intent] = language.intent_handler_map[intent.intent] || {};392 specific.language_understanding.intent_handler_map[intent.intent].handler = !(typeof (intent.target) === 'string') || intent.target.trim() === "" ? null : intent.target;393 }394 } else if (updatedModel.type === 'builtin_recognizers') {395 if (language.builtin_recognizers[updatedModel.model.name].scope !== updatedModel.model.scope) {396 specific.language_understanding.builtin_recognizers = specific.language_understanding.builtin_recognizers || {};397 specific.language_understanding.builtin_recognizers[updatedModel.model.name] = specific.language_understanding.builtin_recognizers[updatedModel.model.name] || {};398 specific.language_understanding.builtin_recognizers[updatedModel.model.name].scope = updatedModel.model.scope;399 }400 modelToReturn = (await tenantContents[accountName].config.load()).get("language_understanding.builtin_recognizers")[updatedModel.model.name];401 for (const intent of updatedModel.model.intents) {402 if (language.intent_handler_map[intent.intent].handler !== intent.target) {403 specific.language_understanding.intent_handler_map = specific.language_understanding.intent_handler_map || {};404 specific.language_understanding.intent_handler_map[intent.intent] = language.intent_handler_map[intent.intent] || {};405 specific.language_understanding.intent_handler_map[intent.intent].handler = !(typeof (intent.target) === 'string') || intent.target.trim() === "" ? null : intent.target;406 }407 }408 } else if (updatedModel.type === 'qna_recognizers') {409 const previousIntent = language.qna_recognizers[updatedModel.model.name].intent;410 specific.language_understanding.qna_recognizers = specific.language_understanding.qna_recognizers || {};411 specific.language_understanding.qna_recognizers[updatedModel.model.name] = {412 enabled: updatedModel.model.enabled,413 description: updatedModel.model.description,414 intent: updatedModel.model.intent,415 qnaEndpoint: updatedModel.model.qnaEndpoint,416 kbId: updatedModel.model.kbId,417 subscription_key: updatedModel.model.subscription_key,418 threshold: updatedModel.model.threshold ? Number(updatedModel.model.threshold) : undefined,419 api_key: updatedModel.model.api_key420 };421 modelToReturn = JSON.parse(JSON.stringify(specific.language_understanding.qna_recognizers[updatedModel.model.name]));422 specific.language_understanding.intent_handler_map = specific.language_understanding.intent_handler_map || {};423 delete specific.language_understanding.intent_handler_map[previousIntent];424 specific.language_understanding.intent_handler_map[updatedModel.model.intent] = language.intent_handler_map[updatedModel.model.intent] || {};425 specific.language_understanding.intent_handler_map[updatedModel.model.intent].handler = !(typeof (updatedModel.model.target) === 'string') || updatedModel.model.target.trim() === "" ? null : updatedModel.model.target;426 }427 await tenantContents[accountName].config.save(specific);428 mainModel.reloadTenant(accountName);429 logLanguageModelsChange(accountName, "modified", user, updatedModel.model.name);430 return {431 name: updatedModel.model.name,432 model: modelToReturn,433 intent_handler_map: (await tenantContents[accountName].config.load()).get("language_understanding.intent_handler_map")434 };435}436export async function toggleEnabled(accountName: string, user: string, modelToChange: any) {437 const enabled = modelToChange.enabled;438 const name = modelToChange.name;439 const modelType = modelToChange.type;440 const specific = await tenantContents[accountName].config.getOverrides();441 const tenantConfig = await tenantContents[accountName].config.load();442 const language: ILanguageUnderstanding = getLanguageUnderstanding(tenantConfig);443 if (language[modelType][name].enabled !== enabled) {444 specific.language_understanding = specific.language_understanding || {};445 specific.language_understanding[modelType] = specific.language_understanding[modelType] || {};446 specific.language_understanding[modelType][name] = specific.language_understanding[modelType][name] || {};447 specific.language_understanding[modelType][name].enabled = enabled;448 await tenantContents[accountName].config.save(specific);449 mainModel.reloadTenant(accountName);450 logLanguageModelsChange(accountName, "modified", user, name);451 }...

Full Screen

Full Screen

browser_ext_tabs_onUpdated.js

Source:browser_ext_tabs_onUpdated.js Github

copy

Full Screen

1/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */2/* vim: set sts=2 sw=2 et tw=80: */3"use strict";4requestLongerTimeout(2);5add_task(async function() {6 let win1 = await BrowserTestUtils.openNewBrowserWindow();7 await focusWindow(win1);8 let extension = ExtensionTestUtils.loadExtension({9 manifest: {10 "permissions": ["tabs"],11 "content_scripts": [{12 "matches": ["http://mochi.test/*/context_tabs_onUpdated_page.html"],13 "js": ["content-script.js"],14 "run_at": "document_start",15 }],16 },17 background: function() {18 let pageURL = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context_tabs_onUpdated_page.html";19 let expectedSequence = [20 {status: "loading"},21 {status: "loading", url: pageURL},22 {status: "complete"},23 ];24 let collectedSequence = [];25 browser.tabs.onUpdated.addListener(function(tabId, updatedInfo) {26 // onUpdated also fires with updatedInfo.faviconUrl, so explicitly27 // check for updatedInfo.status before recording the event.28 if ("status" in updatedInfo) {29 collectedSequence.push(updatedInfo);30 }31 });32 browser.runtime.onMessage.addListener(function() {33 if (collectedSequence.length !== expectedSequence.length) {34 browser.test.assertEq(35 JSON.stringify(expectedSequence),36 JSON.stringify(collectedSequence),37 "got unexpected number of updateInfo data"38 );39 } else {40 for (let i = 0; i < expectedSequence.length; i++) {41 browser.test.assertEq(42 expectedSequence[i].status,43 collectedSequence[i].status,44 "check updatedInfo status"45 );46 if (expectedSequence[i].url || collectedSequence[i].url) {47 browser.test.assertEq(48 expectedSequence[i].url,49 collectedSequence[i].url,50 "check updatedInfo url"51 );52 }53 }54 }55 browser.test.notifyPass("tabs.onUpdated");56 });57 browser.tabs.create({url: pageURL});58 },59 files: {60 "content-script.js": `61 window.addEventListener("message", function(evt) {62 if (evt.data == "frame-updated") {63 browser.runtime.sendMessage("load-completed");64 }65 }, true);66 `,67 },68 });69 await Promise.all([70 extension.startup(),71 extension.awaitFinish("tabs.onUpdated"),72 ]);73 await extension.unload();74 await BrowserTestUtils.closeWindow(win1);75});76async function do_test_update(background, withPermissions = true) {77 let win1 = await BrowserTestUtils.openNewBrowserWindow();78 await focusWindow(win1);79 let manifest = {};80 if (withPermissions) {81 manifest.permissions = ["tabs", "http://mochi.test/"];82 }83 let extension = ExtensionTestUtils.loadExtension({manifest, background});84 await Promise.all([85 await extension.startup(),86 await extension.awaitFinish("finish"),87 ]);88 await extension.unload();89 await BrowserTestUtils.closeWindow(win1);90}91add_task(async function test_pinned() {92 await do_test_update(function background() {93 // Create a new tab for testing update.94 browser.tabs.create({}, function(tab) {95 browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) {96 // Check callback97 browser.test.assertEq(tabId, tab.id, "Check tab id");98 browser.test.log("onUpdate: " + JSON.stringify(changeInfo));99 if ("pinned" in changeInfo) {100 browser.test.assertTrue(changeInfo.pinned, "Check changeInfo.pinned");101 browser.tabs.onUpdated.removeListener(onUpdated);102 // Remove created tab.103 browser.tabs.remove(tabId);104 browser.test.notifyPass("finish");105 }106 });107 browser.tabs.update(tab.id, {pinned: true});108 });109 });110});111add_task(async function test_unpinned() {112 await do_test_update(function background() {113 // Create a new tab for testing update.114 browser.tabs.create({pinned: true}, function(tab) {115 browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) {116 // Check callback117 browser.test.assertEq(tabId, tab.id, "Check tab id");118 browser.test.log("onUpdate: " + JSON.stringify(changeInfo));119 if ("pinned" in changeInfo) {120 browser.test.assertFalse(changeInfo.pinned, "Check changeInfo.pinned");121 browser.tabs.onUpdated.removeListener(onUpdated);122 // Remove created tab.123 browser.tabs.remove(tabId);124 browser.test.notifyPass("finish");125 }126 });127 browser.tabs.update(tab.id, {pinned: false});128 });129 });130});131add_task(async function test_url() {132 await do_test_update(function background() {133 // Create a new tab for testing update.134 browser.tabs.create({}, function(tab) {135 browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) {136 if ("url" in changeInfo) {137 // When activity stream is enabled, about:newtab runs in the content process138 // which causes some timing issues for onUpdated. So if we encounter139 // about:newtab, return early and continue waiting for about:blank.140 if (changeInfo.url === "about:newtab") {141 return;142 }143 browser.test.assertEq("about:blank", changeInfo.url,144 "Check changeInfo.url");145 browser.tabs.onUpdated.removeListener(onUpdated);146 // Remove created tab.147 browser.tabs.remove(tabId);148 browser.test.notifyPass("finish");149 }150 // Check callback151 browser.test.assertEq(tabId, tab.id, "Check tab id");152 browser.test.log("onUpdate: " + JSON.stringify(changeInfo));153 });154 browser.tabs.update(tab.id, {url: "about:blank"});155 });156 });157});158add_task(async function test_title() {159 await do_test_update(async function background() {160 const url = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context_tabs_onUpdated_page.html";161 const tab = await browser.tabs.create({url});162 browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) {163 browser.test.assertEq(tabId, tab.id, "Check tab id");164 browser.test.log(`onUpdated: ${JSON.stringify(changeInfo)}`);165 if ("title" in changeInfo && changeInfo.title === "New Message (1)") {166 browser.test.log("changeInfo.title is correct");167 browser.tabs.onUpdated.removeListener(onUpdated);168 browser.tabs.remove(tabId);169 browser.test.notifyPass("finish");170 }171 });172 browser.tabs.executeScript(tab.id, {code: "document.title = 'New Message (1)'"});173 });174});175add_task(async function test_without_tabs_permission() {176 await do_test_update(async function background() {177 const url = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context_tabs_onUpdated_page.html";178 const tab = await browser.tabs.create({url});179 let count = 0;180 browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) {181 browser.test.assertEq(tabId, tab.id, "Check tab id");182 browser.test.log(`onUpdated: ${JSON.stringify(changeInfo)}`);183 browser.test.assertFalse("url" in changeInfo, "url should not be included without tabs permission");184 browser.test.assertFalse("favIconUrl" in changeInfo, "favIconUrl should not be included without tabs permission");185 browser.test.assertFalse("title" in changeInfo, "title should not be included without tabs permission");186 if (changeInfo.status == "complete") {187 count++;188 if (count === 2) {189 browser.test.log("Reload complete");190 browser.tabs.onUpdated.removeListener(onUpdated);191 browser.tabs.remove(tabId);192 browser.test.notifyPass("finish");193 }194 }195 });196 browser.tabs.reload(tab.id);197 }, false /* withPermissions */);198});...

Full Screen

Full Screen

audit-fields.vo.spec.ts

Source:audit-fields.vo.spec.ts Github

copy

Full Screen

1import {2 AuditFields,3 AuditFieldsProps,4} from "#seedwork/domain/value-objects/audit-fields.vo";5describe("AuditFields Unit Tests", () => {6 let validateSpy: any;7 beforeEach(() => {8 validateSpy = jest.spyOn(AuditFields, "validate");9 });10 describe("should throw an error when created_by is invalid", () => {11 const arrange = [12 {13 testCase: 1,14 created_by: null as any,15 message: {16 created_by: [17 "created_by should not be empty",18 "created_by must be a string",19 "created_by must be shorter than or equal to 255 characters",20 ],21 updated_by: [22 "updated_by should not be empty",23 "updated_by must be a string",24 "updated_by must be shorter than or equal to 255 characters",25 ],26 },27 },28 {29 testCase: 2,30 created_by: undefined as any,31 message: {32 created_by: [33 "created_by should not be empty",34 "created_by must be a string",35 "created_by must be shorter than or equal to 255 characters",36 ],37 updated_by: [38 "updated_by should not be empty",39 "updated_by must be a string",40 "updated_by must be shorter than or equal to 255 characters",41 ],42 },43 },44 {45 testCase: 3,46 created_by: "",47 message: {48 created_by: ["created_by should not be empty"],49 updated_by: ["updated_by should not be empty"],50 },51 },52 {53 testCase: 4,54 created_by: 5 as any,55 message: {56 created_by: [57 "created_by must be a string",58 "created_by must be shorter than or equal to 255 characters",59 ],60 updated_by: [61 "updated_by must be a string",62 "updated_by must be shorter than or equal to 255 characters",63 ],64 },65 },66 {67 testCase: 5,68 created_by: true as any,69 message: {70 created_by: [71 "created_by must be a string",72 "created_by must be shorter than or equal to 255 characters",73 ],74 updated_by: [75 "updated_by must be a string",76 "updated_by must be shorter than or equal to 255 characters",77 ],78 },79 },80 ];81 test.each(arrange)("$testCase) when created_by is $created_by", (i) => {82 expect(83 () => new AuditFields({ created_by: i.created_by })84 ).containsErrorMessages(i.message);85 expect(validateSpy).toHaveBeenCalledTimes(1);86 });87 });88 describe("should throw an error when props are invalid", () => {89 type Arrange = {90 testCase: number;91 props: AuditFieldsProps;92 message: {};93 };94 const created_at = new Date();95 const arrange: Arrange[] = [96 {97 testCase: 1,98 props: { created_by: "user", created_at: "fake" as any },99 message: {100 created_at: ["created_at must be a Date instance"],101 updated_at: [102 "updated_at cannot be older than created_at",103 "updated_at must be a Date instance",104 ],105 },106 },107 {108 testCase: 2,109 props: {110 created_by: "user",111 created_at,112 updated_by: true as any,113 },114 message: {115 updated_by: [116 "updated_by must be a string",117 "updated_by must be shorter than or equal to 255 characters",118 ],119 },120 },121 {122 testCase: 3,123 props: {124 created_by: "user",125 created_at,126 updated_by: "user",127 updated_at: true as any,128 },129 message: {130 updated_at: [131 "updated_at cannot be older than created_at",132 "updated_at must be a Date instance",133 ],134 },135 },136 {137 testCase: 4,138 props: {139 created_by: "user",140 created_at,141 updated_by: "user",142 updated_at: new Date(created_at.getTime() - 100),143 },144 message: {145 updated_at: ["updated_at cannot be older than created_at"],146 },147 },148 ];149 test.each(arrange)("$testCase) when props are $props", (i) => {150 expect(() => new AuditFields(i.props)).containsErrorMessages(i.message);151 expect(validateSpy).toHaveBeenCalledTimes(1);152 });153 });154 it("should create a valid vo with created_by only", () => {155 const vo = new AuditFields({ created_by: "user" });156 expect(vo.value.created_by).toBe("user");157 expect(vo.value.updated_by).toBe(vo.value.created_by);158 expect(vo.value.created_at).toBeInstanceOf(Date);159 expect(vo.value.updated_at).toBe(vo.value.created_at);160 expect(validateSpy).toHaveBeenCalledTimes(1);161 });162 it("should create a valid vo with created_by and created_at", () => {163 const created_at = new Date();164 const vo = new AuditFields({ created_by: "user", created_at });165 expect(vo.value.created_by).toBe("user");166 expect(vo.value.updated_by).toBe(vo.value.created_by);167 expect(vo.value.created_at).toBe(created_at);168 expect(vo.value.updated_at).toBe(created_at);169 expect(validateSpy).toHaveBeenCalledTimes(1);170 });171 it("should create a valid vo with created_by, created_at and updated_by", () => {172 const created_at = new Date();173 const updated_at = new Date(created_at.getTime() + 100);174 const vo = new AuditFields({175 created_by: "user",176 created_at,177 updated_by: "new user",178 updated_at,179 });180 expect(vo.value.created_by).toBe("user");181 expect(vo.value.updated_by).toBe("new user");182 expect(vo.value.created_at).toBe(created_at);183 expect(vo.value.updated_at).toBe(updated_at);184 expect(validateSpy).toHaveBeenCalledTimes(1);185 });...

Full Screen

Full Screen

jobs.js

Source:jobs.js Github

copy

Full Screen

1export const GET = 'GET_JOBS';2export const CREATE = 'CREATE';3export const CREATE_ERROR = 'CREATE_ERROR';4export const UPDATE = 'UPDATE_JOB';5export const APPLY = 'APPLY';6export const APPLY_ERROR = 'APPLY_ERROR';7export const UNAPPLY = 'UNAPPLY';8export const UNAPPLY_ERROR = 'UNAPPLY_ERROR';9export const APPROVE = 'APPROVE';10export const APPROVE_ERROR = 'APPROVE_ERROR';11export const DECLINE = 'DECLINE';12export const DECLINE_ERROR = 'DECLINE_ERROR';13export const DELETE = 'DELETE_JOB';14import * as _ from 'lodash';15export const getJobs = JobIds => {16 return { type: GET, data: JobIds }17};18export const create = (payload) => {19 let job = payload;20 job.createdTime = new Date();21 return(dispatch, getState, {getFirestore, }) => {22 const firestore = getFirestore();23 firestore.collection('jobs').add(24 job25 ).then(() => {26 dispatch({ type: "CREATE", data: payload});27 }).catch((err) => {28 dispatch({ type: "CREATE_ERROR", err});29 })30 }31};32export const updateJob = Job => {33 34 return { type: UPDATE, data: Job }35};36export const apply = (job, uid) => {37 console.log("Job Action: ", job.id, uid);38 let updatedJob = job;39 console.log("Applicants before::: ", updatedJob.applicants);40 let newApplicants = [...updatedJob.applicants, uid];41 console.log("NEW APPLICANTS: ", newApplicants);42 updatedJob = {43 ...updatedJob,44 applicants: [ ...updatedJob.applicants, uid ],45 };46 console.log(" APPLY ACTION, UPDATED JOB: ", updatedJob.applicants);47 return(dispatch, getState, {getFirestore, }) => {48 const firestore = getFirestore();49 firestore.collection('jobs').doc(job.id).set(50 updatedJob51 ).then(() => {52 dispatch({ type: "APPLY", job: job, uid: uid });53 }).catch((err) => {54 dispatch({ type: "APPLY_ERROR", err});55 })56}57};58export const unApply = (job, uid) => {59 console.log("Job UNAPPLY Action: ", job.id, uid);60 let updatedJob = job;61 console.log("Applicants before::: ", updatedJob.applicants);62 updatedJob = {63 ...updatedJob,64 applicants: _.without(updatedJob.applicants, uid),65 };66 console.log(" APPLY ACTION, UPDATED JOB: ", updatedJob.applicants);67 return(dispatch, getState, {getFirestore, }) => {68 const firestore = getFirestore();69 firestore.collection('jobs').doc(job.id).set(70 updatedJob71 ).then(() => {72 dispatch({ type: "UNAPPLY", job: job, uid: uid });73 }).catch((err) => {74 dispatch({ type: "UNAPPLY_ERROR", err});75 })76}77};78export const approve = (job, approvedApplicant) => {79 console.log("Job Approve Action: ", job.id, approvedApplicant);80 let updatedJob = job;81 console.log("Applicants before::: ", updatedJob.applicants);82 updatedJob = {83 ...updatedJob,84 applicants: _.without( updatedJob.applicants, approvedApplicant.id ),85 isFilled: true,86 approvedApplicant: approvedApplicant,87 };88 console.log(" Approve ACTION, UPDATED JOB: ", updatedJob.applicants);89 return(dispatch, getState, {getFirestore, }) => {90 const firestore = getFirestore();91 firestore.collection('jobs').doc(job.id).set(92 updatedJob93 ).then(() => {94 dispatch({ type: "APPROVE", job: job, uid: uid });95 }).catch((err) => {96 dispatch({ type: "APPROVE_ERROR", err});97 })98}99};100export const decline = (job, declinedApplicantId) => {101 let updatedJob = job;102 updatedJob = {103 ...updatedJob,104 applicants: _.without( updatedJob.applicants, declinedApplicantId),105 declinedApplicants: _.concat(updatedJob.declinedApplicants, declinedApplicantId),106 isFilled: false,107 };108 return(dispatch, getState, {getFirestore, }) => {109 const firestore = getFirestore();110 firestore.collection('jobs').doc(job.id).set(111 updatedJob112 ).then(() => {113 dispatch({ type: "DECLINE", job: job, uid: uid });114 }).catch((err) => {115 dispatch({ type: "DECLINE_ERROR", err});116 })117 }118};119export const deleteJob = JobId => {120 return { type: DELETE, data: JobId }...

Full Screen

Full Screen

shop.reducer.js

Source:shop.reducer.js Github

copy

Full Screen

1import {2 ADD_PRODUCT_TO_CART,3 DECREMENT_CART_ITEM_QUANTITY,4 INCREMENT_CART_ITEM_QUANTITY,5 REMOVE_PRODUCT_FROM_CART6} from '../actions';7import {phones} from "../data/phones";8const initialState = {9 products: phones,10 cart: []11};12const shopReducer = (state = initialState, action ) => {13 let updatedCart;14 let updatedItemIndex;15 switch (action.type) {16 case INCREMENT_CART_ITEM_QUANTITY:17 updatedCart = [...state.cart];18 updatedItemIndex = updatedCart.findIndex(19 item => item.id === action.payload20 );21 const incrementedItem = {22 ...updatedCart[updatedItemIndex]23 };24 incrementedItem.quantity++;25 updatedCart[updatedItemIndex] = incrementedItem;26 return {...state, cart: updatedCart};27 case DECREMENT_CART_ITEM_QUANTITY:28 updatedCart = [...state.cart];29 updatedItemIndex = updatedCart.findIndex(30 item => item.id === action.payload31 );32 const decrementedItem = {33 ...updatedCart[updatedItemIndex]34 };35 decrementedItem.quantity--;36 updatedCart[updatedItemIndex] = decrementedItem;37 return {...state, cart: updatedCart};38 case ADD_PRODUCT_TO_CART:39 updatedCart = [...state.cart];40 updatedItemIndex = updatedCart.findIndex(item => item.id === action.payload.id);41 if(updatedItemIndex < 0) {42 updatedCart.push({...action.payload, quantity: 1});43 } else {44 const updatedItem = {45 ...updatedCart[updatedItemIndex]46 };47 updatedItem.quantity++;48 updatedCart[updatedItemIndex] = updatedItem;49 }50 return {...state, cart: updatedCart};51 case REMOVE_PRODUCT_FROM_CART:52 updatedCart = [...state.cart];53 updatedItemIndex = updatedCart.findIndex(54 item => item.id === action.payload55 );56 updatedCart.splice(updatedItemIndex, 1);57 return {...state, cart: updatedCart};58 default:59 return state;60 }61};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2import { AppComponent } from './app.component';3import { AppModule } from './app.module';4describe('AppComponent', () => {5 beforeEach(() => MockBuilder(AppComponent, AppModule));6 it('should create the app', () => {7 const fixture = MockRender(AppComponent);8 const app = ngMocks.findInstance(AppComponent);9 expect(app).toBeTruthy();10 });11 it(`should have as title 'app'`, () => {12 const fixture = MockRender(AppComponent);13 const app = ngMocks.findInstance(AppComponent);14 expect(app.title).toEqual('app');15 });16 it('should render title in a h1 tag', () => {17 const fixture = MockRender(AppComponent);18 expect(ngMocks.formatText(fixture)).toContain('Welcome to app!');19 });20});21import { Component } from '@angular/core';22@Component({23})24export class AppComponent {25 title = 'app';26}27import { BrowserModule } from '@angular/platform-browser';28import { NgModule } from '@angular/core';29import { AppComponent } from './app.component';30@NgModule({31 imports: [BrowserModule],32})33export class AppModule {}34import { MockBuilder, MockRender } from 'ng-mocks';35import { AppComponent } from './app.component';36import { AppModule } from './app.module';37describe('AppComponent', () => {38 beforeEach(() => MockBuilder(AppComponent, AppModule));39 it('should create the app', () => {40 const fixture = MockRender(AppComponent);41 const app = fixture.debugElement.componentInstance;42 expect(app).toBeTruthy();43 });44 it(`should have as title 'app'`, () => {45 const fixture = MockRender(AppComponent);46 const app = fixture.debugElement.componentInstance;47 expect(app.title).toEqual('app');48 });49 it('should render title in a h1 tag', () => {50 const fixture = MockRender(AppComponent);51 expect(fixture.debugElement.nativeElement.querySelector('h1').textContent).toContain('Welcome to app!');52 });53});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2import { MockBuilder, MockRender, ngMocks } from 'ng-mocks/dist/ng-mocks';3import 'ng-mocks';4import 'ng-mocks/dist/ng-mocks';5import 'ng-mocks';6import 'ng-mocks/dist/ng-mocks';7import 'ng-mocks';8import 'ng-mocks/dist/ng-mocks';9import 'ng-mocks';10import 'ng-mocks/dist/ng-mocks';11import 'ng-mocks';12import 'ng-mocks/dist/ng-mocks';13import 'ng-mocks';14import 'ng-mocks/dist/ng-mocks';15import 'ng-mocks';16import 'ng-mocks/dist/ng-mocks';17import 'ng-mocks';18import 'ng-mocks/dist/ng-mocks';19import 'ng-mocks';20import 'ng-mocks/dist/ng-mocks';21import 'ng-mocks';22import 'ng-mocks/dist/ng-mocks';

Full Screen

Using AI Code Generation

copy

Full Screen

1import { ngMocks } from 'ng-mocks';2import { AppComponent } from './app.component';3describe('AppComponent', () => {4 it('should create the app', () => {5 const fixture = ngMocks.guts(AppComponent, null, null);6 const app = fixture.componentInstance;7 expect(app).toBeTruthy();8 });9});10import { ngMocks } from 'ng-mocks';11import { AppComponent } from './app.component';12describe('AppComponent', () => {13 it('should create the app', () => {14 const fixture = ngMocks.guts(AppComponent, null, null);15 const app = fixture.componentInstance;16 expect(app).toBeTruthy();17 });18});19import { ngMocks } from 'ng-mocks';20import { AppComponent } from './app.component';21describe('AppComponent', () => {22 it('should create the app', () => {23 const fixture = ngMocks.guts(AppComponent, null, null);24 const app = fixture.componentInstance;25 expect(app).toBeTruthy();26 });27});28import { ngMocks } from 'ng-mocks';29import { AppComponent } from './app.component';30describe('AppComponent', () => {31 it('should create the app', () => {32 const fixture = ngMocks.guts(AppComponent, null, null);33 const app = fixture.componentInstance;34 expect(app).toBeTruthy();35 });36});37import { ngMocks } from 'ng-mocks';38import { AppComponent } from './app.component';39describe('AppComponent', () => {40 it('should create the app', () => {41 const fixture = ngMocks.guts(AppComponent, null, null);42 const app = fixture.componentInstance;43 expect(app).toBeTruthy();44 });45});46import { ngMocks } from 'ng-mocks';47import { AppComponent } from './app.component';48describe('AppComponent', () => {49 it('should create the app', () => {50 const fixture = ngMocks.guts(AppComponent, null, null);51 const app = fixture.componentInstance;52 expect(app).toBeTruthy();53 });54});55import { ngMocks } from 'ng-mocks';56import { AppComponent } from './app.component';57describe('AppComponent', () => {58 it('should create the app', () =>

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockBuilder, MockRender } from 'ng-mocks';2import { MyComponent } from './my.component';3import { MyModule } from './my.module';4describe('MyComponent', () => {5 beforeEach(() => MockBuilder(MyComponent, MyModule));6 it('should render', () => {7 const fixture = MockRender(MyComponent);8 expect(fixture.point.componentInstance).toBeDefined();9 });10});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2import { AppModule } from './app.module';3import { AppComponent } from './app.component';4import { Component } from '@angular/core';5import { By } from '@angular/platform-browser';6describe('AppComponent', () => {7 beforeEach(() => MockBuilder(AppComponent, AppModule));8 it('should create the app', () => {9 const fixture = MockRender(AppComponent);10 const app = fixture.debugElement.componentInstance;11 expect(app).toBeTruthy();12 });13 it(`should have as title 'app'`, () => {14 const fixture = MockRender(AppComponent);15 const app = fixture.debugElement.componentInstance;16 expect(app.title).toEqual('app');17 });18 it('should render title in a h1 tag', () => {19 const fixture = MockRender(AppComponent);20 const compiled = fixture.debugElement.nativeElement;21 expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');22 });23 it('should render title in a h1 tag', () => {24 const fixture = MockRender(AppComponent);25 const compiled = fixture.debugElement.nativeElement;26 expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');27 });28 it('should render title in a h1 tag', () => {29 const fixture = MockRender(AppComponent);30 const compiled = fixture.debugElement.nativeElement;31 expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');32 });33 it('should render title in a h1 tag', () => {34 const fixture = MockRender(AppComponent);35 const compiled = fixture.debugElement.nativeElement;36 expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');37 });38 it('should render title in a h1 tag', () => {39 const fixture = MockRender(AppComponent);40 const compiled = fixture.debugElement.nativeElement;41 expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');42 });43 it('should render title in a h1 tag', () => {44 const fixture = MockRender(AppComponent);45 const compiled = fixture.debugElement.nativeElement;46 expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');47 });48 it('should render title in a h1 tag', () => {49 const fixture = MockRender(AppComponent);50 const compiled = fixture.debugElement.nativeElement;

Full Screen

Using AI Code Generation

copy

Full Screen

1import { TestBed } from '@angular/core/testing';2import { NgMocks } from 'ng-mocks';3import { FormsModule } from '@angular/forms';4import { AppComponent } from './app.component';5import { By } from '@angular/platform-browser';6describe('AppComponent', () => {7 beforeEach(async () => {8 await TestBed.configureTestingModule({9 imports: [FormsModule],10 }).compileComponents();11 });12 it('should render title', () => {13 const fixture = TestBed.createComponent(AppComponent);14 fixture.detectChanges();15 const compiled = fixture.nativeElement;16 expect(compiled.querySelector('.content span').textContent).toContain(17 );18 });19 it('should render title', () => {20 const fixture = TestBed.createComponent(AppComponent);21 fixture.detectChanges();22 const compiled = fixture.nativeElement;23 expect(compiled.querySelector('.content span').textContent).toContain(24 );25 });26 it('should render title', () => {27 const fixture = TestBed.createComponent(AppComponent);28 fixture.detectChanges();29 const compiled = fixture.nativeElement;30 expect(compiled.querySelector('.content span').textContent).toContain(31 );32 });33 it('should render title', () => {34 const fixture = TestBed.createComponent(AppComponent);35 fixture.detectChanges();36 const compiled = fixture.nativeElement;37 expect(compiled.querySelector('.content span').textContent).toContain(38 );39 });40 it('should render title', () => {41 const fixture = TestBed.createComponent(AppComponent);42 fixture.detectChanges();43 const compiled = fixture.nativeElement;44 expect(compiled.querySelector('.content span').textContent).toContain(45 );46 });47 it('should render title', () => {48 const fixture = TestBed.createComponent(AppComponent);49 fixture.detectChanges();50 const compiled = fixture.nativeElement;51 expect(compiled.querySelector('.content span').textContent).toContain(52 );53 });54 it('should render title', () => {55 const fixture = TestBed.createComponent(AppComponent);56 fixture.detectChanges();57 const compiled = fixture.nativeElement;58 expect(compiled.querySelector('.content span').textContent).toContain(59 );60 });61 it('should render title', () => {62 const fixture = TestBed.createComponent(AppComponent);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2describe('TestComponent', () => {3 beforeEach(() => MockBuilder(TestComponent));4 it('should have a button', () => {5 const fixture = MockRender(TestComponent);6 const button = ngMocks.find('button');7 expect(button).toBeTruthy();8 });9});10import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';11describe('TestComponent', () => {12 beforeEach(() => MockBuilder(TestComponent));13 it('should have a button', () => {14 const fixture = MockRender(TestComponent);15 const button = ngMocks.find('button');16 expect(button).toBeTruthy();17 });18});19import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';20describe('TestComponent', () => {21 beforeEach(() => MockBuilder(TestComponent));22 it('should have a button', () => {23 const fixture = MockRender(TestComponent);24 const button = ngMocks.find('button');25 expect(button).toBeTruthy();26 });27});28import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';29describe('TestComponent', () => {30 beforeEach(() => MockBuilder(TestComponent));31 it('should have a button', () => {32 const fixture = MockRender(TestComponent);33 const button = ngMocks.find('button');34 expect(button).toBeTruthy();35 });36});37import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';38describe('TestComponent', () => {39 beforeEach(() => MockBuilder(TestComponent));40 it('should have a button', () => {41 const fixture = MockRender(TestComponent);42 const button = ngMocks.find('button');43 expect(button).toBeTruthy();44 });45});46import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';47describe('TestComponent', () => {48 beforeEach(() => MockBuilder(TestComponent));49 it('should have a button', () => {50 const fixture = MockRender(TestComponent);51 const button = ngMocks.find('button');52 expect(button).toBeTruthy();53 });54});55import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';56describe('

Full Screen

Using AI Code Generation

copy

Full Screen

1require('ng-mocks/dist/ng-mocks-global');2require('ng-mocks');3require('ng-mocks/dist/ng-mocks');4require('ng-mocks/dist/ng-mocks-standalone');5require('ng-mocks/dist/ng-mocks-standalone-umd');6require('ng-mocks/dist/ng-mocks-standalone-umd.min');7require('ng-mocks/dist/ng-mocks-standalone.min');8require('ng-mocks/dist/ng-mocks-umd');9require('ng-mocks/dist/ng-mocks-umd.min');10require('ng-mocks/dist/ng-mocks.min');11require('ng-mocks/dist/ng-mocks');12require('ng-mocks/dist/ng-mocks-standalone');13require('ng-mocks/dist/ng-mocks-standalone-umd');14require('ng-mocks/dist/ng-mocks-standalone-umd.min');15require('ng-mocks/dist/ng-mocks-standalone.min');16require('ng-mocks/dist/ng-mocks-umd');17require('ng-mocks/dist/ng-mocks-umd.min');18require('ng-mocks/dist/ng-mocks.min');19require('ng-mocks');20require('ng-mocks/dist/ng-mocks-standalone');21require('ng-mocks/dist/ng-mocks-standalone-umd');22require('ng-mocks/dist/ng-mocks

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2beforeEach(() => MockBuilder(TestComponent));3it('should render the component', () => {4 const fixture = MockRender(TestComponent);5 expect(ngMocks.formatText(fixture)).toEqual('Hello World');6});7import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';8beforeEach(() => MockBuilder(TestComponent));9it('should render the component', () => {10 const fixture = MockRender(TestComponent);11 expect(ngMocks.formatText(fixture)).toEqual('Hello World');12});13import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';14beforeEach(() => MockBuilder(TestComponent));15it('should render the component', () => {16 const fixture = MockRender(TestComponent);17 expect(ngMocks.formatText(fixture)).toEqual('Hello World');18});19import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';20beforeEach(() => MockBuilder(TestComponent));21it('should render the component', () => {22 const fixture = MockRender(TestComponent);23 expect(ngMocks.formatText(fixture)).toEqual('Hello World');24});25import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';26beforeEach(() => MockBuilder(TestComponent));27it('should render the component', () => {28 const fixture = MockRender(TestComponent);29 expect(ngMocks.formatText(fixture)).toEqual('Hello World');30});31import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockBuilder, MockRender } from 'ng-mocks';2import { AppModule } from './app.module';3import 'jest-preset-angular';4import 'jest-matchmedia-mock';5describe('AppComponent', () => {6 beforeEach(async () => {7 await MockBuilder(AppComponent).keep(AppModule);8 });9 it('should create the app', () => {10 const fixture = MockRender(AppComponent);11 const app = fixture.point.componentInstance;12 expect(app).toBeTruthy();13 });14});15import { MockBuilder, MockRender } from 'ng-mocks';16import { AppModule } from './app.module';17import 'jest-preset-angular';18import 'jest-matchmedia-mock';19describe('AppComponent', () => {20 beforeEach(async () => {21 await MockBuilder(AppComponent).keep(AppModule);22 });23 it('should create the app', () => {24 const fixture = MockRender(AppComponent);25 const app = fixture.point.componentInstance;26 expect(app).toBeTruthy();27 });28});29import { MockBuilder, MockRender } from 'ng-mocks';30import { AppModule } from './app.module';31import 'jest-preset-angular';32import 'jest-matchmedia-mock';33describe('AppComponent', () => {34 beforeEach(async () => {35 await MockBuilder(AppComponent).keep(AppModule);36 });37 it('should create the app', () => {38 const fixture = MockRender(AppComponent);39 const app = fixture.point.componentInstance;40 expect(app).toBeTruthy();41 });42});43import { MockBuilder, MockRender } from 'ng-mocks';44import { AppModule } from './app.module';

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