How to use getCacheKeyFromConfig method in Jest

Best JavaScript code snippet using jest

fluro.api.js

Source:fluro.api.js Github

copy

Full Screen

...63 useCache = config.cache || defaultCache;64 //If there is a cache65 if (useCache) {66 //Generate the cache key from the request67 var cacheKey = getCacheKeyFromConfig(config);68 //If we have the cachedResponse version69 cachedResponse = useCache.get(cacheKey);70 }71 }72 ///////////////////////////////////////73 ///////////////////////////////////////74 if (cachedResponse) {75 // console.log('FROM CACHE', config.url, cachedResponse);76 return resolve(cachedResponse);77 }78 // const axiosWithoutAdapter = createNewAxios();79 var copy = Object.assign(config, { adapter: defaultAdapter });80 // console.log('NEW ADAPTER THING', copy)81 // const axiosWithoutAdapter = axios(copy);82 return axios.request(config)83 .then(function(res) {84 // console.log('RESPONSE', res)85 resolve(res);86 }, function(err) {87 // console.log('ERROR', err)88 reject(err);89 });90 })91 }92 //////////////////////////////////////////////////////////////////////////////93 const service = createNewAxios(cacheAdapter);94 //////////////////////////////////////////////////////////////////////////////95 function createNewAxios(adapter) {96 var instance = axios.create({97 paramsSerializer: params => qs.stringify(params, { arrayFormat: 'repeat' }),98 adapter,99 // adapter: throttleAdapterEnhancer(cacheAdapterEnhancer(axios.defaults.adapter, { defaultCache: defaultCache }))100 // adapter: throttleAdapterEnhancer(cacheAdapterEnhancer(axios.defaults.adapter, { defaultCache: defaultCache }))101 });102 ///////////////////////////////////////103 instance.defaults.baseURL = fluro.apiURL;104 instance.defaults.headers.common.Accept = 'application/json';105 instance.defaults.withCredentials = fluro.withCredentials;106 /////////////////////////////////////////////////////107 // Add relative date and timezone to every request108 instance.interceptors.request.use(function(config) {109 config.headers['fluro-request-date'] = new Date().getTime();110 if (fluro.date.defaultTimezone) {111 config.headers['fluro-request-timezone'] = fluro.date.defaultTimezone;112 }113 config.headers['fluro-api-version'] = '2.2.30';114 // console.log('USER CONTEXT BY DEFAULT?', fluro.userContextByDefault, config.application, config.disableUserContext)115 ////////////////////////116 //We aren't using the user context by default117 if(!fluro.userContextByDefault) {118 //It's just a normal request and we haven't specified an application119 if (!config.application || config.disableUserContext) {120 return config;121 }122 }123 if (!fluro.app) {124 return config;125 }126 ////////////////////////127 if(fluro.app.uuid) {128 config.headers['fluro-app-uuid'] = fluro.app.uuid;129 console.log('request uuid')130 }131 ////////////////////////132 //There's no app or app user defined anyway133 if (!fluro.app.user) {134 return config;135 }136 ////////////////////////137 console.log('Request as user', fluro.app.user.firstName);138 config.headers['Authorization'] = `Bearer ${fluro.app.user.token}`;139 if(config.params && config.params.access_token) {140 delete config.params.access_token;141 }142 return config;143 });144 /////////////////////////////////////////////////////145 instance.interceptors.response.use(function(response) {146 var config = response.config147 var cacheKey = getCacheKeyFromConfig(config);148 var cache = response.config.cache || defaultCache;149 /////////////////////////////////////////////////////150 if (!cache) {151 return response;152 }153 /////////////////////////////////////////////////////154 switch (String(config.method).toLowerCase()) {155 case 'put':156 case 'patch':157 case 'post':158 case 'delete':159 var idSource = {160 _id: (config.data || {})._id,161 params: config.params,162 url: config.url,163 }164 var ids = retrieveIDs(idSource);165 cache.forEach(function(value, key, cache) {166 if(value.data) {167 value = value.data;168 // console.log('down one level', value)169 }170 var cacheIDs = retrieveIDs({ key, value });171 var crossover = _.intersection(cacheIDs, ids).length;172 if (crossover) {173 cache.del(key);174 // console.log('WIPE RELATED KEY', key);175 }176 });177 break;178 default:179 //Save into the cache180 cache.set(cacheKey, response);181 break;182 }183 /////////////////////////////////////////////////////184 return response;185 }, function(err) {186 if (axios.isCancel(err)) {187 console.log('Request cancelled');188 return Promise.reject(err);189 }190 //Get the response status191 var status = _.get(err, 'response.status') || err.status;192 //Check the status193 switch (status) {194 case 401:195 //Ignore and allow fluro.auth to handle it196 if(fluro.app && fluro.app.user) {197 fluro.app.user = null;198 }199 break;200 case 502:201 // case 503:202 case 504:203 //Retry204 //Try it again205 console.log(`fluro.api > ${status} connection error retrying`)206 return instance.request(err.config);207 break;208 case 404:209 break;210 default:211 //Some other error212 console.log('fluro.api > connection error', status, err);213 break;214 }215 /////////////////////////////////////////////////////216 return Promise.reject(err);217 })218 /////////////////////////////////////////////////////219 return instance;220 }221 ///////////////////////////////////////222 /**223 * @name api.get224 * @description Makes a get http request to the Fluro REST API225 * @function226 * @param {String} path The Fluro API endpoint to request227 * @param {Object} config Optional parameters for the request228 * @example229 * //Make a request to get the current user session230 * fluro.api.get('/content/article', {231 * params:{232 * select:'title created',233 * limit:10,234 * simple:true,235 * }236 * })237 * .then(function (response) {238 * console.log(response);239 * })240 * .catch(function (error) {241 * console.log(error);242 * });243 */244 /**245 * @name api.post246 * @description Makes a post http request to the Fluro REST API247 * @function248 * @param {String} path The Fluro API endpoint to request249 * @param {Object} config Optional parameters for the request250 * @example251 * 252 * fluro.api.post('/content/article', {title:'my new article', ...}, {253 * //headers and other things254 * })255 * .then(function (response) {256 * console.log(response);257 * })258 * .catch(function (error) {259 * console.log(error);260 * });261 */262 /**263 * @name api.put264 * @description Makes a put http request to the Fluro REST API265 * @function266 * @param {String} path The Fluro API endpoint to request267 * @param {Object} config Optional parameters for the request268 * @example269 * 270 * fluro.api.put('/content/article/5ca3d64dd2bb085eb9d450db', {title:'my new article', ...}, {271 * //headers and other things272 * })273 * .then(function (response) {274 * console.log(response);275 * })276 * .catch(function (error) {277 * console.log(error);278 * });279 */280 /**281 * @name api.delete282 * @description Makes a delete http request to the Fluro REST API283 * @function284 * @param {String} path The Fluro API endpoint to request285 * @param {Object} config Optional parameters for the request286 * @example287 * 288 * fluro.api.delete('/content/article/5ca3d64dd2bb085eb9d450db')289 * .then(function (response) {290 * console.log(response);291 * })292 * .catch(function (error) {293 * console.log(error);294 * });295 */296 ///////////////////////////////////////////////////297 /**298 * A helper function for generating an authenticated url for the current user299 * @param {string} endpoint The id of the asset, or the asset object you want to download300 * @alias api.generateEndpointURL301 * @param {object} params 302 * @return {string} A full URL with relevant parameters included303 * @example304 * // returns 'https://api.fluro.io/something?access_token=2352345...'305 * fluro.api.generateEndpointURL('/something');306 */307 service.generateEndpointURL = function(path, params) {308 if (!path || !String(path).length) {309 return;310 }311 if (!params) {312 params = {};313 }314 var url = `${fluro.apiURL}${path}`;315 ////////////////////////////////////////316 317 url = parameterDefaults(url, params);318 ////////////////////////////////////////319 //Map the parameters to a query string320 var queryParameters = fluro.utils.mapParameters(params);321 if (queryParameters.length) {322 url += '?' + queryParameters;323 }324 return url;325 }326 ///////////////////////////////////////////////////////327 function parameterDefaults(url, params) {328 //If we haven't requested without token329 if (!params.withoutToken) {330 //Get the current token from FluroAuth331 var CurrentFluroToken = fluro.auth.getCurrentToken();332 //Check to see if we have a token and none has been explicity set333 if (!params['access_token'] && CurrentFluroToken) {334 //Use the current token by default335 params['access_token'] = CurrentFluroToken;336 }337 }338 ////////////////////////////////////339 if (fluro.app && fluro.app.uuid) {340 params['did'] = fluro.app.uuid;341 }342 return url;343 }344 /////////////////////////////////////////////////////345 //Get all mongo ids from a string346 function retrieveIDs(data) {347 var dataString;348 if (_.isString(data)) {349 dataString = data;350 } else {351 dataString = JSON.stringify(data);352 }353 //Find all mongo ids included in the object354 var myregexp = /[0-9a-fA-F]{24}/g;355 var matches = dataString.match(myregexp);356 //Make sure the matches are unique357 return _.uniq(matches);358 }359 /////////////////////////////////////////////////////360 function getCacheKeyFromConfig(config) {361 var key = _.compact([362 config.method,363 config.url,364 JSON.stringify({ params: config.params, data: config.data }),365 fluro.app && fluro.app.user ? fluro.app.user.persona : '',366 config.application ? 'application' :'',367 config.disableUserContext ? 'disableUserContext' :'',368 ]).join('-')369 // console.log('GET CACHE KEY', key)370 return key;371 }372 ///////////////////////////////////////373 service.CancelToken = CancelToken;374 service.axios = axios;...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...126 return copiedBabelOptions;127 }128 return babelOptions;129}130function getCacheKeyFromConfig(131 sourceText,132 sourcePath,133 babelOptions,134 transformOptions135) {136 const {config, configString, instrument} = transformOptions;137 const configPath = [babelOptions.config || '', babelOptions.babelrc || ''];138 return (0, _crypto().createHash)('md5')139 .update(THIS_FILE)140 .update('\0', 'utf8')141 .update(JSON.stringify(babelOptions.options))142 .update('\0', 'utf8')143 .update(sourceText)144 .update('\0', 'utf8')145 .update(path().relative(config.rootDir, sourcePath))146 .update('\0', 'utf8')147 .update(configString)148 .update('\0', 'utf8')149 .update(configPath.join(''))150 .update('\0', 'utf8')151 .update(instrument ? 'instrument' : '')152 .update('\0', 'utf8')153 .update(process.env.NODE_ENV || '')154 .update('\0', 'utf8')155 .update(process.env.BABEL_ENV || '')156 .update('\0', 'utf8')157 .update(process.version)158 .digest('hex');159}160function loadBabelConfig(cwd, filename, transformOptions) {161 const babelConfig = (0, _loadBabelConfig.loadPartialConfig)(transformOptions);162 assertLoadedBabelConfig(babelConfig, cwd, filename);163 return babelConfig;164}165async function loadBabelConfigAsync(cwd, filename, transformOptions) {166 const babelConfig = await (0, _loadBabelConfig.loadPartialConfigAsync)(167 transformOptions168 );169 assertLoadedBabelConfig(babelConfig, cwd, filename);170 return babelConfig;171}172function loadBabelOptions(173 cwd,174 filename,175 transformOptions,176 jestTransformOptions177) {178 const {options} = loadBabelConfig(cwd, filename, transformOptions);179 return addIstanbulInstrumentation(options, jestTransformOptions);180}181async function loadBabelOptionsAsync(182 cwd,183 filename,184 transformOptions,185 jestTransformOptions186) {187 const {options} = await loadBabelConfigAsync(cwd, filename, transformOptions);188 return addIstanbulInstrumentation(options, jestTransformOptions);189}190const createTransformer = userOptions => {191 var _inputOptions$plugins, _inputOptions$presets;192 const inputOptions =193 userOptions !== null && userOptions !== void 0 ? userOptions : {};194 const options = {195 ...inputOptions,196 caller: {197 name: 'babel-jest',198 supportsDynamicImport: false,199 supportsExportNamespaceFrom: false,200 supportsStaticESM: false,201 supportsTopLevelAwait: false,202 ...inputOptions.caller203 },204 compact: false,205 plugins:206 (_inputOptions$plugins = inputOptions.plugins) !== null &&207 _inputOptions$plugins !== void 0208 ? _inputOptions$plugins209 : [],210 presets: ((_inputOptions$presets = inputOptions.presets) !== null &&211 _inputOptions$presets !== void 0212 ? _inputOptions$presets213 : []214 ).concat(jestPresetPath),215 sourceMaps: 'both'216 };217 function mergeBabelTransformOptions(filename, transformOptions) {218 var _transformOptions$sup,219 _transformOptions$sup2,220 _transformOptions$sup3,221 _transformOptions$sup4;222 const {cwd} = transformOptions.config; // `cwd` first to allow incoming options to override it223 return {224 cwd,225 ...options,226 caller: {227 ...options.caller,228 supportsDynamicImport:229 (_transformOptions$sup = transformOptions.supportsDynamicImport) !==230 null && _transformOptions$sup !== void 0231 ? _transformOptions$sup232 : options.caller.supportsDynamicImport,233 supportsExportNamespaceFrom:234 (_transformOptions$sup2 =235 transformOptions.supportsExportNamespaceFrom) !== null &&236 _transformOptions$sup2 !== void 0237 ? _transformOptions$sup2238 : options.caller.supportsExportNamespaceFrom,239 supportsStaticESM:240 (_transformOptions$sup3 = transformOptions.supportsStaticESM) !==241 null && _transformOptions$sup3 !== void 0242 ? _transformOptions$sup3243 : options.caller.supportsStaticESM,244 supportsTopLevelAwait:245 (_transformOptions$sup4 = transformOptions.supportsTopLevelAwait) !==246 null && _transformOptions$sup4 !== void 0247 ? _transformOptions$sup4248 : options.caller.supportsTopLevelAwait249 },250 filename251 };252 }253 return {254 canInstrument: true,255 getCacheKey(sourceText, sourcePath, transformOptions) {256 const babelOptions = loadBabelConfig(257 transformOptions.config.cwd,258 sourcePath,259 mergeBabelTransformOptions(sourcePath, transformOptions)260 );261 return getCacheKeyFromConfig(262 sourceText,263 sourcePath,264 babelOptions,265 transformOptions266 );267 },268 async getCacheKeyAsync(sourceText, sourcePath, transformOptions) {269 const babelOptions = await loadBabelConfigAsync(270 transformOptions.config.cwd,271 sourcePath,272 mergeBabelTransformOptions(sourcePath, transformOptions)273 );274 return getCacheKeyFromConfig(275 sourceText,276 sourcePath,277 babelOptions,278 transformOptions279 );280 },281 process(sourceText, sourcePath, transformOptions) {282 const babelOptions = loadBabelOptions(283 transformOptions.config.cwd,284 sourcePath,285 mergeBabelTransformOptions(sourcePath, transformOptions),286 transformOptions287 );288 const transformResult = (0, _core().transformSync)(...

