Best JavaScript code snippet using apimocker
index copy.ts
Source:index copy.ts
1import axios from 'axios'2import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'3import { ElLoading } from 'element-plus'4/**5 * 2.对å®ä¾å¯¹è±¡ä¸configå±æ§çæ©å±ï¼å¢å äºä¸ä¸ª STInterceptors ç±»å6 */7// <T = AxiosResponse> æ³åé»è®¤å¼ä¸º AxiosResponse8interface STInterceptors<T = AxiosResponse> {9 requestInterceptor?: (config: AxiosRequestConfig) => AxiosRequestConfig10 requestInterceptorCatch?: (err: any) => any11 responseInterceptor?: (res: T) => T12 responseInterceptorCatch?: (err: any) => any13}14// 3.æ©å±åå
çconfig对象å¯ä»¥æ·»å interceptorï¼isShow å±æ§15interface STRequestConfig<T = AxiosResponse> extends AxiosRequestConfig {16 // interceptorsåæ°å¯ä»¥ä¸ä¼ 17 stInterceptors?: STInterceptors<T>18 isShow?: boolean19}20// 1.å°è£
èªå·±çAxiosç±»21class STAxios {22 instance: AxiosInstance23 stInterceptors?: STInterceptors24 // æ§å¶loadingçæ¾ç¤ºéè25 loading?: any26 isShow?: boolean27 constructor(config: STRequestConfig) {28 // å¦æéè¦å¯å®ç°å¤ä¸ªå®ä¾å¯¹è±¡29 this.instance = axios.create(config)30 this.stInterceptors = config.stInterceptors31 // config.isShow ?? true 空å¼å并è¿ç®ç¬¦ï¼ å¦æ config.isShow 为空设置é»è®¤å¼ä¸º true32 this.isShow = config.isShow ?? true33 // 4.1.ç»å½åå®ä¾æ·»å æææ¦æªå¨34 this.instance.interceptors.request.use(35 // ?.å¯éé¾ æ¦æªå¨åå¨ï¼æ§è¡åé¢çæ¹æ³36 this.stInterceptors?.requestInterceptor,37 this.stInterceptors?.requestInterceptorCatch38 )39 this.instance.interceptors.response.use(40 this.stInterceptors?.responseInterceptor,41 this.stInterceptors?.responseInterceptorCatch42 )43 // 4.2.ç»ææå®ä¾æ·»å æææ¦æªå¨44 this.instance.interceptors.request.use(45 (config) => {46 // 请æ±æ°æ®è¿ç¨ä¸æ¾ç¤º loading47 if (this.isShow) {48 this.loading = ElLoading.service({49 lock: true,50 text: 'Loading',51 background: 'rgba(0, 0, 0, 0.7)'52 })53 }54 // console.log('ææå®ä¾é½ææ¦æªå¨ï¼å¹¶ä¸è¯·æ±æ¦æªæå~')55 return config56 },57 (err) => {58 // console.log('ææå®ä¾é½ææ¦æªå¨ï¼å¹¶ä¸è¯·æ±æ¦æªå¤±è´¥~')59 return err60 }61 )62 this.instance.interceptors.response.use(63 (res) => {64 // 请æ±æåå
³é loading65 // ?. es11 å¯éé¾ï¼ å¦æåé¢æå¼ï¼æ§è¡åé¢æä½66 this.loading?.close()67 // console.log('ææå®ä¾é½ææ¦æªå¨ï¼å¹¶ä¸ååºæ¦æªæå~')68 // console.log('ç´æ¥è¿åææä¿¡æ¯data: ' + res.data)69 return res.data70 },71 (err) => {72 // if (err.data.status === '404') {73 // console.log('没æå½å页é¢~')74 // }75 // console.log('ææå®ä¾é½ææ¦æªå¨ï¼å¹¶ä¸ååºæ¦æªå¤±è´¥~')76 return err77 }78 )79 }80 request<T>(config: STRequestConfig<T>): Promise<T> {81 // request(config: STRequestConfig) {82 return new Promise((resolve, reject) => {83 // 4.3.1 对å个请æ±çæ¦æªå¤ç84 if (config.stInterceptors?.requestInterceptor) {85 // å°æ§è¡äºçrequestInterceptorçè¿åå¼èµå¼ç»config86 config = config.stInterceptors.requestInterceptor(config)87 }88 // 4.3 æ个å®ä¾çåç¬è¯·æ±æ¦æª89 this.instance90 // request<T = any, R = AxiosResponse<T>, D = any> é»è®¤ä¿®æ¹çæ¯ç¬¬äºä¸ªæ³å91 .request<any, T>(config)92 .then((res) => {93 // 4.3.2 对å个ååºçæ¦æªå¤ç94 if (config.stInterceptors?.responseInterceptor) {95 res = config.stInterceptors.responseInterceptor(res)96 }97 resolve(res)98 })99 .catch((err) => {100 reject(err)101 })102 })103 }104 // 5. å
¶ä»æ¹æ³å°è£
105 get<T>(config: STRequestConfig<T>): Promise<T> {106 return this.request<T>({ ...config, method: 'get' })107 }108 post<T>(config: any): Promise<T> {109 return this.request<T>({ ...config, method: 'post' })110 }111 delete<T>(config: STRequestConfig<T>): Promise<T> {112 return this.request<T>({ ...config, method: 'delete' })113 }114 patch<T>(config: STRequestConfig<T>): Promise<T> {115 return this.request<T>({ ...config, method: 'patch' })116 }117}...
index.ts
Source:index.ts
1import axios from 'axios'2import type { AxiosInstance } from 'axios'3import type { STRequestInterceptors, STRequestConfig } from './type'4import { ElLoading } from 'element-plus'5import { LoadingInstance } from 'element-plus/lib/components/loading/src/loading'6const DEAFULT_LOADING = true7class STRequest {8 instance: AxiosInstance9 interceptors?: STRequestInterceptors10 showLoading: boolean11 loading?: LoadingInstance12 constructor(config: STRequestConfig) {13 // å建axioså®ä¾14 this.instance = axios.create(config)15 // ä¿ååºæ¬ä¿¡æ¯16 this.showLoading = config.showLoading ?? DEAFULT_LOADING17 this.interceptors = config.interceptors18 // 使ç¨æ¦æªå¨19 // 1.ä»configä¸ååºçæ¦æªå¨æ¯å¯¹åºçå®ä¾çæ¦æªå¨20 this.instance.interceptors.request.use(21 this.interceptors?.requestInterceptor,22 this.interceptors?.requestInterceptorCatch23 )24 this.instance.interceptors.response.use(25 this.interceptors?.responseInterceptor,26 this.interceptors?.responseInterceptorCatch27 )28 // 2.æ·»å ææçå®ä¾é½æçæ¦æªå¨29 this.instance.interceptors.request.use(30 (config) => {31 if (this.showLoading) {32 this.loading = ElLoading.service({33 lock: true,34 text: 'æ£å¨è¯·æ±æ°æ®....',35 background: 'rgba(0, 0, 0, 0.5)'36 })37 }38 return config39 },40 (err) => {41 return err42 }43 )44 this.instance.interceptors.response.use(45 (res) => {46 // å°loading移é¤47 this.loading?.close()48 const data = res.data49 if (data.returnCode === '-1001') {50 console.log('请æ±å¤±è´¥~, é误信æ¯')51 } else {52 return data53 }54 },55 (err) => {56 // å°loading移é¤57 this.loading?.close()58 // ä¾å: å¤æä¸åçHttpErrorCodeæ¾ç¤ºä¸åçé误信æ¯59 if (err.response.status === 404) {60 console.log('404çé误~')61 }62 return err63 }64 )65 }66 request<T = any>(config: STRequestConfig<T>): Promise<T> {67 return new Promise((resolve, reject) => {68 // 1.å个请æ±å¯¹è¯·æ±configçå¤ç69 if (config.interceptors?.requestInterceptor) {70 config = config.interceptors.requestInterceptor(config)71 }72 // 2.å¤ææ¯å¦éè¦æ¾ç¤ºloading73 if (config.showLoading === false) {74 this.showLoading = config.showLoading75 }76 this.instance77 .request<any, T>(config)78 .then((res) => {79 // 1.å个请æ±å¯¹æ°æ®çå¤ç80 if (config.interceptors?.responseInterceptor) {81 res = config.interceptors.responseInterceptor(res)82 }83 // 2.å°showLoading设置true, è¿æ ·ä¸ä¼å½±åä¸ä¸ä¸ªè¯·æ±84 this.showLoading = DEAFULT_LOADING85 // 3.å°ç»æresolveè¿ååºå»86 resolve(res)87 })88 .catch((err) => {89 // å°showLoading设置true, è¿æ ·ä¸ä¼å½±åä¸ä¸ä¸ªè¯·æ±90 this.showLoading = DEAFULT_LOADING91 reject(err)92 return err93 })94 })95 }96 get<T = any>(config: STRequestConfig<T>): Promise<T> {97 return this.request<T>({ ...config, method: 'GET' })98 }99 post<T = any>(config: any): Promise<T> {100 return this.request<T>({ ...config, method: 'POST' })101 }102 delete<T = any>(config: STRequestConfig<T>): Promise<T> {103 return this.request<T>({ ...config, method: 'DELETE' })104 }105 patch<T = any>(config: any): Promise<T> {106 return this.request<T>({ ...config, method: 'PATCH' })107 }108}...
index.js
Source:index.js
1const API_ENDPOINT = 'http://stapi.co/api/v1/rest/';2const stRequest = new XMLHttpRequest();3let query = '';4let userInput = 'search';5let category = '';6//define const variables for DOM elements7const inputSelector = document.querySelector('#input');8const categorySelector = document.querySelector('#category');9const buttonSelector = document.querySelector('#button');10const buttonClearSelector = document.querySelector('#buttonClear');11const errorSelector = document.querySelector('#error');12const answerSelector = document.querySelector('#answer');13function showAnswer(response) {14 if (category === 'movie') category = 'movies';15 if (category === 'astronomicalObject') category = 'astronomicalObjects';16 if (category === 'character') category = 'characters';17 if (category === 'location') category = 'locations';18 if (category === 'movie') category = 'movies';19 if (category === 'season') category = 'seasons';20 if (category === 'spacecraft') category = 'spacecrafts';21 if (category === 'weapon') category = 'weapons';22 let myList = response[category];23 for (let i = 0; i < myList.length; i++) {24 let li = document.createElement('li');25 li.appendChild(26 category === 'movies' || category === 'seasons' || category === 'series'27 ? document.createTextNode(myList[i].title)28 : document.createTextNode(myList[i].name)29 );30 answerSelector.appendChild(li);31 }32 buttonSelector.setAttribute('disabled', 'disabled');33}34function showError(error) {35 errorSelector.innerHTML = error;36 errorSelector.style.visibility = 'visible';37 setTimeout(() => {38 errorSelector.style.visibility = 'hidden';39 }, 3000);40}41//Connect to API and get data42function getData() {43 query = API_ENDPOINT + category + '/' + userInput;44 stRequest.open('GET', query);45 stRequest.responseType = 'json';46 stRequest.onload = function () {47 showAnswer(stRequest.response);48 };49 stRequest.onerror = function () {50 showError('There was an error! Please select category.');51 };52 stRequest.send();53}54function clearData() {55 answerSelector.innerHTML = '';56 buttonSelector.removeAttribute('disabled');57}58//Begin search59category = categorySelector.addEventListener('click', e => (category = e.target.value));60//inputSelector.addEventListener('input', e => (userInput = e.target.value));61buttonSelector.addEventListener('click', getData);...
Using AI Code Generation
1var apimocker = require('apimocker');2var stRequest = apimocker.stRequest;3var stResponse = apimocker.stResponse;4var stMock = apimocker.stMock;5var stScenario = apimocker.stScenario;6var stConfig = apimocker.stConfig;7var stUtils = apimocker.stUtils;8var mock = stMock('test', stRequest('GET', '/test'), stResponse(200, 'OK'), stScenario('test', true), stConfig('test', true));9var utils = stUtils();10var config = stConfig('test', true);11var scenario = stScenario('test', true);12var request = stRequest('GET', '/test');13var response = stResponse(200, 'OK');14var mocker = apimocker();15mocker.addMock(mock);16mocker.addUtils(utils);17mocker.addConfig(config);18mocker.addScenario(scenario);19mocker.addRequest(request);20mocker.addResponse(response);21mocker.start();22mocker.stop();23mocker.set('test', 'test');24mocker.get('test');25mocker.use('test', 'test');26mocker.getMocks();27mocker.getUtils();28mocker.getConfig();29mocker.getScenarios();30mocker.getRequests();31mocker.getResponses();32mocker.getMock('test');33mocker.getUtil('test');34mocker.getConfig('test');35mocker.getScenario('test');36mocker.getRequest('test');37mocker.getResponse('test');38mocker.removeMock('test');39mocker.removeUtil('test');40mocker.removeConfig('test');41mocker.removeScenario('test');42mocker.removeRequest('test');43mocker.removeResponse('test');44mocker.removeMocks();
Using AI Code Generation
1var stRequest = require('apimocker').stRequest;2var stResponse = require('apimocker').stResponse;3var stMock = require('apimocker').stMock;4var stMocker = require('apimocker').stMocker;5var stMockerRegistry = require('apimocker').stMockerRegistry;6var stMockerConfig = require('apimocker').stMockerConfig;7var stMockerConfigBuilder = require('apimocker').stMockerConfigBuilder;8var stMockerConfigFileLoader = require('apimocker').stMockerConfigFileLoader;9var stMockerConfigFileWriter = require('apimocker').stMockerConfigFileWriter;10var stMockerConfigValidator = require('apimocker').stMockerConfigValidator;11var stMockerRequestHandler = require('apimocker').stMockerRequestHandler;12var stMockerResponseHandler = require('apimocker').stMockerResponseHandler;13var stMockerResponseWriter = require('apimocker').stMockerResponseWriter;14var stMockerServer = require('apimocker').stMockerServer;15var stMockerServerFactory = require('apimocker').stMockerServerFactory;16var stMockerServerStartupHandler = require('apimocker').stMockerServerStartupHandler;17var stMockerUtil = require('apimocker').stMockerUtil;18var stMockerValidator = require('apimocker').stMockerValidator;19var stMockerValidatorFactory = require('apimocker').stMockerValidatorFactory;20var stMockerValidatorRegistry = require('apimocker').stMockerValidatorRegistry;21var stMockerValidatorResult = require('apimocker').stMockerValidatorResult;22var stMockerValidatorResultFactory = require('apimocker').stMockerValidatorResultFactory;23var stMockerValidatorResultRegistry = require('apimocker').stMockerValidatorResultRegistry;24var stMockerValidatorResultWriter = require('apimocker').stMockerValidatorResultWriter;25var stMockerValidatorWriter = require('apimocker').stMockerValidatorWriter;26var stMockerWriterFactory = require('apimocker').stMockerWriterFactory;27var stMockerWriterRegistry = require('apimocker').stMockerWriterRegistry;
Using AI Code Generation
1var stRequest = require('apimocker').stRequest;2var http = require('http');3var options = {4};5var req = http.request(options, function(res) {6 console.log('STATUS: ' + res.statusCode);7 console.log('HEADERS: ' + JSON.stringify(res.headers));8 res.setEncoding('utf8');9 res.on('data', function (chunk) {10 console.log('BODY: ' + chunk);11 });12});13req.end();14{15 "request": {16 },17 "response": {18 }19}20[MIT](LICENSE)
Using AI Code Generation
1var stRequest = require('apimocker').stRequest;2var stResponse = require('apimocker').stResponse;3var stMock = require('apimocker').stMock;4var mock = stMock('mock1', stRequest('/test'), stResponse(200, 'Hello World!'));5module.exports = mock;6Default: `process.cwd()`7Default: `process.cwd()`8Default: `{}`
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!!