Best JavaScript code snippet using ts-auto-mock
traverseModules.js
Source:traverseModules.js
1const parser = require('@babel/parser')2const traverse = require('@babel/traverse').default3const fs = require('fs')4const { resolve, dirname, join, extname } = require('path')5// ç¨äºå¨ç»ç«¯è¾åºé¢è²ä¸åçå
容6const chalk = require('chalk')7const postcss = require('postcss')8const postcssLess = require('postcss-less')9const postcssScss = require('postcss-scss')10const JS_EXT = ['.js', '.jsx', '.ts', '.tsx']11const CSS_EXT = ['.css', '.less', '.scss']12const JSON_EXT = ['.json']13let requirePathResolver = () => {}14const MODULE_TYPES = {15 JS: 1 << 0,16 CSS: 1 << 1,17 JSON: 1 << 218}19// åæ¾å·²ç»å¤çè¿ç模åè·¯å¾20const visitedModules = new Set()21// å°è¯å¯¹ä¸ä¸ªè·¯å¾è¿è¡è§£æ, å¤ææ¯å¦æ¯è·¯å¾ (å 为忽ç¥äºåç¼å, æ以éè¦å¤æ)22function isDirectory (filePath) {23 try {24 return fs.statSync(filePath).isDirectory()25 } catch (e) {26 return false27 }28}29function moduleResolve (curModulePath, requirePath) {30 if (typeof requirePathResolver === 'function') {31 const res = requirePathResolver(dirname(curModulePath), requirePath)32 if (typeof res === 'string') {33 requirePath = res34 }35 }36 requirePath = resolve(dirname(curModulePath), requirePath)37 // 对第ä¸æ¹æ¨¡åä¸è¿è¡æ£æµ38 if (requirePath.includes('node_modules')) {39 return ''40 }41 requirePath = completeModulePath(requirePath)42 if (visitedModules.has(requirePath)) {43 return ''44 } else {45 visitedModules.add(requirePath)46 }47 return requirePath48}49exports.setRequirePathResolver = function (resolver) {50 requirePathResolver = resolver51}52function completeModulePath (modulePath) {53 const EXTS = [...JSON_EXT, ...JS_EXT]54 // 表示带æåç¼åçç´æ¥è¿å55 if (modulePath.match(/\.[a-zA-Z]+$/)) return modulePath56 // å°è¯æ·»å ä¸åçåç¼å, è¿åæ£ç¡®çè·¯å¾åç¼57 function tryCompletePath (resolvePath) {58 for (let i = 0; i < EXTS.length; i++) {59 let tempPath = resolvePath(EXTS[i])60 if (fs.existsSync(tempPath)) return tempPath61 }62 }63 function NotFoundModule (modulePath) {64 throw chalk.red('module not found: ' + modulePath)65 }66 // å¦æä¼ å
¥è·¯å¾æ¯ä¸ä¸ªç®å½67 if (isDirectory(modulePath)) {68 const tryModulePath = tryCompletePath(69 (ext) => join(modulePath, 'index' + ext))70 if (!tryModulePath) {71 NotFoundModule(tryModulePath)72 } else {73 return tryModulePath74 }75 } else if (!EXTS.some(ext => modulePath.endsWith(ext))) {76 const tryModulePath = tryCompletePath((ext) => modulePath + ext)77 if (!tryModulePath) {78 NotFoundModule(tryModulePath)79 } else {80 return tryModulePath81 }82 }83 return modulePath84}85// 解æ对åºç±»å86function getModuleType (modulePath) {87 const moduleExt = extname(modulePath)88 if (JS_EXT.some(ext => ext === moduleExt)) {89 return MODULE_TYPES.JS90 } else if (CSS_EXT.some(ext => ext === moduleExt)) {91 return MODULE_TYPES.CSS92 } else if (JSON_EXT.some(ext => ext === moduleExt)) {93 return MODULE_TYPES.JSON94 }95}96function resolveBabelSyntaxPlugins (modulePath) {97 const plugins = []98 if (['.tsx', '.jsx'].some(ext => modulePath.endsWith(ext))) {99 plugins.push('jsx')100 }101 if (['.ts', '.tsx'].some(ext => modulePath.endsWith(ext))) {102 plugins.push('typescript')103 }104 return plugins105}106function traverseJsModule (currentModulePath, callback) {107 const moduleFileContent = fs.readFileSync(currentModulePath,108 { encoding: 'utf-8' })109 // éè¿ parser 转æ¢ä¸º ast, unambiguous 表æåºäº ES6110 const ast = parser.parse(moduleFileContent, {111 sourceType: 'unambiguous',112 plugins: resolveBabelSyntaxPlugins(currentModulePath)113 })114 // æ ¹æ® ast æåä¾èµå
³ç³»115 traverse(ast, {116 ImportDeclaration (path) {117 const subModulePath = moduleResolve(currentModulePath,118 path.get('source.value').node)119 if (!subModulePath) return120 callback && callback(subModulePath)121 traverseModule(subModulePath, callback)122 },123 CallExpression (path) {124 if (path.get('callee').toString() === 'require') {125 const subModulePath = moduleResolve(currentModulePath,126 path.get('arguments.0').toString().replace(/['"]/g, ''))127 if (!subModulePath) return128 callback && callback(subModulePath)129 // éå½å¯»æ¾ä¾èµ130 traverseModule(subModulePath, callback)131 }132 }133 })134}135// é对ä¸åç css æ件, 使ç¨ä¸åçæ件å¤ç136function resolvePostcssSyntaxPlugin (modulePath) {137 if (modulePath.endsWith('.scss')) {138 return postcssScss139 }140 if (modulePath.endsWith('.less')) {141 return postcssLess142 }143}144function traverseCssModule (currentModulePath, callback) {145 const moduleFileContent = fs.readFileSync(currentModulePath,146 { encoding: 'utf-8' })147 // ä½¿ç¨ postcss å¯¹ä¼ å
¥ç css è¿è¡è½¬æ¢148 const ast = postcss.parse(moduleFileContent, {149 syntax: resolvePostcssSyntaxPlugin(currentModulePath)150 })151 // å¤ç import æ
åµ152 ast.walkAtRules('import', rule => {153 const subModulePath = moduleResolve(currentModulePath,154 rule.params.replace(/['"]/g, ''))155 if (!subModulePath) return156 callback && callback(subModulePath)157 traverseModule(subModulePath, callback)158 })159 // å¤ç url æ
åµ160 ast.walkDecls(decl => {161 if (decl.value.includes('url(')) {162 const temp = /.*url\((.+)\).*/.exec(decl.value)163 let url = ''164 if (temp[1]) {165 url = temp[1].replace(/['"]/g, '')166 } else {167 throw new Error('ä¼ å
¥ç url 为空')168 }169 const subModulePath = moduleResolve(currentModulePath, url)170 if (!subModulePath) return171 callback && callback(subModulePath)172 }173 })174}175function traverseModule (currentModulePath, callback) {176 currentModulePath = completeModulePath(currentModulePath)177 const moduleType = getModuleType(currentModulePath)178 if (moduleType & MODULE_TYPES.JS) {179 // é对 JS æ件, è¿è¡è§£æ (require / import)180 traverseJsModule(currentModulePath, callback)181 } else if (moduleType & MODULE_TYPES.CSS) {182 // é对 CSS æ件, è¿è¡è§£æ (import / url)183 traverseCssModule(currentModulePath, callback)184 }185}...
Blamer.js
Source:Blamer.js
1'use babel';2import { isFunction, each } from 'lodash';3import GitCommander from './GitCommander';4export default class Blamer {5 constructor(repo) {6 if (!repo) {7 throw new Error('Cannot create a Blamer without a repository.');8 }9 this.repo = repo;10 this.initialize();11 }12 /**13 * Initializes this Blamer instance, by creating git-tools repos for the root14 * repository and submodules.15 */16 initialize() {17 this.tools = {};18 this.tools.root = new GitCommander(this.repo.getWorkingDirectory());19 const submodules = this.repo.submodules;20 if (submodules) {21 each(submodules, (submodule, submodulePath) => {22 this.tools[submodulePath] = new GitCommander(`${this.repo.getWorkingDirectory()}/${submodulePath}`);23 });24 }25 }26 /**27 * Blames the given filePath and calls callback with blame lines or error.28 *29 * @param {string} filePath - filePath to blame30 * @param {function} callback - callback to call back with blame data31 */32 blame(filePath, callback) {33 // Ensure file path is relative to root repo34 let cleanedFilePath = this.repo.relativize(filePath);35 const repoUtil = this.repoUtilForPath(cleanedFilePath);36 // Ensure that if this file is in a submodule, we remove the submodule dir37 // from the path38 cleanedFilePath = this.removeSubmodulePrefix(cleanedFilePath);39 if (!isFunction(callback)) {40 throw new Error('Must be called with a callback function');41 }42 // Make the async blame call on the git repo43 repoUtil.blame(cleanedFilePath, function (err, blame) {44 callback(err, blame);45 });46 }47 /**48 * Utility to get the GitCommander repository for the given filePath. Takes into49 * account whether the file is part of a submodule and returns that repository50 * if necessary.51 *52 * @param {string} filePath - the path to the file in question.53 */54 repoUtilForPath(filePath) {55 const submodules = this.repo.submodules;56 // By default, we return the root GitCommander repository.57 let repoUtil = this.tools.root;58 // if we have submodules, loop through them and see if the given file path59 // belongs inside one of the repositories. If so, we return the GitCommander repo60 // for that submodule.61 if (submodules) {62 each(submodules, (submodule, submodulePath) => {63 const submoduleRegex = new RegExp(`^${submodulePath}`);64 if (submoduleRegex.test(filePath)) {65 repoUtil = this.tools[submodulePath];66 }67 });68 }69 return repoUtil;70 }71 /**72 * If the file path given is inside a submodule, removes the submodule73 * directory prefix.74 *75 * @param {string} filePath - path to file to relativize76 * @param {Repo} toolsRepo - git-tools Repo77 */78 removeSubmodulePrefix(filePath) {79 let trimmedFilePath = filePath;80 const submodules = this.repo.submodules;81 if (submodules) {82 each(submodules, (submodule, submodulePath) => {83 const submoduleRegex = new RegExp(`^${submodulePath}`);84 if (submoduleRegex.test(trimmedFilePath)) {85 trimmedFilePath = filePath.replace(submoduleRegex, '');86 }87 });88 }89 // remove leading '/' if there is one before returning90 return trimmedFilePath.replace(/^\//, '');91 }...
applySubmoduleFix.ts
Source:applySubmoduleFix.ts
1import { execCmd } from "./utils/execCmd";2import { resolve } from "path";3import { readFileSync, writeFileSync } from "fs";4import assert = require("assert");5import { projectName } from "./utils/projectName";6export { applySubmoduleFix };7let debug = false;8async function applySubmoduleFix() {9 if (isWindows()) {10 return;11 }12 const { submodulePath, submodulePathRelative } = getSubmodulePath();13 let isAlreadyInitialized;14 try {15 isAlreadyInitialized = await apply(submodulePath);16 } catch (err) {17 debug = true;18 await apply(submodulePath);19 return;20 }21 const already = !isAlreadyInitialized ? "" : "already ";22 console.log(23 `[${projectName}] submodule ${submodulePathRelative} ${already}initialized`24 );25}26async function apply(submodulePath: string): Promise<boolean> {27 const isAlreadyInitialized = await useSSHRemoteURL(submodulePath);28 await setGitHead(submodulePath);29 return isAlreadyInitialized;30}31async function setGitHead(submodulePath: string) {32 const cwd = submodulePath;33 const { stdout: revisionHash } = await execCmd("git rev-parse HEAD", {34 cwd,35 log: debug,36 });37 await execCmd("git checkout master", { cwd, log: debug });38 await execCmd(`git reset --hard ${revisionHash}`, { cwd, log: debug });39}40async function useSSHRemoteURL(submodulePath: string): Promise<boolean> {41 const before = "https://github.com/";42 const after = "git@github.com:";43 const gitConfigPath = getGitConfigPath(submodulePath);44 if (debug) {45 console.log(`[${projectName}] Git remote URLs updated (${gitConfigPath})`);46 }47 let gitConfigContent = readFileSync(gitConfigPath).toString();48 if (!gitConfigContent.includes(before)) {49 return true;50 }51 gitConfigContent = gitConfigContent.split(before).join(after);52 writeFileSync(gitConfigPath, gitConfigContent, "utf8");53 return false;54}55function getGitConfigPath(submodulePath: string): string {56 let pointer = readFileSync(resolve(submodulePath, "./.git"))57 .toString()58 .trim();59 assert(pointer.split("\n").length === 1);60 const prefix = "gitdir: ";61 assert(pointer.startsWith(prefix));62 pointer = pointer.slice(prefix.length);63 return resolve(submodulePath, pointer, "./config");64}65function isWindows() {66 return process.platform === "win32";67}68function getSubmodulePath() {69 const submodulePathRelative = getArg();70 const submodulePath = resolve(process.cwd(), submodulePathRelative);71 return { submodulePath, submodulePathRelative };72}73function getArg(): string {74 const args = process.argv;75 assert(args.length === 3);76 return args[2];...
Using AI Code Generation
1import { submodulePath } from 'ts-auto-mock';2import { submodulePath } from 'ts-auto-mock';3import { submodulePath } from 'ts-auto-mock';4import { submodulePath } from 'ts-auto-mock';5import { submodulePath } from 'ts-auto-mock';6import { submodulePath } from 'ts-auto-mock';7import { submodulePath } from 'ts-auto-mock';8import { submodulePath } from 'ts-auto-mock';9import { submodulePath } from 'ts-auto-mock';10import { submodulePath } from 'ts-auto-mock';11import { submodulePath } from 'ts-auto-mock';12import { submodulePath } from 'ts-auto-mock';13import { submodulePath } from 'ts-auto-mock';14import { submodulePath } from 'ts-auto-mock';15import { submodulePath } from 'ts-auto-mock';16import { submodulePath } from 'ts-auto-mock';
Using AI Code Generation
1import { submodulePath } from 'ts-auto-mock';2const path = submodulePath('test2');3import { submodulePath } from 'ts-auto-mock';4const path = submodulePath('test3');5import { submodulePath } from 'ts-auto-mock';6const path = submodulePath('test4');7import { submodulePath } from 'ts-auto-mock';8const path = submodulePath('test5');9import { submodulePath } from 'ts-auto-mock';10const path = submodulePath('test6');11import { submodulePath } from 'ts-auto-mock';12const path = submodulePath('test7');13import { submodulePath } from 'ts-auto-mock';14const path = submodulePath('test8');15import { submodulePath } from 'ts-auto-mock';16const path = submodulePath('test9');17import { submodulePath } from 'ts-auto-mock';18const path = submodulePath('test10');19import { submodulePath } from 'ts-auto-mock';20const path = submodulePath('test11');21import { submodulePath } from 'ts-auto-mock';22const path = submodulePath('test12');23import { submodulePath } from 'ts-auto-mock';24const path = submodulePath('test13');25import { submodulePath } from
Using AI Code Generation
1import { submodulePath } from 'ts-auto-mock';2import { Submodule } from './submodule';3export interface Test1 {4 submodule: Submodule;5}6import { submodulePath } from 'ts-auto-mock';7import { Submodule } from './submodule';8export interface Test2 {9 submodule: Submodule;10}11import { submodulePath } from 'ts-auto-mock';12import { Test1 } from './test1';13describe('test1', () => {14 it('should contain the submodule', () => {15 const test1: Test1 = {16 submodule: submodulePath('submodule'),17 };18 expect(test1).toMatchSnapshot();19 });20});21import { submodulePath } from 'ts-auto-mock';22import { Test2 } from './test2';23describe('test2', () => {24 it('should contain the submodule', () => {25 const test2: Test2 = {26 submodule: submodulePath('submodule'),27 };28 expect(test2).toMatchSnapshot();29 });30});31import { createMock } from 'ts-auto-mock';32it('should match the type of the given object', () => {33 const a = createMock({ a: 1, b: '2' });34 expect(a).toMatchTypeOf({ a: 1, b: '2' });35});36import { createMock } from 'ts-auto-mock';37it('should have the same properties as the given object', () => {38 const a = createMock({ a: 1, b: '2' });39 expect(a).toHaveProperties(['a', 'b']);40});
Using AI Code Generation
1import { submodulePath } from 'ts-auto-mock';2const path = submodulePath('test', 'submodule');3import { submodulePath } from 'ts-auto-mock';4const path = submodulePath('test', 'submodule', 'file.ts');5import { submodulePath } from 'ts-auto-mock';6const path = submodulePath('test', 'submodule', 'file.ts', 'subsubmodule');7import { submodulePath } from 'ts-auto-mock';8const path = submodulePath('test', 'submodule', 'file.ts', 'subsubmodule', 'file2.ts');9import { submodulePath } from 'ts-auto-mock';10const path = submodulePath('test', 'submodule', 'file.ts', 'subsubmodule', 'file2.ts', 'subsubsubmodule');11import { submodulePath } from 'ts-auto-mock';12const path = submodulePath('test', 'submodule', 'file.ts', 'subsubmodule', 'file2.ts', 'subsubsubmodule', 'file3.ts');13You can use submodulePath in your project by importing it from ts-auto-mock14import { submodulePath } from 'ts-auto-mock';15You can use submodulePath in your project by importing it from ts-auto-mock16import { submodulePath } from 'ts-auto-mock/dist
Using AI Code Generation
1import { submodulePath } from 'ts-auto-mock/extension';2import { Submodule } from './submodule';3export class Test1 {4 submodule: Submodule;5}6import { submodulePath } from 'ts-auto-mock/extension';7import { Submodule } from './submodule';8export class Test2 {9 submodule: Submodule;10}11import { submodulePath } from 'ts-auto-mock/extension';12export class Submodule {13 submodule: Submodule;14}15import { submodulePath } from 'ts-auto-mock/extension';16import { Test1 } from './test1';17import { Test2 } from './test2';18describe('test', () => {19 it('test', () => {20 const test1 = new Test1();21 const test2 = new Test2();22 console.log(submodulePath(test1, test2));23 });24});
Using AI Code Generation
1import { submodulePath } from 'ts-auto-mock';2const path = submodulePath('test1.js');3{4 "transformIgnorePatterns": ["node_modules/(?!ts-auto-mock)"]5}6{7 "compilerOptions": {8 "paths": {9 }10 }11}12{13 typescript({14 tsconfigDefaults: {15 compilerOptions: {16 paths: {17 },18 },19 },20 }),21}22{23 resolve: {24 alias: {25 },26 },27}28{29 rollup(config) {30 config.resolve.alias = {31 };32 return config;33 },34}35{36 resolver: {37 extraNodeModules: {38 'ts-auto-mock': path.resolve(__dirname, 'node_modules/ts-auto-mock/dist'),39 },40 },41}42{43 "compilerOptions": {44 "paths": {45 }46 }47}
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!!