Full Screen

Full Screen

Jest Testing Tutorial

LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.

Chapters

  1. What is Jest Framework
  2. Advantages of Jest - Jest has 3,898,000 GitHub repositories, as mentioned on its official website. Learn what makes Jest special and why Jest has gained popularity among the testing and developer community.
  3. Jest Installation - All the prerequisites and set up steps needed to help you start Jest automation testing.
  4. Using Jest with NodeJS Project - Learn how to leverage Jest framework to automate testing using a NodeJS Project.
  5. Writing First Test for Jest Framework - Get started with code-based tutorial to help you write and execute your first Jest framework testing script.
  6. Jest Vocabulary - Learn the industry renowned and official jargons of the Jest framework by digging deep into the Jest vocabulary.
  7. Unit Testing with Jest - Step-by-step tutorial to help you execute unit testing with Jest framework.
  8. Jest Basics - Learn about the most pivotal and basic features which makes Jest special.
  9. Jest Parameterized Tests - Avoid code duplication and fasten automation testing with Jest using parameterized tests. Parameterization allows you to trigger the same test scenario over different test configurations by incorporating parameters.
  10. Jest Matchers - Enforce assertions better with the help of matchers. Matchers help you compare the actual output with the expected one. Here is an example to see if the object is acquired from the correct class or not. -

