Best JavaScript code snippet using taiko
Leanplum.test.ts
Source:Leanplum.test.ts
...43 * Intercept the next request.44 * @param {Function} callback The callback to be called on interception.45 */46let xhr47function interceptRequest(callback) {48 xhr = sinon.useFakeXMLHttpRequest()49 xhr.onCreate = function(req) {50 // Wait for request to populate correctly.51 setTimeout(function() {52 callback(req)53 }, 0)54 }55}56const testModes = {57 PROD: 0,58 DEV: 159}60let Leanplum61const start = (done) => {62 interceptRequest((request) => {63 expect(request).not.toBeNull()64 request.respond(200, {65 'Content-Type': 'application/json'66 }, JSON.stringify(startResponse))67 })68 Leanplum.setRequestBatching(false)69 Leanplum.start(userId, userAttributes, (success) => {70 expect(success).toBe(true)71 done && done(success ? null : success)72 })73}74function setAppId(mode) {75 if (mode === testModes.DEV) {76 Leanplum.setAppIdForDevelopmentMode(APP_ID, KEY_PROD)77 } else {78 Leanplum.setAppIdForProductionMode(APP_ID, KEY_DEV)79 }80}81Object.keys(testModes).forEach((mode) => {82 describe(mode + ' mode:', () => {83 const LEANPLUM_PATH = '../../dist/leanplum.js'84 beforeEach(() => {85 Leanplum = require(LEANPLUM_PATH)86 setAppId(testModes[mode])87 })88 afterEach(() => {89 if (xhr) {90 xhr.restore()91 xhr = null92 }93 Leanplum.__destroy()94 delete require.cache[require.resolve(LEANPLUM_PATH)]95 Leanplum = null96 localStorage.clear()97 })98 describe('Test start methods.', () => {99 it('start', (done) => {100 interceptRequest((request) => {101 request.respond(200, {102 'Content-Type': 'application/json'103 }, JSON.stringify(startResponse))104 })105 Leanplum.start(userId, userAttributes, (success) => {106 expect(success).toBe(true)107 done()108 })109 })110 it('startFromCache', (done) => {111 Leanplum.startFromCache(userId, userAttributes, (success) => {112 expect(success).toBe(true)113 done()114 })115 })116 it('stop', (done) => {117 interceptRequest((request) => {118 expect(request).not.toBeNull()119 expect(getAction(request)).toBe('stop')120 request.respond(200, {121 'Content-Type': 'application/json'122 }, JSON.stringify(successResponse))123 done()124 })125 Leanplum.stop()126 })127 })128 describe('Test action methods.', () => {129 beforeEach(start)130 it('pauseSession', (done) => {131 interceptRequest((request) => {132 expect(request).not.toBeNull()133 expect(getAction(request)).toBe('pauseSession')134 request.respond(200, {135 'Content-Type': 'application/json'136 }, JSON.stringify(successResponse))137 done()138 })139 Leanplum.pauseSession()140 })141 it('resumeSession', (done) => {142 interceptRequest((request) => {143 expect(request).not.toBeNull()144 expect(getAction(request)).toBe('resumeSession')145 request.respond(200, {146 'Content-Type': 'application/json'147 }, JSON.stringify(successResponse))148 done()149 })150 Leanplum.resumeSession()151 })152 it('pauseState', (done) => {153 interceptRequest((request) => {154 expect(request).not.toBeNull()155 expect(getAction(request)).toBe('pauseState')156 request.respond(200, {157 'Content-Type': 'application/json'158 }, JSON.stringify(successResponse))159 done()160 })161 Leanplum.pauseState()162 })163 it('resumeState', (done) => {164 interceptRequest((request) => {165 expect(request).not.toBeNull()166 expect(getAction(request)).toBe('resumeState')167 request.respond(200, {168 'Content-Type': 'application/json'169 }, JSON.stringify(successResponse))170 done()171 })172 Leanplum.resumeState()173 })174 it('setUserAttributes', (done) => {175 interceptRequest((request) => {176 expect(request).not.toBeNull()177 expect(getAction(request)).toBe('setUserAttributes')178 request.respond(200, {179 'Content-Type': 'application/json'180 }, JSON.stringify(successResponse))181 done()182 })183 Leanplum.setUserAttributes(userId, userAttributes)184 })185 it('advanceTo', (done) => {186 interceptRequest((request) => {187 expect(request).not.toBeNull()188 expect(getAction(request)).toBe('advance')189 request.respond(200, {190 'Content-Type': 'application/json'191 }, JSON.stringify(successResponse))192 done()193 })194 Leanplum.advanceTo('Shopping Cart')195 })196 it('verifyDefaultApiPath', (done) => {197 interceptRequest((request) => {198 expect(request).not.toBeNull()199 expect(request.url).toContain('https://api.leanplum.com/api')200 request.respond(200, {201 'Content-Type': 'application/json'202 }, JSON.stringify(successResponse))203 done()204 })205 Leanplum.track('Page View')206 })207 it('setApiPath', (done) => {208 const newApiPath = 'http://leanplum-staging.appspot.com/api'209 interceptRequest((request) => {210 expect(request).not.toBeNull()211 expect(request.url).toContain(newApiPath)212 request.respond(200, {213 'Content-Type': 'application/json'214 }, JSON.stringify(successResponse))215 done()216 })217 Leanplum.setApiPath(newApiPath)218 Leanplum.track('Page View')219 })220 it('setUserAttributes', (done) => {221 interceptRequest((request) => {222 expect(request).not.toBeNull()223 let json = JSON.parse(request.requestBody).data[0]224 expect(getAction(request)).toBe('setUserAttributes')225 expect(json.newUserId).toBe('u1')226 expect(JSON.parse(json.userAttributes).gender).toBe(227 userAttributes.gender)228 expect(JSON.parse(json.userAttributes).age).toBe(229 userAttributes.age)230 request.respond(200, {231 'Content-Type': 'application/json'232 }, JSON.stringify(successResponse))233 done()234 })235 Leanplum.setUserAttributes('u1', userAttributes)236 })237 xit('setRequestBatching', (done) => {238 Leanplum.setRequestBatching(true, 0.1)239 let count = 0240 interceptRequest((request) => {241 expect(request).not.toBeNull()242 count++243 request.respond(200, {244 'Content-Type': 'application/json'245 }, JSON.stringify(successResponse))246 })247 Leanplum.track('Page View')248 Leanplum.advanceTo('Shopping Cart')249 setTimeout(function() {250 expect(count).toBe(testModes[mode] === testModes.DEV ? 2 : 1)251 done()252 }, 100)253 })254 })255 describe('Test addStartResponseHandler callback after start.', () => {256 it('test addStartResponseHandler', (done) => {257 interceptRequest((request) => {258 request.respond(200, {259 'Content-Type': 'application/json'260 }, JSON.stringify(startResponse))261 })262 Leanplum.addStartResponseHandler(() => {263 return done()264 })265 Leanplum.start()266 })267 })268 describe('Test forceContentUpdate.', () => {269 it('forceContentUpdate', (done) => {270 interceptRequest((request) => {271 expect(request).not.toBeNull()272 expect(getAction(request)).toBe('getVars')273 request.respond(200, {274 'Content-Type': 'application/json'275 }, JSON.stringify(successResponse))276 })277 Leanplum.forceContentUpdate(() => done())278 })279 })280 describe('Test variable changed callback after forceContentUpdate.', () => {281 it('test setVariable forceContentUpdate', (done) => {282 interceptRequest((request) => {283 if (getAction(request) == 'getVars'){284 request.respond(200, {285 'Content-Type': 'application/json'286 }, JSON.stringify(forceContentUpdateResponse))287 } else {288 request.respond(200, {289 'Content-Type': 'application/json'290 }, JSON.stringify(startResponse))291 }292 })293 Leanplum.setVariables(userAttributes)294 Leanplum.start()295 var isVariablesChangedFromStart = true296 let vars = forceContentUpdateResponse.response[0].vars297 Leanplum.addVariablesChangedHandler(() => {298 if(isVariablesChangedFromStart) {299 isVariablesChangedFromStart = false;300 expect(Leanplum.getVariables().gender).toBe(userAttributes.gender)301 expect(Leanplum.getVariables().age).toBe(userAttributes.age)302 } else {303 expect(Leanplum.getVariables().gender).toBe(vars.gender)304 expect(Leanplum.getVariables().age).toBe(vars.age)305 return done()306 }307 })308 Leanplum.forceContentUpdate();309 })310 })311 describe('Test callback in forceContentUpdate.', () => {312 it('test callback success forceContentUpdate', (done) => {313 interceptRequest((request) => {314 if (getAction(request) == 'getVars'){315 request.respond(200, {316 'Content-Type': 'application/json'317 }, JSON.stringify(forceContentUpdateResponse))318 } else {319 request.respond(200, {320 'Content-Type': 'application/json'321 }, JSON.stringify(startResponse))322 }323 })324 Leanplum.setVariables(userAttributes)325 Leanplum.start()326 let vars = forceContentUpdateResponse.response[0].vars327 Leanplum.forceContentUpdate(function(success) {328 expect(success).toBe(true)329 expect(Leanplum.getVariables().gender).toBe(vars.gender)330 expect(Leanplum.getVariables().age).toBe(vars.age)331 return done()332 });333 })334 it('test callback error response forceContentUpdate', (done) => {335 interceptRequest((request) => {336 if (getAction(request) == 'getVars'){337 request.respond(500, {338 'Content-Type': 'application/json'339 })340 } else {341 request.respond(200, {342 'Content-Type': 'application/json'343 }, JSON.stringify(startResponse))344 }345 })346 Leanplum.start()347 Leanplum.forceContentUpdate(function(success) {348 expect(success).toBe(false)349 return done()350 });351 })352 it('test callback response success:false forceContentUpdate', (done) => {353 interceptRequest((request) => {354 if (getAction(request) == 'getVars'){355 request.respond(200, {356 'Content-Type': 'application/json'357 }, JSON.stringify({"response": [{"success": false}]}))358 } else {359 request.respond(200, {360 'Content-Type': 'application/json'361 }, JSON.stringify(startResponse))362 }363 })364 Leanplum.start()365 Leanplum.forceContentUpdate(function(success) {366 expect(success).toBe(false)367 return done()...
bg.js
Source:bg.js
...5 * https://github.com/44886/sound-down6 */7/**æ¯æçä¸äºtype*/8var types = ['media', 'video/mp4', 'object'];9chrome.webRequest.onBeforeRequest.addListener(function interceptRequest(request) {10 if (request.type != 'media') {11 return false;12 }13 var url = decodeURIComponent(request.url);14 chrome.tabs.sendMessage(request.tabId, {15 url: url,16 type: 'mp3'17 });18}, {19 urls: ['http://*/*.mp3*', 'https://*/*.mp3*']20}, ['blocking']);21chrome.webRequest.onBeforeRequest.addListener(function interceptRequest(request) {22 if (request.type != 'media') {23 return false;24 }25 var url = decodeURIComponent(request.url);26 chrome.tabs.sendMessage(request.tabId, {27 url: url,28 type: 'wav'29 });30}, {31 urls: ['http://*/*.wav*', 'https://*/*.wav*']32}, ['blocking']);33chrome.webRequest.onBeforeRequest.addListener(function interceptRequest(request) {34 if (request.type != 'media') {35 return false;36 }37 var url = decodeURIComponent(request.url);38 chrome.tabs.sendMessage(request.tabId, {39 url: url,40 type: 'aac'41 });42}, {43 urls: ['http://*/*.aac*', 'https://*/*.aac*']44}, ['blocking']);45chrome.webRequest.onBeforeRequest.addListener(function interceptRequest(request) {46 if (request.type != 'media') {47 return false;48 }49 var url = decodeURIComponent(request.url);50 chrome.tabs.sendMessage(request.tabId, {51 url: url,52 type: 'm4a'53 });54}, {55 urls: ['http://*/*.m4a*', 'https://*/*.m4a*']56}, ['blocking']);57chrome.webRequest.onBeforeRequest.addListener(function interceptRequest(request) {58 if (types.indexOf(request.type) == -1) {59 return false;60 }61 var url = decodeURIComponent(request.url);62 chrome.tabs.sendMessage(request.tabId, {63 url: url,64 type: 'mp4'65 });66}, {67 urls: ['http://*/*.mp4*', 'https://*/*.mp4*']68}, ['blocking']);69/**ä¸äºå
¶ä»çæç±»ç½ç«ï¼æ²¡æåç¼çé£ç§ */70chrome.webRequest.onBeforeRequest.addListener(function interceptRequest(request) {71 console.log(request);72 if (request.type != 'media') {73 return false;74 }75 var url = decodeURIComponent(request.url);76 chrome.tabs.sendMessage(request.tabId, {77 url: url,78 type: 'other'79 });80}, {81 urls: [82 'http://*.pstatp.com/obj/*', /*æé³*/83 'http://*.ixigua.com/*', /**è¿ä¹æ¯æé³ï¼ä¸ç¥é为ä»ä¹æ¯ ixigua */84 ]...
ApiClient.js
Source:ApiClient.js
...5 this.serviceOptions = {6 withCredentials: true7 } 8 }9 async interceptRequest(request) {10 try {11 await request;12 } catch(err) {13 if (err.response.status === 408) {14 this.rootStore.routerStore.goTo("home");15 this.rootStore.notificationsStore.error("Session expired")16 }17 }18 if (!this.rootStore.userStore.user && this.rootStore.mainViewStore.currentRoute !== "home") {19 this.rootStore.routerStore.goTo("home");20 }21 return request;22 }23 async get(url, resources) {24 return await this.interceptRequest(axios.get(url, { params: resources, ...this.serviceOptions }));25 }26 async post(url, data) {27 return await this.interceptRequest(axios.post(url, data, this.serviceOptions));28 }29 async patch(url, data) {30 return await this.interceptRequest(axios.patch(url, data, this.serviceOptions));31 }32 async delete(url) {33 return await this.interceptRequest(axios.delete(url, this.serviceOptions));34 }35}...
Using AI Code Generation
1const { openBrowser, goto, interceptRequest, closeBrowser } = require('taiko');2(async () => {3 try {4 await openBrowser();5 request.continue({ method: 'POST', postData: 'Hello World' });6 });7 } catch (e) {8 console.error(e);9 } finally {10 await closeBrowser();11 }12})();
Using AI Code Generation
1const { openBrowser, goto, intercept, closeBrowser } = require('taiko');2(async () => {3 try {4 await openBrowser();5 request.respond("mockData.json", { headers: { "Content-Type": "application/json" } })6 })7 await closeBrowser();8 } catch (error) {9 console.error(error);10 }11})();12### `intercept(url, options, requestHandler)`
Using AI Code Generation
1const { intercept, openBrowser, goto, closeBrowser } = require('taiko');2(async () => {3 try {4 await openBrowser();5 request.respond('{"status": 200, "contentType": "application/json", "body": "Hello World!"}');6 });7 await closeBrowser();8 } catch (e) {9 console.error(e);10 }11})();12const { interceptRequest, openBrowser, goto, closeBrowser } = require('taiko');13(async () => {14 try {15 await openBrowser();16 request.respond('{"status": 200, "contentType": "application/json", "body": "Hello World!"}');17 });18 await closeBrowser();19 } catch (e) {20 console.error(e);21 }22})();23const { interceptResponse, openBrowser, goto, closeBrowser } = require('taiko');24(async () => {25 try {26 await openBrowser();27 request.respond('{"status": 200, "contentType": "application/json", "body": "Hello World!"}');28 });29 await closeBrowser();30 } catch (e) {31 console.error(e);32 }33})();34const { intercept, clearRequestInterception, openBrowser, goto, closeBrowser } = require('taiko');35(async () => {36 try {37 await openBrowser();
Using AI Code Generation
1const { openBrowser, goto, intercept, closeBrowser } = require('taiko');2(async () => {3 try {4 await openBrowser();5 request.respond({6 body: JSON.stringify({ name: 'John' })7 })8 });9 request.respond({10 body: JSON.stringify({ name: 'John' })11 })12 });13 request.respond({14 body: JSON.stringify({ name: 'John' })15 })16 });17 request.respond({18 body: JSON.stringify({ name: 'John' })19 })20 });21 request.respond({22 body: JSON.stringify({ name: 'John' })23 })24 });25 request.respond({26 body: JSON.stringify({ name: 'John' })27 })28 });29 request.respond({30 body: JSON.stringify({ name: 'John' })31 })32 });
Using AI Code Generation
1const { openBrowser, goto, intercept, closeBrowser } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await closeBrowser();6 } catch (e) {7 console.error(e);8 } finally {9 }10})();11const { openBrowser, goto, interceptRequest, closeBrowser } = require('taiko');12(async () => {13 try {14 await openBrowser();15 request.respond({ body: "Hello World" });16 });17 await closeBrowser();18 } catch (e) {19 console.error(e);20 } finally {21 }22})();23const { openBrowser
Using AI Code Generation
1(async () => {2 try {3 request.respond({4 headers: {5 'content-type': 'application/json; charset=utf-8'6 },7 body: '{"login":"testuser","id":123}'8 });9 });10 await openBrowser();11 await click("Login");12 await click("Sign in with GitHub");13 await waitFor(2000);14 await write("testuser");15 await press('Enter');16 await waitFor(2000);17 await click("Testuser");18 await waitFor(2000);19 await screenshot({ path: "./screenshot.png" });20 } catch (e) {21 console.error(e);22 } finally {23 await closeBrowser();24 }25})();26(async () => {27 try {28 await openBrowser();29 await click("Login");30 await click("Sign in with GitHub");31 await waitFor(2000);32 request.respond({33 headers: {34 'content-type': 'application/json; charset=utf-8'35 },36 body: '{"login":"testuser","id":123}'37 });38 });39 await write("testuser");40 await press('Enter');41 await waitFor(2000);42 await click("Testuser");43 await waitFor(2000);44 await screenshot({ path: "./screenshot.png" });45 } catch (e) {46 console.error(e);47 } finally {48 await closeBrowser();49 }50})();51(async () => {52 try {53 await openBrowser();54 await click("Login");55 await click("Sign in with GitHub");56 await waitFor(2000);57 request.respond({
Using AI Code Generation
1const { openBrowser, interceptRequest, closeBrowser, goto, click, text, button, write } = require('taiko');2(async () => {3 try {4 await openBrowser();5 request.continue({6 headers: {7 }8 });9 });10 console.log(await text().exists());11 } catch (e) {12 console.error(e);13 } finally {14 await closeBrowser();15 }16})();17`interceptResponse(pattern, responseHandler)`18| `pattern` | string \| [RequestPattern](
Using AI Code Generation
1const { interceptRequest } = require('taiko');2const { setConfig } = require('taiko/lib/config');3setConfig({4});5const response = {6 headers: {7 },8 body: '{"content": "Hello World!"}',9};10interceptRequest(url, response);11(async () => {12 await openBrowser();13 await goto(url);14 await closeBrowser();15})();16### interceptRequest(url, response, requestMatcher)17const { interceptRequest } = require('taiko');18const { setConfig } = require('taiko/lib/config');19setConfig({20});21const response = {22 headers: {23 },24 body: '{"content": "Hello World!"}',25};26const requestMatcher = {27 postData: '{"name": "John"}',28};29interceptRequest(url, response, requestMatcher);30(async () => {31 await openBrowser();32 await goto(url);33 await closeBrowser();34})();35### clearRequestInterception()36const { interceptRequest, clearRequestInterception } = require('taiko');37const { setConfig } = require('taiko/lib/config');38setConfig({39});40const response = {41 headers: {42 },43 body: '{"content": "Hello World!"}',44};45interceptRequest(url, response);
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!!