Best JavaScript code snippet using ng-mocks
ModernProtocol.js
Source:ModernProtocol.js  
1const Protocol = require("./Protocol");2const Reader = require("../primitives/Reader");3const Writer = require("../primitives/Writer");45const PingReturn = Buffer.from(new Uint8Array([2]));67class ModernProtocol extends Protocol {8    /**9     * @param {Connection} connection10     */11    constructor(connection) {12        super(connection);13        this.protocol = NaN;1415        this.leaderboardPending = false;16        /** @type {LeaderboardType} */17        this.leaderboardType = null;18        /** @type {LeaderboardDataType[LeaderboardType][]} */19        this.leaderboardData = null;20        /** @type {LeaderboardDataType[LeaderboardType]} */21        this.leaderboardSelfData = null;2223        /** @type {{ source: ChatSource, message: string }[]} */24        this.chatPending = [];25        /** @type {Rect} */26        this.worldBorderPending = null;27        /** @type {ViewArea} */28        this.spectateAreaPending = null;29        this.serverInfoPending = false;30        this.worldStatsPending = false;31        this.clearCellsPending = false;32    }3334    static get type() { return "modern"; }35    get subtype() { return `m${!isNaN(this.protocol) ? ("00" + this.protocol).slice(-2) : "//"}`; }3637    /**38     * @param {Reader} reader39     */40    distinguishes(reader) {41        if (reader.length < 5) return false;42        if (reader.readUInt8() !== 1) return false;43        this.gotProtocol = true;44        this.protocol = reader.readUInt32();45        if (this.protocol !== 3) return void this.fail(1003, "Unsupported protocol version");46        this.connection.createPlayer();47        return true;48    }4950    /**51     * @param {Reader} reader52     */53    onSocketMessage(reader) {54        const messageId = reader.readUInt8();55        switch (messageId) {56            case 2:57                this.send(PingReturn);58                this.worldStatsPending = true;59                break;60            case 3:61                if (reader.length < 12)62                    return void this.fail(1003, "Unexpected message format");63                let i, l, count;64                this.connection.mouseX = reader.readInt32();65                this.connection.mouseY = reader.readInt32();66                this.connection.splitAttempts += reader.readUInt8();67                count = reader.readUInt8();68                for (i = 0, l = this.connection.minions.length; count > 0 && i < l; i++)69                    this.connection.minions[i].splitAttempts += count;7071                const globalFlags = reader.readUInt8();72                if (globalFlags & 1) {73                    if (reader.length < 13)74                        return void this.fail(1003, "Unexpected message format");75                    this.connection.spawningName = reader.readZTStringUTF8();76                }77                if (globalFlags & 2) this.connection.requestingSpectate = true;78                if (globalFlags & 4) this.connection.isPressingQ = true;79                if (globalFlags & 8) this.connection.isPressingQ = this.connection.hasProcessedQ = false;80                if (globalFlags & 16) this.connection.ejectAttempts++;81                if (globalFlags & 32)82                    for (i = 0, l = this.connection.minions.length; i < l; i++)83                        this.connection.minions[i].ejectAttempts++;84                if (globalFlags & 64) this.connection.minionsFrozen = !this.connection.minionsFrozen;85                if (globalFlags & 128) {86                    if (reader.length < 13 + (globalFlags & 1))87                        return void this.fail(1003, "Unexpected message format");88                    count = reader.readUInt8();89                    if (reader.length < 13 + (globalFlags & 1) + count)90                        return void this.fail(1003, "Unexpected message format");91                    for (let i = 0; i < count; i++)92                        this.connection.onChatMessage(reader.readZTStringUTF8());93                }94                break;95            default: return void this.fail(1003, "Unknown message type");96        }97    }9899    /**100     * @param {ChatSource} source101     * @param {string} message102     */103    onChatMessage(source, message) {104        this.chatPending.push({105            source: source,106            message: message107        });108    }109110    /**111     * @param {PlayerCell} cell112     */113    onNewOwnedCell(cell) { /* ignored */ }114115    /**116     * @param {Rect} range117     * @param {boolean} includeServerInfo118     */119    onNewWorldBounds(range, includeServerInfo) {120        this.worldBorderPending = range;121        this.serverInfoPending = includeServerInfo;122    }123124    onWorldReset() {125        this.clearCellsPending = true;126        this.worldBorderPending = false;127        this.worldStatsPending = false;128        this.onVisibleCellUpdate([], [], [], []);129    }130131    /**132     * @param {LeaderboardType} type133     * @param {LeaderboardDataType[type][]} data134     * @param {LeaderboardDataType[type]=} selfData135     */136    onLeaderboardUpdate(type, data, selfData) {137        this.leaderboardPending = true;138        this.leaderboardType = type;139        this.leaderboardData = data;140        this.leaderboardSelfData = selfData;141    }142143    /**144     * @param {ViewArea} viewArea145     */146    onSpectatePosition(viewArea) {147        this.spectateAreaPending = viewArea;148    }149150    /**151     * @abstract152     * @param {Cell[]} add153     * @param {Cell[]} upd154     * @param {Cell[]} eat155     * @param {Cell[]} del156     */157    onVisibleCellUpdate(add, upd, eat, del) {158        let globalFlags = 0, hitSelfData, flags, item, i, l;159160        if (this.spectateAreaPending != null) globalFlags |= 1;161        if (this.worldBorderPending != null)  globalFlags |= 2;162        if (this.serverInfoPending)           globalFlags |= 4;163        if (this.connection.hasPlayer && this.connection.player.hasWorld && this.worldStatsPending)164                                              globalFlags |= 8;165        if (this.chatPending.length > 0)      globalFlags |= 16;166        if (this.leaderboardPending)          globalFlags |= 32;167        if (this.clearCellsPending)           globalFlags |= 64,168            this.clearCellsPending = false;169        if (add.length > 0)                   globalFlags |= 128;170        if (upd.length > 0)                   globalFlags |= 256;171        if (eat.length > 0)                   globalFlags |= 512;172        if (del.length > 0)                   globalFlags |= 1024;173174        if (globalFlags === 0) return;175176        const writer = new Writer();177        writer.writeUInt8(3);178        writer.writeUInt16(globalFlags);179180        if (this.spectateAreaPending != null) {181            writer.writeFloat32(this.spectateAreaPending.x);182            writer.writeFloat32(this.spectateAreaPending.y);183            writer.writeFloat32(this.spectateAreaPending.s);184            this.spectateAreaPending = null;185        }186        if (this.worldBorderPending != null) {187            item = this.worldBorderPending;188            writer.writeFloat32(item.x - item.w);189            writer.writeFloat32(item.x + item.w);190            writer.writeFloat32(item.y - item.h);191            writer.writeFloat32(item.y + item.h);192            this.worldBorderPending = null;193        }194        if (this.serverInfoPending) {195            writer.writeUInt8(this.handle.gamemode.type);196            item = this.handle.version.split(".");197            writer.writeUInt8(parseInt(item[0]));198            writer.writeUInt8(parseInt(item[1]));199            writer.writeUInt8(parseInt(item[2]));200            this.serverInfoPending = false;201        }202        if (this.worldStatsPending) {203            item = this.connection.player.world.stats;204            writer.writeZTStringUTF8(item.name);205            writer.writeZTStringUTF8(item.gamemode);206            writer.writeFloat32(item.loadTime / this.handle.tickDelay);207            writer.writeUInt32(item.uptime);208            writer.writeUInt16(item.limit);209            writer.writeUInt16(item.external);210            writer.writeUInt16(item.internal);211            writer.writeUInt16(item.playing);212            writer.writeUInt16(item.spectating);213            this.worldStatsPending = false;214        }215        if ((l = this.chatPending.length) > 0) {216            writer.writeUInt16(l);217            for (i = 0; i < l; i++) {218                item = this.chatPending[i];219                writer.writeZTStringUTF8(item.source.name);220                writer.writeColor(item.source.color);221                writer.writeUInt8(item.source.isServer ? 1 : 0);222                writer.writeZTStringUTF8(item.message);223            }224            this.chatPending.splice(0, l);225        }226        if (this.leaderboardPending) {227            l = this.leaderboardData.length;228            switch (this.leaderboardType) {229                case "ffa":230                    writer.writeUInt8(1);231                    for (i = 0; i < l; i++) {232                        item = this.leaderboardData[i];233                        flags = 0;234                        if (item.highlighted) flags |= 1;235                        if (item === this.leaderboardSelfData)236                            flags |= 2, hitSelfData = true;237                        writer.writeUInt16(item.position);238                        writer.writeUInt8(flags);239                        writer.writeZTStringUTF8(item.name);240                    }241                    if (!hitSelfData && (item = this.leaderboardSelfData) != null) {242                        writer.writeUInt16(item.position);243                        flags = item.highlighted ? 1 : 0;244                        writer.writeUInt8(flags);245                        writer.writeZTStringUTF8(item.name);246                    }247                    writer.writeUInt16(0);248                    break;249                case "pie":250                    writer.writeUInt8(2);251                    writer.writeUInt16(l);252                    for (i = 0; i < l; i++)253                        writer.writeFloat32(this.leaderboardData[i]);254                    break;255                case "text":256                    writer.writeUInt8(3);257                    writer.writeUInt16(l);258                    for (i = 0; i < l; i++)259                        writer.writeZTStringUTF8(this.leaderboardData[i]);260                    break;261            }262263            this.leaderboardPending = false;264            this.leaderboardType = null;265            this.leaderboardData = null;266            this.leaderboardSelfData = null;267        }268269        if ((l = add.length) > 0) {270            for (i = 0; i < l; i++) {271                item = add[i];272                writer.writeUInt32(item.id);273                writer.writeUInt8(item.type);274                writer.writeFloat32(item.x);275                writer.writeFloat32(item.y);276                writer.writeUInt16(item.size);277                writer.writeColor(item.color);278                flags = 0;279                if (item.type === 0 && item.owner === this.connection.player)280                    flags |= 1;281                if (!!item.name) flags |= 2;282                if (!!item.skin) flags |= 4;283                writer.writeUInt8(flags);284                if (!!item.name) writer.writeZTStringUTF8(item.name);285                if (!!item.skin) writer.writeZTStringUTF8(item.skin);286            }287            writer.writeUInt32(0);288        }289        if ((l = upd.length) > 0) {290            for (i = 0; i < l; i++) {291                item = upd[i];292                flags = 0;293                if (item.posChanged) flags |= 1;294                if (item.sizeChanged) flags |= 2;295                if (item.colorChanged) flags |= 4;296                if (item.nameChanged) flags |= 8;297                if (item.skinChanged) flags |= 16;298                writer.writeUInt32(item.id);299                writer.writeUInt8(flags);300                if (item.posChanged) {301                    writer.writeFloat32(item.x);302                    writer.writeFloat32(item.y);303                }304                if (item.sizeChanged)305                    writer.writeUInt16(item.size);306                if (item.colorChanged) writer.writeColor(item.color);307                if (item.nameChanged) writer.writeZTStringUTF8(item.name);308                if (item.skinChanged) writer.writeZTStringUTF8(item.skin);309            }310            writer.writeUInt32(0);311        }312        if ((l = eat.length) > 0) {313            for (i = 0; i < l; i++) {314                item = eat[i];315                writer.writeUInt32(item.id);316                writer.writeUInt32(item.eatenBy.id);317            }318            writer.writeUInt32(0);319        }320        if ((l = del.length) > 0) {321            for (i = 0; i < l; i++)322                writer.writeUInt32(del[i].id);323            writer.writeUInt32(0);324        }325326        this.send(writer.finalize());327    }328}329330module.exports = ModernProtocol;331332const Cell = require("../cells/Cell");333const PlayerCell = require("../cells/PlayerCell");
...GlobalFlag.js
Source:GlobalFlag.js  
1import { initFlag,2         fetchValFromInfo,3         fullWidthNumber2Integer } from './Utils.js'4export function globalFlag (szData, team, tar, debug = false) {5  let flagArr = []6  // case: effect on statistics screen7  if (/ç²å¾ç¶é©å¼çº0/.test(szData.info) && tar !== 5) {8    let flag = initFlag(team.length, 'exp')9    flag.global = true10    flag.exp = -10011    flagArr.push(flag)12  }13  if (/(æå)?ç²å¾çç¶é©å¼(æå)?/.test(szData.info)) {14    let flag = initFlag(team.length, 'exp')15    flag.global = true16    flag.exp = parseInt(fetchValFromInfo(szData.info, /\d+%/))17    flagArr.push(flag)18  }19  if (/æåç²å¾çéå¹£ /.test(szData.info)) {20    let flag = initFlag(team.length, 'coin')21    flag.global = true22    flag.coin = parseInt(fetchValFromInfo(szData.info, /\d+%/))23    flagArr.push(flag)24  }25  if (/ç¶é©å¼åéå¹£/.test(szData.info)) {26    let flag1 = initFlag(team.length, 'exp')27    let flag2 = initFlag(team.length, 'coin')28    flag1.global = flag2.global = true29    flag1.exp = parseInt(fetchValFromInfo(szData.info, /(\d+)%/))30    flag2.coin = parseInt(fetchValFromInfo(szData.info, /(\d+)%/))31    flagArr.push(flag1, flag2)32  }33  if (/éå¹£\d+%ãç¶é©å¼\d+%/.test(szData.info)) {34    let flag1 = initFlag(team.length, 'exp')35    let flag2 = initFlag(team.length, 'coin')36    flag1.global = flag2.global = true37    flag1.exp = parseInt(fetchValFromInfo(szData.info, /éå¹£(\d+)%/))38    flag2.coin = parseInt(fetchValFromInfo(szData.info, /ç¶é©å¼(\d+)%/))39    flagArr.push(flag1, flag2)40  }41  if (/æåå¥ç´ç¶é©å¼/.test(szData.info)) {42    let flag = initFlag(team.length, 'cardExp')43    flag.global = true44    flag.cardExp = parseInt(fetchValFromInfo(szData.info, /(\d+)%/))45    flagArr.push(flag)46  }47  if (/æå寶箱åºç¾ç/.test(szData.info)) {48    let flag = initFlag(team.length, 'boxOccurance')49    flag.global = true50    flag.boxOccurance = true51    flagArr.push(flag)52  }53  if (/æåæå¯¶ç/.test(szData.info)) {54    let flag = initFlag(team.length, 'boxDropChance')55    flag.global = true56    flag.boxDropChance = true57    flagArr.push(flag)58  }59  // case: effect on answer the question60  if (/åçé£æåº¦(\S*)ä¸é/.test(szData.info)) {61    let flag = initFlag(team.length, 'difficultyDrop')62    const str = fetchValFromInfo(szData.info, /åçé£æåº¦(\S*)ä¸é/)63    const arr = ['å¾®å¹
', '', 'ä¸å¹
', '大å¹
', '顯è']64    flag.global = true65    flag.difficultyDrop = arr.indexOf(str)66    flagArr.push(flag)67  }68  if (/(ç顿è½ç¼åæéå»¶é·\d+ç§)|(å»¶é·\d+ç§çé¡æè½æééå¶)/.test(szData.info)) {69    let flag = initFlag(team.length, 'answerTime')70    flag.global = true71    flag.answerTime = szData.const72    flagArr.push(flag)73  }74  if (/å¯ä»¥å¨åç䏿£ç¢ºæå°è§£é¡çæ
å復çºé¸æåé¡é¡åä¹å/.test(szData.info)) {75    let flag = initFlag(team.length, 'answerReset')76    flag.global = true77    flag.answerReset = true78    flagArr.push(flag)79  }80  if (/(ç«|æ°´|é·)屬æ§åé¡é¡åè¼å®¹æåºç¾/.test(szData.info)) {81    let flag = initFlag(team.length, 'questionProp')82    flag.global = true83    flag.questionPropUp = {84    	prop: szData.elmts,85    	cnt: 186    }87    if (szData.info.indexOf('ææå¼') >= 0) {88      flag.questionPropUp.cnt = fullWidthNumber2Integer(fetchValFromInfo(szData.info, /ï¼ææå¼ï¼(\S+)ï¼/))89    }90    flagArr.push(flag)91  }92  if (/å¨åé¸ä¸åçä¸è¼å®¹æåºç¾ã\S+ãé¡å/.test(szData.info)) {93    let flag = initFlag(team.length, 'questionCategoryUp')94    flag.global = true95    flag.questionCategoryUp = szData.quest_type96    flagArr.push(flag)97  }98  // case: effect on chain99  if (/æ¼ä¸æ¬¡ä»»åä¸ï¼å
é\S次ä¿è·é£éæ¸/.test(szData.info)) {100    let flag = initFlag(team.length, 'chainSecure')101    flag.global = true102    flag.chainSecure = 'ä¸äºä¸åäº'.indexOf(fetchValFromInfo(szData.info, /å
é(\S)次/)) + 1103    flagArr.push(flag)104  }105  if (/ä»»åéå§æè³¦äºé£éæ¸å \d+çææ/.test(szData.info)) {106    let flag = initFlag(team.length, 'chainBoost')107    flag.global = true108    flag.chainBoost = parseInt(fetchValFromInfo(szData.info, /é£éæ¸å (\d+)/))109    flagArr.push(flag)110  }111  if (debug)112    console.log({ szData: szData, effects: flagArr });113  return flagArr114}115export function recoverRelative (szData, team, debug = false) {116  let flagArr = []117  // case: recover all118  if (/æ°é¬¥çµæå¾å復å
¨é«éå\d+%HP/.test(szData.info)) {119    let flag = initFlag(team.length, 'recoverAtEnd')120    flag.global = true121    flag.recoverAtEnd = {122      ratio: parseInt(fetchValFromInfo(szData.info, /(\d+)%HP/))123    }124    flagArr.push(flag)125  }126  // case: recover certain source127  if (/æ°é¬¥çµæå¾ï¼å復ã\S+ãç²¾é\d+%HP/.test(szData.info)) {128    let flag = initFlag(team.length, 'recoverAtEnd')129    flag.target = team.map(card => {130    	if (card.obtainType === undefined) return false131    	return szData.info.indexOf(card.obtainType.title) >= 0132    })133    flag.recoverAtEnd = {134      ratio: parseInt(fetchValFromInfo(szData.info, /(\d+)%HP/))135    }136    flagArr.push(flag)137  }138  if (debug)139    console.log({ szData: szData, effects: flagArr });140  return flagArr141}142export function mindRelative (szData, team, debug = false) {143  let flagArr = []144  if (/çç©¿èç¼ç¡å¾å¾è¦çç實/.test(szData.info)) {145    let flag1 = initFlag(team.length, 'answerRatio')146    let flag2 = initFlag(team.length, 'enermyHP')147    flag1.global = flag2.global = true148    flag1.answerRatio = true149    flag2.enermyHP = true150    flagArr.push(flag1, flag2)151  }152  if (/çç©¿æµæ¹æè½å彿çè¡å/.test(szData.info)) {153    let flag = initFlag(team.length, 'enermyReflection')154    flag.global = true155    flag.enermyReflection = true156    flagArr.push(flag)157  }158  if (/çç©¿æµæ¹ä¸æ¬¡çè¡å/.test(szData.info)) {159    let flag = initFlag(team.length, 'enermyNext')160    flag.global = true161    flag.enermyNext = true162    flagArr.push(flag)163  }164  if (/èç ´æµäººçæ¤ææ¢ä»¶/.test(szData.info)) {165    let flag = initFlag(team.length, 'enermyAngerCondition')166    flag.global = true167    flag.enermyAngerCondition = true168    flagArr.push(flag)169  }170  if (/çç©¿æµæ¹æ»äº¡æçè¡å/.test(szData.info)) {171    let flag = initFlag(team.length, 'enermyDeath')172    flag.global = true173    flag.enermyDeath = true174    flagArr.push(flag)175  }176  if (/å¯ä»¥å¾ç¥åçççé¡æç¸¾/.test(szData.info)) {177    let flag = initFlag(team.length, 'answerRatio')178    flag.global = true179    flag.answerRatio = true180    flagArr.push(flag)181  }182  if (/è½å¤ å¾ç¥æµæ¹çHP/.test(szData.info)) {183    let flag = initFlag(team.length, 'enermyHP')184    flag.global = true185    flag.enermyHP = true186    flagArr.push(flag)187  }188  if (debug)189    console.log({ szData: szData, effects: flagArr });190  return flagArr191}192// a reduce function for global effects193export function groupGlobal (globalFlags, effect) {194  if (effect.answerRatio !== undefined) {195    globalFlags.answerRatio = true196  }197  if (effect.answerReset !== undefined) {198    globalFlags.answerReset = true199  }200  if (effect.answerTime !== undefined) {201    globalFlags.answerTime = Math.max(globalFlag.answerTime, effect.answerTime)202  }203  if (effect.boxDropChance !== undefined) {204    globalFlags.boxDropChance = true205  }206  if (effect.boxOccurance !== undefined) {207    globalFlags.boxOccurance = true208  }209  if (effect.cardExp !== undefined) {210    globalFlags.cardExp = globalFlags.cardExp || 0211    globalFlags.cardExp += effects.cardExp212  }213  if (effect.chainBoost !== undefined) {214    globalFlags.chainBoost = globalFlags.chainBoost || 0215    globalFlags.chainBoost += effect.chainBoost216  }217  if (effect.chainSecure !== undefined) {218    globalFlags.chainSecure = globalFlags.chainSecure || 0219    globalFlags.chainSecure = Math.max(globalFlags.chainSecure, effect.chainSecure)220  }221  if (effect.coin !== undefined) {222    globalFlags.coin = globalFlags.coin || 0223    globalFlags.coin += effects.coin224  }225  if (effect.difficultyDrop !== undefined) {226    globalFlags.difficultyDrop = globalFlags.difficultyDrop || 0227    globalFlags.difficultyDrop = Math.max(globalFlags.difficultyDrop, effect.difficultyDrop)228  }229  if (effect.enermyAngerCondition !== undefined) {230    globalFlags.enermyAngerCondition = true231  }232  if (effect.enermyDeath !== undefined) {233    globalFlags.enermyDeath = true234  }235  if (effect.enermyHP !== undefined) {236    globalFlags.enermyHP = true237  }238  if (effect.enermyNext !== undefined) {239    globalFlags.enermyNext = true240  }241  if (effect.enermyReflection !== undefined) {242    globalFlags.enermyReflection = true243  }244  if (effect.exp !== undefined) {245    globalFlags.exp = globalFlags.exp || 0246    globalFlags.exp += effect.exp247  }248  if (effect.questionCategoryUp !== undefined) {249    globalFlags.questionCategoryUp = globalFlags.questionCategoryUp || []250    globalFlags.questionCategoryUp.push(effect.questionCategoryUp)251  }252  if (effect.questionPropUp !== undefined) {253    globalFlags.questionPropUp = globalFlags.questionPropUp || { 'ç«': 0, 'æ°´': 0, 'é·': 0 }254    globalFlags.questionPropUp[effect.questionPropUp.prop] += effect.questionPropUp.cnt255  }256  if (effect.recoverAtEnd !== undefined) {257    globalFlags.recoverAtEnd = globalFlags.recoverAtEnd || 0258    globalFlags.recoverAtEnd += effect.recoverAtEnd.ratio259  }260  return globalFlags...run_with_commands.ts
Source:run_with_commands.ts  
1/*2 * Licensed to Elasticsearch B.V. under one or more contributor3 * license agreements. See the NOTICE file distributed with4 * this work for additional information regarding copyright5 * ownership. Elasticsearch B.V. licenses this file to you under6 * the Apache License, Version 2.0 (the "License"); you may7 * not use this file except in compliance with the License.8 * You may obtain a copy of the License at9 *10 *    http://www.apache.org/licenses/LICENSE-2.011 *12 * Unless required by applicable law or agreed to in writing,13 * software distributed under the License is distributed on an14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY15 * KIND, either express or implied.  See the License for the16 * specific language governing permissions and limitations17 * under the License.18 */19import { ToolingLog, pickLevelFromFlags } from '../tooling_log';20import { RunContext, RunOptions } from './run';21import { getFlags, FlagOptions, mergeFlagOptions } from './flags';22import { Cleanup } from './cleanup';23import { getHelpForAllCommands, getCommandLevelHelp } from './help';24import { createFlagError } from './fail';25import { withProcRunner } from '../proc_runner';26export type CommandRunFn<T> = (context: RunContext & T) => Promise<void> | void;27export interface Command<T> {28  name: string;29  run: CommandRunFn<T>;30  description: RunOptions['description'];31  usage?: RunOptions['usage'];32  flags?: FlagOptions;33}34export interface RunWithCommandsOptions<T> {35  log?: RunOptions['log'];36  description?: RunOptions['description'];37  usage?: RunOptions['usage'];38  globalFlags?: FlagOptions;39  extendContext?(context: RunContext): Promise<T> | T;40}41export class RunWithCommands<T> {42  constructor(43    private readonly options: RunWithCommandsOptions<T>,44    private readonly commands: Array<Command<T>> = []45  ) {}46  command(options: Command<T>) {47    return new RunWithCommands(this.options, this.commands.concat(options));48  }49  async execute() {50    const globalFlags = getFlags(process.argv.slice(2), {51      allowUnexpected: true,52    });53    const isHelpCommand = globalFlags._[0] === 'help';54    const commandName = isHelpCommand ? globalFlags._[1] : globalFlags._[0];55    const command = this.commands.find((c) => c.name === commandName);56    const log = new ToolingLog({57      level: pickLevelFromFlags(globalFlags, {58        default: this.options.log?.defaultLevel,59      }),60      writeTo: process.stdout,61    });62    const globalHelp = getHelpForAllCommands({63      description: this.options.description,64      usage: this.options.usage,65      globalFlagHelp: this.options.globalFlags?.help,66      commands: this.commands,67    });68    const cleanup = Cleanup.setup(log, globalHelp);69    if (!command) {70      if (globalFlags.help) {71        log.write(globalHelp);72        process.exit();73      }74      const error = createFlagError(75        commandName ? `unknown command [${commandName}]` : `missing command name`76      );77      cleanup.execute(error);78      process.exit(1);79    }80    const commandFlagOptions = mergeFlagOptions(this.options.globalFlags, command.flags);81    const commandFlags = getFlags(process.argv.slice(2), commandFlagOptions);82    // strip command name plus "help" if we're actually executing the fake "help" command83    if (isHelpCommand) {84      commandFlags._.splice(0, 2);85    } else {86      commandFlags._.splice(0, 1);87    }88    const commandHelp = getCommandLevelHelp({89      usage: this.options.usage,90      globalFlagHelp: this.options.globalFlags?.help,91      command,92    });93    cleanup.helpText = commandHelp;94    if (commandFlags.help || isHelpCommand) {95      cleanup.execute();96      log.write(commandHelp);97      process.exit();98    }99    if (!commandFlagOptions.allowUnexpected && commandFlags.unexpected.length) {100      cleanup.execute(createFlagError(`Unknown flag(s) "${commandFlags.unexpected.join('", "')}"`));101      return;102    }103    try {104      await withProcRunner(log, async (procRunner) => {105        const context: RunContext = {106          log,107          flags: commandFlags,108          procRunner,109          addCleanupTask: cleanup.add.bind(cleanup),110        };111        const extendedContext = {112          ...context,113          ...(this.options.extendContext ? await this.options.extendContext(context) : ({} as T)),114        };115        await command.run(extendedContext);116      });117    } catch (error) {118      cleanup.execute(error);119      // exitCode is set by `cleanup` when necessary120      process.exit();121    } finally {122      cleanup.execute();123    }124  }...Using AI Code Generation
1import { globalFlags } from 'ng-mocks';2import { mockInstance } from 'ng-mocks';3import { mockProvider } from 'ng-mocks';4import { mockRender } from 'ng-mocks';5import { mockReset } from 'ng-mocks';6import { mockResetAll } from 'ng-mocks';7import { mockResetAllProviders } from 'ng-mocks';8import { mockResetAllRenderers } from 'ng-mocks';9import { mockResetRender } from 'ng-mocks';10import { mockResetRenderer } from 'ng-mocks';11import { mockResetRendererAll } from 'ng-mocks';12import { mockResetRendererProvider } from 'ng-mocks';13import { mockResetRendererProviders } from 'ng-mocks';14import { mockResetRendererProviderType } from 'ng-mocks';15import { mockResetRendererProviderTypes } from 'ng-mocks';16import { mockResetRendererType } from 'ng-mocks';17import { mockResetRendererTypes } from 'ng-mocks';18import { mockResetType } from 'ng-mocks';19import { mockResetTypes } from 'ng-mocks';20import { mockType } from 'ng-mocksUsing AI Code Generation
1import { globalFlags } from 'ng-mocks';2import { Component, NgModule } from '@angular/core';3import { TestBed } from '@angular/core/testing';4import { MockBuilder, MockRender } from 'ng-mocks';5@Component({6})7class TestComponent {}8@NgModule({9})10class TestModule {}11describe('test', () => {12  beforeEach(() => {13    globalFlags.reset();14    return MockBuilder(TestComponent, TestModule);15  });16  it('should work', () => {17    MockRender(TestComponent);18  });19});20import { globalFlags } from 'ng-mocks';21describe('test', () => {22  beforeEach(() => {23    globalFlags.reset();24  });25  it('should work', () => {26    expect(true).toBe(true);27  });28});29import { globalFlags } from 'ng-mocks';30globalFlags.reset();31### `globalFlags.reset()`32### `globalFlags.resetAll()`33### `globalFlags.resetCache()`34### `globalFlags.resetMock()`35### `globalFlags.resetMockAll()`36### `globalFlags.resetMockCache()`37### `MockInstance<T>(instance: T, mock: Partial<T>): T`38import { MockInstance } from 'ng-mocks';39class TestClass {Using AI Code Generation
1import { globalFlags } from 'ng-mocks';2import { Component, NgModule } from '@angular/core';3import { BrowserModule } from '@angular/platform-browser';4@Component({5    <h2>{{title}}</h2>6})7export class AppComponent {8    title = 'Angular';9}10@NgModule({11    imports: [12})13export class AppModule { }14describe('AppComponent', () => {15    it('should create the app', () => {16        const fixture = globalFlags().create(AppComponent);17        const app = fixture.componentInstance;18        expect(app).toBeTruthy();19    });20    it(`should have as title 'Angular'`, () => {21        const fixture = globalFlags().create(AppComponent);22        const app = fixture.componentInstance;23        expect(app.title).toEqual('Angular');24    });25    it('should render title', () => {26        const fixture = globalFlags().create(AppComponent);27        fixture.detectChanges();28        const compiled = fixture.nativeElement;29        expect(compiled.querySelector('h2').textContent).toContain('Angular');30    });31});32module.exports = {33};34{35    "compilerOptions": {36    },37}38{39    "compilerOptions": {40        "importHelpers": true,Using AI Code Generation
1import { globalFlags } from 'ng-mocks';2globalFlags({3});4import { globalFlags } from 'ng-mocks';5globalFlags({6});7import { globalFlags } from 'ng-mocks';8globalFlags({9});10import { globalFlags } from 'ng-mocks';11globalFlags({12});13import { globalFlags } from 'ng-mocks';14globalFlags({15});16import { globalFlags } from 'ng-mocks';17globalFlags({18});19import { globalFlags } from 'ng-mocks';20globalFlags({21});22import { globalFlags } from 'ng-mocks';23globalFlags({24});25import { globalFlags } from 'ng-mocks';26globalFlags({27});28import { globalFlags } from 'ng-mocks';Using AI Code Generation
1require('ng-mocks').globalFlags({2});3import { NgModule, Injector } from '@angular/core';4import { createCustomElement } from '@angular/elements';5import { BrowserModule } from '@angular/platform-browser';6import { AppComponent } from './app.component';7@NgModule({8  imports: [9})10export class AppModule {11  constructor(private injector: Injector) {12    const el = createCustomElement(AppComponent, { injector });13    customElements.define('app-root', el);14  }15  ngDoBootstrap() {}16}17import { Component } from '@angular/core';18@Component({19})20export class AppComponent {21  title = 'app';22}23import { TestBed, async } from '@angular/core/testing';24import { AppComponent } from './app.component';25describe('AppComponent', () => {26  beforeEach(async(() => {27    TestBed.configureTestingModule({28    }).compileComponents();29  }));30  it('should create the app', () => {31    const fixture = TestBed.createComponent(AppComponent);32    const app = fixture.debugElement.componentInstance;33    expect(app).toBeTruthy();34  });35  it(`should have as title 'app'`, () => {36    const fixture = TestBed.createComponent(AppComponent);37    const app = fixture.debugElement.componentInstance;38    expect(app.title).toEqual('app');39  });40  it('should render title in a h1 tag', () => {41    const fixture = TestBed.createComponent(AppComponent);42    fixture.detectChanges();43    const compiled = fixture.debugElement.nativeElement;44    expect(compiled.querySelector('h1').textContent).toContain('Hello World');45  });46});47h1 {48  color: red;49}50import { TestBed, async } from '@angular/core/testing';51import { AppComponent } from './app.component';52describe('AppComponent', () => {53  beforeEach(async(() => {54    TestBed.configureTestingModule({Using AI Code Generation
1import { globalFlags } from 'ng-mocks';2const flags = globalFlags();3globalFlags({ ...flags, mockRender: true });4import { MyComponent } from './my.component';5import { MyModule } from './my.module';6import { MockBuilder, MockRender } from 'ng-mocks';7import { TestBed } from '@angular/core/testing';8describe('MyComponent', () => {9  beforeEach(() => MockBuilder(MyComponent, MyModule));10  it('should render', () => {11    const fixture = MockRender(MyComponent);12    const component = fixture.point.componentInstance;13    expect(component).toBeDefined();14  });15});16import { globalMock } from 'ng-mocks';17const mock = globalMock('mock');18globalMock('mock', { ...mock, provide: { useValue: 'mock' } });19import { MyComponent } from './my.component';20import { MyModule } from './my.module';21import { MockBuilder, MockRender } from 'ng-mocks';22import { TestBed } from '@angular/core/testing';23describe('MyComponent', () => {24  beforeEach(() => MockBuilder(MyComponent, MyModule));25  it('should render', () => {26    const fixture = MockRender(MyComponent);27    const component = fixture.point.componentInstance;28    expect(component).toBeDefined();29  });30});31import { globalMock } from 'ng-mocks';32const mock = globalMock('mock');33globalMock('mock', { ...mock,Using AI Code Generation
1import { globalFlags } from 'ng-mocks';2describe('test', () => {3  it('should return true if selector in global flags', () => {4    globalFlags({5    });6    const component = () => ({7    });8    expect(globalFlags(component)).toBe(true);9  });10  it('should return false if selector not in global flags', () => {11    globalFlags({12    });13    const component = () => ({14    });15    expect(globalFlags(component)).toBe(false);16  });17});18import { globalFlags } from 'ng-mocks';19describe('test', () => {20  it('should return true if selector in global flags', () => {21    globalFlags({22    });23    const component = () => ({24    });25    expect(globalFlags(component)).toBe(true);26  });27  it('should return false if selector not in global flags', () => {28    globalFlags({29    });30    const component = () => ({31    });32    expect(globalFlags(component)).toBe(false);33  });34});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!!
