Best JavaScript code snippet using ts-auto-mock
Condition.js
Source:Condition.js
1import PropTypes from 'prop-types';2import React from 'react';3import { types } from 'recast';4import Impact, { ErrorCatcher } from './Impact';5import { methodDescriptor, extractMethod } from './method';6import { methodDescriptor as globalMethodDescriptor } from './globalMethod';7import ConditionOperator from './ConditionOperator';8import { renderForm, valueToAST, getReadOnlySchema } from './args';9import { containerStyle } from '../Views/conditionImpactStyle';10const b = types.builders;11const nT = types.namedTypes;12/**13 * return a default value for the given type14 * @param {string} type the type for which a default value is required15 * @returns {string|undefined|boolean} the default value16 */17function defaultValue(type) {18 switch (type) {19 case 'string':20 return '';21 case 'number':22 return undefined;23 case 'boolean':24 return true;25 default:26 throw new Error(27 `Default value for 'returns' property '${type}' is not implemented`28 );29 }30}31/**32 * Find method's schema. Delegate to different method if it's a global method or a variable method.33 * @param {Object} node ast left node34 * @returns {Object} schema for given ast node35 */36function getMethodDescriptor(node) {37 const { global, method, variable, member } = extractMethod(38 nT.CallExpression.check(node) ? node : node.left39 );40 return global41 ? globalMethodDescriptor(member, method)42 : methodDescriptor(variable, method);43}44function isBoolCallFn(node) {45 const descr = getMethodDescriptor(node);46 return nT.CallExpression.check(node) && descr && descr.returns === 'boolean';47}48class Condition extends React.Component {49 constructor(props) {50 super(props);51 const { node } = props;52 const descr = getMethodDescriptor(node);53 if (nT.CallExpression.check(node)) {54 if (isBoolCallFn(node)) {55 this.state = { node: { left: node } };56 } else {57 this.state = { node: { left: node, operator: '===' } };58 }59 } else {60 this.state = {61 node: {62 left: node.left,63 right: node.right,64 operator: node.operator || '===',65 },66 };67 }68 this.returns = descr && descr.returns; // store current method's returns69 this.sendUpdate = this.sendUpdate.bind(this);70 }71 componentWillReceiveProps(nextProps) {72 const { node } = nextProps;73 const descr = getMethodDescriptor(node);74 if (nT.CallExpression.check(node)) {75 if (isBoolCallFn(node)) {76 this.setState({ node: { left: node } });77 } else {78 this.setState({ node: { left: node, operator: '===' } });79 }80 } else {81 this.setState({82 node: {83 left: node.left,84 right: node.right,85 operator: node.operator || '===',86 },87 });88 }89 this.returns = descr && descr.returns;90 }91 sendUpdate() {92 const { node } = this.state;93 const descr = getMethodDescriptor(node);94 if (!descr && node.left) {95 this.props.onChange(node.left);96 } else if (97 descr &&98 descr.returns === 'boolean' &&99 (node.right === undefined ||100 (node.right &&101 node.right.value === true &&102 node.operator === '==='))103 ) {104 this.props.onChange(node.left);105 } else if (node.operator && node.left) {106 const n = b.binaryExpression(107 node.operator,108 node.left,109 node.right ||110 valueToAST(defaultValue(descr.returns), {111 type: descr.returns,112 })113 );114 this.props.onChange(n);115 }116 }117 check() {118 const { node } = this.state;119 const descr = getMethodDescriptor(node);120 if (!descr) {121 this.setState(({ node: n }) => ({122 node: { ...n, right: undefined },123 }));124 } else if (this.returns !== descr.returns) {125 this.setState(126 ({ node: n }) => ({127 node: {128 ...n,129 operator: '===',130 right: valueToAST(defaultValue(descr.returns), {131 type: descr.returns,132 }),133 },134 }),135 this.sendUpdate136 );137 this.returns = descr.returns;138 } else {139 this.sendUpdate();140 }141 }142 render() {143 const { node } = this.state;144 const descr = getMethodDescriptor(node);145 let container;146 if (descr && typeof descr.returns !== 'string') {147 const { method } = extractMethod(148 nT.CallExpression.check(node) ? node : node.left149 );150 throw Error(151 `Method '${method}' is not comparable. Missing 'returns' description`152 );153 }154 if (node.right) {155 if (!descr) {156 const { method } = extractMethod(157 nT.CallExpression.check(node) ? node : node.left158 );159 throw Error(`Method '${method}' not found`);160 }161 const schema = {162 type: descr.returns,163 value: defaultValue(descr.returns),164 required: true,165 view: {166 layout: 'extraShortInline',167 },168 };169 let argsForm = renderForm(170 node.right,171 schema,172 v =>173 this.setState(174 ({ node: n }) => ({ node: { ...n, right: v } }),175 this.check176 ),177 undefined,178 'right'179 );180 if (this.props.view.readOnly) {181 argsForm = getReadOnlySchema(argsForm);182 }183 container = [184 <div key="operator" className={containerStyle}>185 <ConditionOperator186 operator={node.operator}187 onChange={v =>188 this.setState(189 ({ node: n }) => ({190 node: { ...n, operator: v },191 }),192 this.check193 )194 }195 type={descr.returns}196 readOnly={this.props.view.readOnly}197 />198 </div>,199 argsForm,200 ];201 }202 const isBoolCall =203 nT.CallExpression.check(node) && descr.returns === 'boolean';204 return (205 <div>206 <Impact207 {...this.props}208 node={isBoolCall ? node : node.left}209 onChange={v => {210 if (nT.CallExpression.check(v)) {211 this.setState(({ node: n }) => {212 const des = getMethodDescriptor(v);213 if (des && des.returns === 'boolean') {214 return { node: { left: v } };215 }216 return { node: { ...n, left: v } };217 }, this.check);218 } else if (nT.ExpressionStatement.check(v)) {219 this.props.onChange(v.expression);220 } else {221 this.props.onChange(v);222 }223 }}224 />225 {container}226 </div>227 );228 }229}230Condition.propTypes = {231 onChange: PropTypes.func.isRequired,232 node: PropTypes.object.isRequired,233};234export default function SecuredCondition(props) {235 return (236 <ErrorCatcher237 node={props.node}238 onChange={v => props.onChange(v.expression)}239 >240 <Condition {...props} />241 </ErrorCatcher>242 );243}244SecuredCondition.propTypes = {245 node: PropTypes.object,246 onChange: PropTypes.func.isRequired,...
FieldTest.ts
Source:FieldTest.ts
1/*2*3*/4// @ts-ignore5import {System} from "lib-utils-ts/src/lang/System";6import {Method} from "lib-utils-ts/src/Reflect/Method";7import {Field} from "lib-utils-ts/src/Reflect/Field";8import {Predication} from "lib-utils-ts/src/Predication";9import {Class} from "lib-utils-ts/src/Class";10export class FieldTest{11 public static readonly staticOneAR:String = "";12 public static staticOneA:FieldTest = new FieldTest();13 public static staticOneAa:Method = FieldTest.class().getMethod("staticOne", Method.STATIC);14 public static staticOneAp:Predication<string> = Predication.of(()=>void 0);15 public readonly instancedOneAR:String = "stringTest";16 public instancedOneA:string = null;17 public static Main(args:string[]):void{18 let fieldI:FieldTest = new FieldTest();19 System.out.println(fieldI.getClass().toString());20 System.out.println(FieldTest.class().toString());21 System.out.println(22 FieldTest23 .class()24 .getMethod("instancedOne")25 .toString()26 );27 System.out.println(28 fieldI.getClass()29 .getMethod("instancedOne")30 .toString()31 );32 System.out.println(33 FieldTest34 .class()35 .getMethod("instancedOne")36 .getMethodDescriptor()37 .toString()+"--" );38 System.out.println(39 FieldTest40 .class()41 .getMethod("instancedOne")42 .getMethodDescriptor()43 .isWritable() );44 System.out.println(45 fieldI.getClass()46 .getMethod("instancedOne")47 .getMethodDescriptor()48 .toString()49 );50 System.out.println(51 FieldTest52 .class()53 .getMethod("staticOne", Method.STATIC)54 .toString()55 );56 System.out.println(57 fieldI.getClass()58 .getMethod("staticOne", Method.STATIC)59 .toString()60 );61 System.out.println(62 FieldTest63 .class()64 .getMethod("staticOne", Method.STATIC)65 .getMethodDescriptor()66 .toString()67 );68 System.out.println(69 fieldI.getClass()70 .getMethod("staticOne", Method.STATIC)71 .getMethodDescriptor()72 .toString()73 );74 System.out.println("===============================" );75 System.out.println(76 fieldI77 .getClass()78 .getField("staticOneAp", Field.STATIC)79 );80 System.out.println(81 fieldI82 .getClass()83 .getField("staticOneAa", Field.STATIC)84 );85 System.out.println(86 fieldI87 .getClass()88 .getField("staticOneA", Field.STATIC)89 );90 System.out.println(91 fieldI92 .getClass()93 .getField("staticOneA", Field.STATIC)94 .getFieldDescriptor()95 .toString()96 );97 System.out.println("*************************************************" );98 FieldTest.class()99 .getField("staticOneA", Field.STATIC)100 .getFieldDescriptor()101 .final()102 .set();103 System.out.println(104 FieldTest.class()105 .getField("staticOneA", Field.STATIC)106 .getFieldDescriptor()107 .toString()108 );109 System.out.println(110 fieldI111 .getClass()112 .getField("staticOneAR", Field.STATIC)113 );114 System.out.println(115 fieldI116 .getClass()117 .getField("staticOneAR", Field.STATIC)118 .getFieldDescriptor()119 .toString()120 );121 System.out.println(122 FieldTest.class()123 .getField("staticOneA", Field.STATIC)124 );125 System.out.println(126 FieldTest.class()127 .getField("staticOneA", Field.STATIC)128 .getFieldDescriptor()129 .toString()130 );131 System.out.println(132 FieldTest.class()133 .getField("staticOneAR", Field.STATIC)134 );135 System.out.println(136 FieldTest.class()137 .getField("staticOneAR", Field.STATIC)138 .getFieldDescriptor()139 .toString()140 );141 System.out.println(142 fieldI.getClass()143 .getField("instancedOneAR", Field.INSTANCED)144 );145 System.out.println(146 fieldI.getClass()147 .getField("instancedOneAR", Field.INSTANCED)148 .getFieldDescriptor()149 .toString()150 );151 System.out.println(152 "********"+ FieldTest.class()153 .getField("instancedOneAR", Field.INSTANCED)154 );155 System.out.println(156 fieldI.getClass()157 .getField("instancedOneA", Field.INSTANCED)158 );159 System.out.println(160 fieldI.getClass()161 .getField("instancedOneA", Field.INSTANCED)162 .getFieldDescriptor()163 .toString()164 );165 System.out.println(166 FieldTest.class()167 .getField("instancedOneA", Field.INSTANCED)168 );169 // console.log(FieldTest.constructor.prototype["instancedOneA"]);170 }171 public instancedOne():void{}172 public static staticOne():void{}173}...
index.js
Source:index.js
1import getMethodDescriptor from './helpers/getMethodDescriptor'2import logInvocation from './loggers/invocation'3import logResult from './loggers/result'4import logError from './loggers/error'5/**6 * Class methods invocation logging decorator outer7 *8 * @param {Object|Function} [param={}]9 *10 * @returns {Function}11 */12export default function cmildOuter (param = {}) {13 /**14 * Class methods invocation logging decorator inner15 *16 * @param {Object} [options.styles={}]17 * @param {String} [options.enabled=true]18 * @param {Object} [options.styles.browser={}]19 * @param {String} [options.styles.browser.invocation='background: #F2EAFF; color: #03A9F4; font-weight: bold']20 * @param {String} [options.styles.browser.result='background: #F2EAFF; color: #4CAF50; font-weight: bold']21 * @param {String} [options.styles.browser.error='background: #F2EAFF; color: #F20404; font-weight: bold']22 * @param {Object} [options.styles.node={}]23 * @param {String} [options.styles.node.invocation='bgBlack.blue.bold']24 * @param {String} [options.styles.node.result='bgBlack.green.bold']25 * @param {String} [options.styles.node.error='bgBlack.red.bold']26 * @param {Function} target27 */28 function cmildInner ({29 enabled = true,30 styles = {31 browser: {32 invocation: 'background: #F2EAFF; color: #03A9F4; font-weight: bold',33 result: 'background: #F2EAFF; color: #4CAF50; font-weight: bold',34 error: 'background: #F2EAFF; color: #F20404; font-weight: bold',35 },36 node: {37 invocation: 'bgBlack.blue.bold',38 result: 'bgBlack.green.bold',39 error: 'bgBlack.red.bold',40 },41 },42 } = {}, target) {43 if (typeof target !== 'function') {44 throw TypeError('`target` decorator param should be a class function!')45 }46 if (! enabled) {47 return48 }49 for (const propertyName of Reflect.ownKeys(target.prototype)) {50 const propertyValue = target.prototype[propertyName]51 const isMethod = propertyValue instanceof Function52 if (! isMethod) {53 // eslint-disable-next-line no-continue54 continue55 }56 const descriptor = getMethodDescriptor(target, propertyName)57 const originalMethod = descriptor.value58 descriptor.value = function decorate (...args) {59 const classMethod = `${target.name}#${originalMethod.name}`60 const logI = logInvocation.bind(null, classMethod, styles[process.browser ? 'browser' : 'node'].invocation)61 const logR = logResult.bind(null, classMethod, styles[process.browser ? 'browser' : 'node'].result)62 const logE = logError.bind(null, classMethod, styles[process.browser ? 'browser' : 'node'].error)63 logI(...args)64 let result65 try {66 result = Reflect.apply(originalMethod, this, args)67 const isPromise = (68 result instanceof Promise ||69 Promise.resolve(result) === result ||70 (71 typeof result === 'object' &&72 result.constructor &&73 result.constructor.name === 'Promise'74 )75 )76 if (isPromise) {77 result.then(logR).catch(logE)78 } else {79 logR(result)80 }81 } catch (error) {82 logE(error)83 throw error84 }85 return result86 }87 Reflect.defineProperty(target.prototype, propertyName, descriptor)88 }89 }90 if (typeof param === 'function') {91 return cmildInner({}, param)92 }93 return cmildInner.bind(cmildInner, param)...
Using AI Code Generation
1import {GetMethodDescriptor} from 'ts-auto-mock';2import {TestClass} from './test2';3GetMethodDescriptor(TestClass, 'testMethod');4import {GetMethodDescriptor} from 'ts-auto-mock';5export class TestClass {6 public testMethod(): string {7 return 'string';8 }9}10import {TestClass} from './test2';11import {GetMethodDescriptor} from 'ts-auto-mock';12GetMethodDescriptor(TestClass, 'testMethod');
Using AI Code Generation
1const descriptor = GetMethodDescriptor(MyClass, 'myMethod');2const descriptor = GetMethodDescriptor(MyClass.prototype, 'myMethod');3const descriptor = GetMethodDescriptor(MyClass.prototype, 'myMethod');4const descriptor = GetMethodDescriptor(MyClass.prototype, 'myMethod');5const descriptor = GetMethodDescriptor(MyClass.prototype, 'myMethod');6const descriptor = GetMethodDescriptor(MyClass.prototype, 'myMethod');7const descriptor = GetMethodDescriptor(MyClass.prototype, 'myMethod');8const descriptor = GetMethodDescriptor(MyClass.prototype, 'myMethod');9const descriptor = GetMethodDescriptor(MyClass.prototype, 'myMethod');10const descriptor = GetMethodDescriptor(MyClass.prototype, 'myMethod');11const descriptor = GetMethodDescriptor(MyClass.prototype, 'myMethod');12const descriptor = GetMethodDescriptor(MyClass.prototype, 'myMethod');13const descriptor = GetMethodDescriptor(MyClass.prototype, 'myMethod');14const descriptor = GetMethodDescriptor(MyClass.prototype, 'myMethod');15const descriptor = GetMethodDescriptor(MyClass.prototype, 'myMethod');
Using AI Code Generation
1import {GetMethodDescriptor} from 'ts-auto-mock';2const descriptor = GetMethodDescriptor('test1.ts', 'class1', 'method1');3console.log(descriptor);4import {GetMethodDescriptor} from 'ts-auto-mock';5const descriptor = GetMethodDescriptor('test2.ts', 'class2', 'method2');6console.log(descriptor);7{ type: 'method',8 parameters: [ { name: 'param1', type: 'string' } ] }9{ type: 'method',10 parameters: [ { name: 'param1', type: 'string' } ] }11{ type: 'method',12 parameters: [ { name: 'param1', type: 'string' } ] }
Using AI Code Generation
1const {GetMethodDescriptor} = require('ts-auto-mock');2const descriptor = GetMethodDescriptor('path/to/file.ts', 'ClassName', 'methodName');3console.log(descriptor);4const {GetMethodDescriptor} = require('ts-auto-mock');5const descriptor = GetMethodDescriptor('path/to/file.ts', 'ClassName', 'methodName', 'methodName2');6console.log(descriptor);7{8 name: string;9 parameters: {10 name: string;11 type: string;12 isOptional: boolean;13 }[];14 returnType: string;15}16{17 name: string;18 values: {19 name: string;20 value: string;21 }[];22}
Using AI Code Generation
1import {GetMethodDescriptor} from 'ts-auto-mock';2import {MyClass} from './myClass';3const methodDescriptor = GetMethodDescriptor(MyClass, 'myMethod');4{5 {6 },7 {8 }9}10import {GetMethodDescriptor} from 'ts-auto-mock';11import {MyClass} from './myClass';12const methodDescriptor = GetMethodDescriptor(MyClass, 'myMethod');13{14 {15 },16 {17 }18}19export class MyClass {20 myMethod(param1: string, param2: number): string {21 return '';22 }23}24To use ts-auto-mock, you need to import the library in your test file:25import {mock} from 'ts-auto-mock';26import {mock} from 'ts-auto
Using AI Code Generation
1import {getMock} from 'ts-auto-mock';2import {MyClass} from './MyClass';3const mock: MyClass = getMock<MyClass>();4console.log(mock.getMyMethod());5export class MyClass {6 getMyMethod(): string {7 return 'Hello World';8 }9}
Using AI Code Generation
1import { GetMethodDescriptor } from 'ts-auto-mock';2const methodDescriptor = GetMethodDescriptor(3);4console.log(methodDescriptor);5import { GetMethodDescriptor } from 'ts-auto-mock';6const methodDescriptor = GetMethodDescriptor(7);8console.log(methodDescriptor);9import { GetMethodDescriptor } from 'ts-auto-mock';10const methodDescriptor = GetMethodDescriptor(11);12console.log(methodDescriptor);13import { GetMethodDescriptor } from 'ts-auto-mock';14const methodDescriptor = GetMethodDescriptor(15);16console.log(methodDescriptor);17import { GetMethodDescriptor } from 'ts-auto-mock';18const methodDescriptor = GetMethodDescriptor(19);20console.log(methodDescriptor);21import { GetMethodDescriptor } from 'ts-auto-mock';22const methodDescriptor = GetMethodDescriptor(23);24console.log(methodDescriptor);25import { GetMethodDescriptor } from 'ts-auto-mock';26const methodDescriptor = GetMethodDescriptor(27);28console.log(methodDescriptor);
Using AI Code Generation
1import {GetMethodDescriptor} from 'ts-auto-mock';2const descriptor = GetMethodDescriptor();3import {GetPropertyDescriptor} from 'ts-auto-mock';4const descriptor = GetPropertyDescriptor();5import {GetAccessorDescriptor} from 'ts-auto-mock';6const descriptor = GetAccessorDescriptor();7import {GetParameterDescriptor} from 'ts-auto-mock';8const descriptor = GetParameterDescriptor();9import {GetCallDescriptor} from 'ts-auto-mock';10const descriptor = GetCallDescriptor();11import {GetConstructorDescriptor} from 'ts-auto-mock';12const descriptor = GetConstructorDescriptor();13import {GetClassDescriptor} from 'ts-auto-mock';14const descriptor = GetClassDescriptor();15import {GetInterfaceDescriptor} from 'ts-auto-mock';16const descriptor = GetInterfaceDescriptor();17import {GetEnumDescriptor} from 'ts-auto-mock';18const descriptor = GetEnumDescriptor();
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!!