|<p>it('check_object_of_Car', () => {</p><p> expect(newCar()).toBeInstanceOf(Car);</p><p> });</p>| | :- |

  1. Jest Hooks: Setup and Teardown - Learn how to set up conditions which needs to be followed by the test execution and incorporate a tear down function to free resources after the execution is complete.
  2. Jest Code Coverage - Unsure there is no code left unchecked in your application. Jest gives a specific flag called --coverage to help you generate code coverage.
  3. HTML Report Generation - Learn how to create a comprehensive HTML report based on your Jest test execution.
  4. Testing React app using Jest Framework - Learn how to test your react web-application with Jest framework in this detailed Jest tutorial.
  5. Test using LambdaTest cloud Selenium Grid - Run your Jest testing script over LambdaTest cloud-based platform and leverage parallel testing to help trim down your test execution time.
  6. Snapshot Testing for React Front Ends - Capture screenshots of your react based web-application and compare them automatically for visual anomalies with the help of Jest tutorial.
  7. Bonus: Import ES modules with Jest - ES modules are also known as ECMAScript modules. Learn how to best use them by importing in your Jest testing scripts.
  8. Jest vs Mocha vs Jasmine - Learn the key differences between the most popular JavaScript-based testing frameworks i.e. Jest, Mocha, and Jasmine.
  9. Jest FAQs(Frequently Asked Questions) - Explore the most commonly asked questions around Jest framework, with their answers.

Run Jest 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