Best JavaScript code snippet using wpt
request.test.js
Source: request.test.js
1import nock from 'nock'2import farfetch from '../src'3afterAll(() => {4 nock.cleanAll()5})6const URL_TEST = 'http://api.localhost'7const API_TEST = '/login/'8const fetch = farfetch.api(URL_TEST)9function returnRequestHeaders() {10 return this.req.headers11}12test('rejects with status code != 2XX', async () => {13 nock(URL_TEST).get(API_TEST).reply(400, returnRequestHeaders)14 try {15 expect(await fetch.get(API_TEST)).toThrow()16 } catch (e) {17 expect(e).toBeDefined()18 }19})20test('fetches without baseURL', async () => {21 nock('http://other-api.localhost').get('/login/').reply(200, returnRequestHeaders)22 const request = await fetch.get('http://other-api.localhost/login/', { noBaseURL: true })23 expect(request.host).toBe('other-api.localhost')24})25test('gets a formatted final URL', () => {26 const url = 'http://some.thing'27 const params = {28 a: 'some value',29 b: false,30 c: undefined,31 d: ['a', 'b'],32 teste: [['a', 'b'], ['c', 'd']],33 }34 expect(fetch.getURL(url, {}, params))35 .toBe('http://some.thing/?a=some value&b=false&d[]=a&d[]=b&teste[]=a,b&teste[]=c,d')36})37test('with removeTrailingSlash = true ', () => {38 const url = 'http://some.thing/end/trailing/slash/'39 expect(fetch.getURL(url, { removeTrailingSlash: true }))40 .toBe('http://some.thing/end/trailing/slash')41})42test('with removeTrailingSlash as option instance ', () => {43 const BASE = 'http://some.thing/'44 const customFetch = farfetch.api(BASE, false, { removeTrailingSlash: true })45 const path = 'end/trailing/slash/'46 expect(customFetch.getURL(path, { removeTrailingSlash: true }))47 .toBe('http://some.thing/end/trailing/slash')48 expect(customFetch.getURL(path))49 .toBe('http://some.thing/end/trailing/slash')50})51test('has default content-type header and has no Authorization header', async () => {52 nock(URL_TEST).get(API_TEST).reply(200, returnRequestHeaders)53 const request = await fetch.get(API_TEST)54 expect(request['content-type'][0]).toBe('application/json; charset=UTF-8')55 expect(request.authorization).toBeFalsy()56})57test('has custom content-type header', async () => {58 nock(URL_TEST).get(API_TEST).reply(200, returnRequestHeaders)59 const request = await fetch.get(API_TEST, {60 headers: {61 'Content-type': 'text/html',62 },63 })64 expect(request['content-type'][0]).toBe('text/html')65})66test('has overrided Authorization headers (ignores `key`)', async () => {67 nock(URL_TEST).get(API_TEST).reply(200, returnRequestHeaders)68 const request = await fetch.get(API_TEST, {69 key: 'ABCDEFG',70 headers: {71 Authorization: 'Token ABCDEFGH',72 },73 })74 expect(request.authorization[0]).toBe('Token ABCDEFGH')75})76test('has Authorization header generated by `key` option', async () => {77 nock(URL_TEST).get(API_TEST).reply(200, returnRequestHeaders)78 const request = await fetch.get(API_TEST, { key: 'banana' })79 expect(request.authorization[0]).toBe('Token banana')80})81const defaults = { method: 'PUT', headers: { 'content-type': 'leleo', 'some-other-header': '123' } }82const fetchWithDefaults = farfetch.api(URL_TEST, defaults)83test('has default content-type header', async () => {84 nock(URL_TEST).put(API_TEST).reply(200, returnRequestHeaders)85 const request = await fetchWithDefaults.request(API_TEST)86 expect(request['content-type'][0]).toBe('leleo')87 expect(request['some-other-header'][0]).toBe('123')88})89test('has custom header generated by `key` option with custom keyword and header name', async () => {90 nock(URL_TEST).get(API_TEST).reply(200, returnRequestHeaders)91 const f = farfetch.api(URL_TEST, null, {92 defaultAuthorizationKeyword: 'SomeThing ',93 defaultAuthorizationHeader: 'NotAuth',94 })95 const request = await f.get(API_TEST, { key: 'banana' })96 expect(request.notauth[0]).toBe('SomeThing banana')97})98test('rejects when the URL is not valid', async () => {99 const f = farfetch.api(URL_TEST, null)100 try {101 await f.get(API_TEST)102 } catch (e) {103 expect(e.error.name).toBe('FetchError')104 }105})106test('rejects when the response body is malformed JSON', async () => {107 nock(URL_TEST).get(API_TEST).reply(200, 'asd', {108 'content-type': 'application/json',109 })110 const f = farfetch.api(URL_TEST)111 try {112 await f.get(API_TEST)113 } catch (e) {114 expect(e.message).toBe('PARSE_ERROR')115 }116})117test('rejects when the response is not OK', async () => {118 nock(URL_TEST).get(API_TEST).reply(500, 'some text')119 const f = farfetch.api(URL_TEST)120 try {121 await f.get(API_TEST)122 } catch (e) {123 expect(e).toBe('some text')124 }125})126test('rejects with parse error also when the response is not OK', async () => {127 nock(URL_TEST).get(API_TEST).reply(500, 'some text', {128 'content-type': 'application/json',129 })130 const f = farfetch.api(URL_TEST)131 try {132 await f.get(API_TEST)133 } catch (e) {134 expect(e.message).toBe('PARSE_ERROR')135 }136})137test('rejects when the response not OK with parsed JSON', async () => {138 nock(URL_TEST).get(API_TEST).reply(400, { valid: 'json' }, {139 'content-type': 'application/json',140 })141 const f = farfetch.api(URL_TEST)142 try {143 await f.get(API_TEST)144 } catch (e) {145 expect(e).toEqual({ valid: 'json' })146 }...
course-filters.js
Source: course-filters.js
1(function ($) {2 function thim_updateQueryStringParameter(url, key, value) {3 if (!url) {4 url = window.location.href;5 }6 var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");7 var separator = url.indexOf('?') !== -1 ? "&" : "?";8 var url_match = url.match(re);9 if (url_match) {10 if (value && value != '') {11 return url.replace(re, '$1' + key + "=" + value + '$2');12 } else {13 if( url_match[2] ) {14 url = url.replace(re, '$1');15 }else{16 url = url.replace(re, '');17 }18 return url;19 }20 }21 else {22 //If not match23 if (value && value != '') {24 return url + separator + key + "=" + value;25 } else {26 return url;27 }28 }29 }30 function thim_filters_addLoading() {31 $('body').addClass('course-filter-active').append('<div class="filter-loading"><div class="cssload-container"><div class="cssload-loading"><i></i><i></i><i></i><i></i></div></div></div>');32 }33 function thim_filters_removeLoading() {34 $('body').removeClass('course-filter-active');35 $('.filter-loading').remove();36 }37 function thim_filters_ajaxComplete(html) {38 var archive = $('#lp-archive-courses'),39 filters = $('.widget-course-filters-contain'),40 archive_html = $(html).find('#lp-archive-courses').html();41 //filters_html = $(html).find('.widget-course-filters-contain').html();42 archive.html(archive_html);43 //filters.html(filters_html);44 $('body').removeClass('course-filter-active');45 $('.filter-loading').remove();46 }47 function thim_filters_sendAjax(url) {48 $.ajax({49 type : 'POST',50 dataType : 'html',51 url : url,52 beforeSend: function () {53 thim_filters_addLoading();54 },55 success : function (html) {56 if (html) {57 thim_filters_ajaxComplete(html);58 }59 },60 error : function () {61 thim_filters_removeLoading();62 }63 });64 }65 $(document).ready(function () {66 $(document).on('change', '.course_filter_price input[name="lp_price"]', function () {67 var elem = $(this),68 elem_val = elem.val();69 var url_ajax = window.location.protocol + "//" + window.location.host + window.location.pathname,70 url_test = ( elem_val != '' ) ? ( url_ajax + '?lp_price=' + elem_val ) : url_ajax;71 if (!window.location.search) {72 window.history.pushState({path: url_test}, '', url_test);73 } else {74 var url_test = thim_updateQueryStringParameter(window.location.href, 'lp_price', elem_val);75 window.history.pushState({path: url_test}, '', url_test);76 }77 thim_filters_sendAjax(url_test);78 });79 $(document).on('change', '.course_filter_featured input[name="lp_featured"]', function () {80 var elem = $(this),81 elem_val = elem.val();82 if (!elem.is(':checked')) {83 elem_val = '';84 }85 var url_ajax = window.location.protocol + "//" + window.location.host + window.location.pathname,86 archive = $('#lp-archive-courses'),87 url_test = ( elem_val != '' ) ? ( url_ajax + '?lp_featured=' + elem_val ) : url_ajax;88 if (!window.location.search) {89 window.history.pushState({path: url_test}, '', url_test);90 } else {91 var url_test = thim_updateQueryStringParameter(window.location.href, 'lp_featured', elem_val);92 window.history.pushState({path: url_test}, '', url_test);93 }94 thim_filters_sendAjax(url_test);95 });96 $(document).on('change', '.course_filter_orderby [name="lp_orderby"]', function () {97 var elem = $(this),98 elem_val = elem.val();99 var url_ajax = window.location.protocol + "//" + window.location.host + window.location.pathname,100 archive = $('#lp-archive-courses'),101 url_test = ( elem_val != '' ) ? ( url_ajax + '?lp_orderby=' + elem_val ) : url_ajax;102 if (!window.location.search) {103 window.history.pushState({path: url_test}, '', url_test);104 } else {105 var url_test = thim_updateQueryStringParameter(window.location.href, 'lp_orderby', elem_val);106 window.history.pushState({path: url_test}, '', url_test);107 }108 thim_filters_sendAjax(url_test);109 });110 });...
Using AI Code Generation
1var wptools = require('wptools');2wptools.url_test(url, function(err, resp) {3 if (err) {4 console.log(err);5 } else {6 console.log(resp);7 }8});9{10 "infobox": {11 "education": "Occidental College (BA), Columbia University (JD)",
Using AI Code Generation
1var wpt = require('wpt.js');2 if (err) {3 console.log(err);4 }5 else {6 console.log(data);7 }8});9var request = require('request');10var wpt = {11 url_test: function (url, callback) {12 var options = {13 qs: {14 }15 };16 request(options, function (err, res, body) {17 if (err) {18 return callback(err, null);19 }20 else {21 return callback(null, body);22 }23 });24 }25};26module.exports = wpt;
Using AI Code Generation
1var wpt = require('wpt.js');2 if (err) {3 console.log(err);4 } else {5 console.log(data);6 }7});
Using AI Code Generation
1var wpt = require('wpt');2wpt.url_test(url, function(err, data) {3 if (err) {4 console.log('error: ' + err);5 } else {6 console.log(data)
Using AI Code Generation
1var wpt = require('wpt.js');2wpt.url_test(url, function(data) {3 console.log(data);4});5var request = require('request');6exports.url_test = function(url, callback) {7 if (!error && response.statusCode == 200) {8 callback(body);9 }10 });11}
Using AI Code Generation
1var wpt = require('./wpt.js');2 console.log(data);3});4var request = require('request');5module.exports.url_test = function(url, browser, location, callback){6 var options = {7 qs: {8 }9 };10 request(options, function(error, response, body){11 if(!error && response.statusCode == 200){12 callback(body);13 }14 });15};16var wpt = require('./wpt.js');17 console.log(data);18 wpt.result(data.testId, function(data){19 console.log(data);20 });21});22var request = require('request');23module.exports.url_test = function(url, browser, location, callback){24 var options = {25 qs: {26 }27 };28 request(options, function(error, response, body){29 if(!error && response.statusCode == 200){30 callback(JSON.parse(body));31 }32 });33};34module.exports.result = function(testId, callback){35 var options = {
Using AI Code Generation
1 if(err){2 console.log(err);3 } else {4 console.log(data);5 }6});7 if(err){8 console.log(err);9 } else {10 fs.writeFile('google.json', JSON.stringify(data), function (err) {11 if (err) throw err;12 console.log('It\'s saved!');13 });14 }15});16 if(err){17 console.log(err);18 } else {19 fs.writeFile('google.json', JSON.stringify(data), function (err) {20 if (err) throw err;21 console.log('It\'s saved!');22 });23 console.log(data);24 }25});26 if(err){27 console.log(err);28 } else {29 fs.writeFile('google.json', JSON.stringify(data), function (err) {30 if (err) throw err;31 console.log('It\'s saved!');32 });33 console.log(data);34 console.log('Status: '+data.statusCode);35 }36});
Using AI Code Generation
1var wpt = require('wpt.js');2var wpt = new WebPageTest('www.webpagetest.org', 'A.3eef3a0b3e8a2d0e2f4b0a1b9f1b4a4b');3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 }8});9var wpt = require('wpt.js');10var wpt = new WebPageTest('www.webpagetest.org', 'A.3eef3a0b3e8a2d0e2f4b0a1b9f1b4a4b');11 if (err) {12 console.log(err);13 } else {14 console.log(data);15 }16});
Check out the latest blogs from LambdaTest on this topic:
Testing is a critical step in any web application development process. However, it can be an overwhelming task if you don’t have the right tools and expertise. A large percentage of websites still launch with errors that frustrate users and negatively affect the overall success of the site. When a website faces failure after launch, it costs time and money to fix.
We launched LT Browser in 2020, and we were overwhelmed by the response as it was awarded as the #5 product of the day on the ProductHunt platform. Today, after 74,585 downloads and 7,000 total test runs with an average of 100 test runs each day, the LT Browser has continued to help developers build responsive web designs in a jiffy.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
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!!