Best JavaScript code snippet using playwright-internal
index.spec.js
Source:index.spec.js
...64 accountActions.setupNewAccountPending(),65 accountActions.updateStatus(defaultStatus),66 permissionsActions.checkAllPermissions(),67 permissionsActions.requestAllPermissions(),68 accountActions.startTracing(),69 ]);70 });71 it('should not request permissions when they were already granted', async () => {72 // Execute73 const channel = stdChannel();74 const dispatched = [];75 runSaga({76 channel,77 dispatch: (action) => dispatched.push(action),78 }, setupNewAccount);79 channel.put(permissionsActions.checkAllPermissionsResult(true));80 // Assert81 expect(dispatched).toHaveLength(4);82 expect(dispatched).toEqual([83 accountActions.setupNewAccountPending(),84 accountActions.updateStatus(defaultStatus),85 permissionsActions.checkAllPermissions(),86 accountActions.startTracing(),87 ]);88 });89 it('should start tracing when startTracing returns success', async () => {90 // Prepare91 NavigationService.navigate.mockImplementation(() => {});92 // Execute93 const channel = stdChannel();94 const dispatched = [];95 const saga = runSaga({96 channel,97 dispatch: (action) => dispatched.push(action),98 }, setupNewAccount);99 channel.put(permissionsActions.checkAllPermissionsResult(true));100 channel.put(accountActions.startTracing(TRACING_RESULTS.SUCCESS));101 await saga.toPromise();102 // Assert103 expect(NavigationService.navigate).toHaveBeenCalled();104 expect(NavigationService.navigate).toHaveBeenCalledWith(AppRoutes.APP);105 expect(dispatched).toHaveLength(8);106 expect(dispatched).toEqual(expect.arrayContaining([107 accountActions.setupNewAccountPending(),108 accountActions.updateStatus(defaultStatus),109 permissionsActions.checkAllPermissions(),110 accountActions.startTracing(),111 accountActions.setTracingEnabled(true),112 onboardingActions.setOnboarding(false),113 accountActions.setupNewAccountDone(),114 ]));115 });116 it('should not start tracing when startTracing returns failed', async () => {117 // Prepare118 NavigationService.navigate.mockImplementation(() => {});119 // Execute120 const channel = stdChannel();121 const dispatched = [];122 const saga = runSaga({123 channel,124 dispatch: (action) => dispatched.push(action),125 }, setupNewAccount);126 channel.put(permissionsActions.checkAllPermissionsResult(true));127 channel.put(accountActions.startTracing(TRACING_RESULTS.FAILED));128 await saga.toPromise();129 // Assert130 expect(NavigationService.navigate).toHaveBeenCalled();131 expect(NavigationService.navigate).toHaveBeenCalledWith(AppRoutes.APP);132 expect(dispatched).toHaveLength(8);133 expect(dispatched).toEqual(expect.arrayContaining([134 accountActions.setupNewAccountPending(),135 accountActions.updateStatus(defaultStatus),136 permissionsActions.checkAllPermissions(),137 accountActions.startTracing(),138 accountActions.setTracingEnabled(false),139 onboardingActions.setOnboarding(false),140 accountActions.setupNewAccountDone(),141 ]));142 });143 it('should not start tracing and report error when startTracing returns gaen', async () => {144 // Prepare145 NavigationService.navigate.mockImplementation(() => {});146 // Execute147 const channel = stdChannel();148 const dispatched = [];149 const saga = runSaga({150 channel,151 dispatch: (action) => dispatched.push(action),152 }, setupNewAccount);153 channel.put(permissionsActions.checkAllPermissionsResult(true));154 channel.put(accountActions.startTracing(TRACING_RESULTS.GAEN));155 await saga.toPromise();156 // Assert157 expect(NavigationService.navigate).toHaveBeenCalled();158 expect(NavigationService.navigate).toHaveBeenCalledWith(AppRoutes.APP);159 expect(dispatched).toHaveLength(9);160 expect(dispatched).toEqual(expect.arrayContaining([161 accountActions.setupNewAccountPending(),162 accountActions.updateStatus(defaultStatus),163 permissionsActions.checkAllPermissions(),164 accountActions.startTracing(),165 accountActions.setTracingEnabled(false),166 accountActions.setErrors([ERRORS[Platform.OS].GAEN_UNEXPECTEDLY_DISABLED]),167 onboardingActions.setOnboarding(false),168 accountActions.setupNewAccountDone(),169 ]));170 });171 });172 describe('Watch Tracing Status', () => {173 afterEach(() => {174 jest.resetAllMocks();175 });176 it('should update status when event is emitted', async () => {177 // Prepare178 let emitter;179 TracingManager.addUpdateEventListener.mockImplementation((callback) => {180 emitter = callback;181 });182 // Execute183 const channel = stdChannel();184 const dispatched = [];185 runSaga({186 channel,187 dispatch: (action) => dispatched.push(action),188 }, watchTracingStatus);189 // Await for watcher to be registered190 await new Promise((resolve) => setTimeout(resolve, 10));191 // Emit tracing event192 emitter(defaultStatus);193 // Assert194 expect(TracingManager.addUpdateEventListener).toHaveBeenCalled();195 expect(dispatched).toHaveLength(2);196 expect(dispatched).toEqual([197 accountActions.tracingStatusListenerRegistered(),198 accountActions.updateStatus(defaultStatus),199 ]);200 });201 });202 describe('Start Tracing', () => {203 afterEach(() => {204 jest.resetAllMocks();205 });206 it('should register tracing status listener when start returns success', async () => {207 // Prepare208 TracingManager.start.mockImplementation(() => Promise.resolve(GAEN_RESULTS.EN_SUCCEEDED));209 TracingManager.sync.mockImplementation(() => Promise.resolve());210 TracingManager.getStatus.mockImplementation(() => Promise.resolve(defaultStatus));211 // Execute212 const channel = stdChannel();213 const dispatched = [];214 runSaga({215 channel,216 dispatch: (action) => dispatched.push(action),217 }, startTracing);218 // Await for watcher to be registered219 await new Promise((resolve) => setTimeout(resolve, 10));220 channel.put(accountActions.tracingStatusListenerRegistered());221 // Await for start222 await new Promise((resolve) => setTimeout(resolve, 10));223 // Assert224 expect(TracingManager.start).toHaveBeenCalled();225 expect(TracingManager.sync).toHaveBeenCalled();226 expect(TracingManager.getStatus).toHaveBeenCalled();227 expect(dispatched).toHaveLength(3);228 expect(dispatched).toEqual([229 accountActions.tracingStatusListenerRegistered(),230 accountActions.updateStatus(defaultStatus),231 accountActions.startTracingResult(TRACING_RESULTS.SUCCESS),232 ]);233 });234 it('should not register tracing status listener when start returns cancelled', async () => {235 // Prepare236 TracingManager.start.mockImplementation(() => Promise.resolve(GAEN_RESULTS.EN_CANCELLED));237 // Execute238 const channel = stdChannel();239 const dispatched = [];240 runSaga({241 channel,242 dispatch: (action) => dispatched.push(action),243 }, startTracing).toPromise();244 // Await for watcher to be registered245 await new Promise((resolve) => setTimeout(resolve, 10));246 channel.put(accountActions.tracingStatusListenerRegistered());247 // Await for start248 await new Promise((resolve) => setTimeout(resolve, 10));249 // Assert250 expect(TracingManager.start).toHaveBeenCalled();251 expect(Alert.alert).toHaveBeenCalled();252 expect(Alert.alert).toHaveBeenCalledWith(253 i18n.translate('common.dialogs.gaen.enable.title'),254 i18n.translate('common.dialogs.gaen.enable.description'),255 [256 {257 text: i18n.translate('common.actions.ok'),258 style: 'default',259 },260 ],261 );262 expect(dispatched).toHaveLength(2);263 expect(dispatched).toEqual([264 accountActions.tracingStatusListenerRegistered(),265 accountActions.startTracingResult(TRACING_RESULTS.GAEN),266 ]);267 });268 it('should not register tracing status listener when start throws an error', async () => {269 // Prepare270 TracingManager.start.mockImplementation(() => Promise.reject(GAEN_RESULTS.EN_FAILED));271 // Execute272 const channel = stdChannel();273 const dispatched = [];274 runSaga({275 channel,276 dispatch: (action) => dispatched.push(action),277 }, startTracing).toPromise();278 // Await for watcher to be registered279 await new Promise((resolve) => setTimeout(resolve, 10));280 channel.put(accountActions.tracingStatusListenerRegistered());281 // Await for start282 await new Promise((resolve) => setTimeout(resolve, 10));283 // Assert284 expect(TracingManager.start).toHaveBeenCalled();285 expect(dispatched).toHaveLength(2);286 expect(dispatched).toEqual([287 accountActions.tracingStatusListenerRegistered(),288 accountActions.startTracingResult(TRACING_RESULTS.FAILED),289 ]);290 });291 it('should stop tracing status listener when stop tracing actions is dispatched', async () => {292 // Prepare293 TracingManager.start.mockImplementation(() => Promise.resolve(GAEN_RESULTS.EN_SUCCEEDED));294 TracingManager.getStatus.mockImplementation(() => Promise.resolve(defaultStatus));295 TracingManager.sync.mockImplementation(() => Promise.resolve());296 // Execute297 const channel = stdChannel();298 const dispatched = [];299 const saga = runSaga({300 channel,301 dispatch: (action) => dispatched.push(action),302 }, startTracing);303 // Await for watcher to be registered304 await new Promise((resolve) => setTimeout(resolve, 10));305 channel.put(accountActions.tracingStatusListenerRegistered());306 channel.put(accountActions.stopTracing());307 await saga.toPromise();308 // Assert309 expect(TracingManager.start).toHaveBeenCalled();310 expect(TracingManager.getStatus).toHaveBeenCalled();311 expect(TracingManager.stop).toHaveBeenCalled();312 expect(TracingManager.sync).toHaveBeenCalled();313 expect(dispatched).toHaveLength(4);314 expect(dispatched).toEqual([315 accountActions.tracingStatusListenerRegistered(),316 accountActions.updateStatus(defaultStatus),317 accountActions.startTracingResult(TRACING_RESULTS.SUCCESS),318 accountActions.stopTracingResult(TRACING_RESULTS.SUCCESS),319 ]);320 });321 });322 describe('Submit Diagnosis', () => {323 afterEach(() => {324 jest.resetAllMocks();325 });326 const code = '123123123123';327 it('should report code when exposed returns success', async () => {328 // Prepare329 TracingManager.exposed.mockImplementation(() => Promise.resolve(GAEN_RESULTS.EN_SUCCEEDED));330 // Execute331 const channel = stdChannel();332 const dispatched = [];333 const saga = runSaga({334 channel,335 dispatch: (action) => dispatched.push(action),336 getState: () => ({337 services: {338 network: true,339 },340 }),341 }, submitDiagnosis, { payload: code });342 channel.put(accountActions.updateStatusResult());343 channel.put(modalsActions.networkModalOpen());344 channel.put(modalsActions.loadingModalClosed());345 await saga.toPromise();346 // Assert347 expect(TracingManager.removeUpdateEventListener).toHaveBeenCalled();348 expect(TracingManager.exposed).toHaveBeenCalled();349 expect(TracingManager.exposed).toHaveBeenCalledWith(code);350 expect(dispatched).toHaveLength(6);351 expect(dispatched).toEqual([352 accountActions.submitDiagnosisPending(),353 modalsActions.openLoadingModal(),354 accountActions.setInfectionStatus(INFECTION_STATUS.INFECTED),355 accountActions.setTracingEnabled(false),356 accountActions.submitDiagnosisDone(),357 modalsActions.closeLoadingModal(),358 ]);359 });360 it('should not report code when exposed returns cancelled', async () => {361 // Prepare362 TracingManager.exposed.mockImplementation(() => Promise.resolve(GAEN_RESULTS.EN_CANCELLED));363 // Execute364 const channel = stdChannel();365 const dispatched = [];366 const saga = runSaga({367 channel,368 dispatch: (action) => dispatched.push(action),369 getState: () => ({370 services: {371 network: true,372 },373 }),374 }, submitDiagnosis, { payload: code });375 channel.put(modalsActions.networkModalOpen());376 channel.put(modalsActions.loadingModalClosed());377 await saga.toPromise();378 // Assert379 expect(Alert.alert).toHaveBeenCalled();380 expect(Alert.alert).toHaveBeenCalledWith(381 i18n.translate('common.dialogs.gaen.export.title'),382 i18n.translate('common.dialogs.gaen.export.description'),383 [384 {385 text: i18n.translate('common.actions.ok'),386 style: 'default',387 },388 ],389 );390 expect(TracingManager.exposed).toHaveBeenCalled();391 expect(TracingManager.exposed).toHaveBeenCalledWith(code);392 expect(dispatched).toHaveLength(4);393 expect(dispatched).toEqual([394 accountActions.submitDiagnosisPending(),395 modalsActions.openLoadingModal(),396 accountActions.submitDiagnosisDone(),397 modalsActions.closeLoadingModal(),398 ]);399 });400 it('should not report code when exposed throws an error', async () => {401 // Prepare402 TracingManager.exposed.mockImplementation(() => Promise.reject(GAEN_RESULTS.EN_FAILED));403 // Execute404 const channel = stdChannel();405 const dispatched = [];406 const saga = runSaga({407 channel,408 dispatch: (action) => dispatched.push(action),409 getState: () => ({410 services: {411 network: true,412 },413 }),414 }, submitDiagnosis, { payload: code });415 channel.put(modalsActions.networkModalOpen());416 channel.put(modalsActions.loadingModalClosed());417 channel.put(modalsActions.serverErrorModalOpen());418 await saga.toPromise();419 // Assert420 expect(TracingManager.exposed).toHaveBeenCalled();421 expect(TracingManager.exposed).toHaveBeenCalledWith(code);422 expect(dispatched).toHaveLength(6);423 expect(dispatched).toEqual([424 accountActions.submitDiagnosisPending(),425 modalsActions.openLoadingModal(),426 accountActions.submitDiagnosisDone(),427 modalsActions.closeLoadingModal(),428 accountActions.submitDiagnosisError(i18n.translate('common.errors.general')),429 modalsActions.openServerErrorModal(),430 ]);431 });432 });433 describe('Switch Tracing', () => {434 afterEach(() => {435 jest.resetAllMocks();436 });437 it('should stop tracing when tracing is enabled', async () => {438 // Execute439 const channel = stdChannel();440 const dispatched = [];441 const saga = runSaga({442 channel,443 dispatch: (action) => dispatched.push(action),444 getState: () => ({445 account: {446 tracingEnabled: true,447 },448 }),449 }, switchTracing);450 channel.put(accountActions.stopTracingResult(TRACING_RESULTS.SUCCESS));451 await saga.toPromise();452 // Assert453 expect(dispatched).toHaveLength(3);454 expect(dispatched).toEqual([455 accountActions.stopTracing(),456 accountActions.setTracingEnabled(false),457 accountActions.setErrors([]),458 ]);459 });460 it('should start tracing when all permissions are granted and start tracing returns success', async () => {461 // Execute462 const channel = stdChannel();463 const dispatched = [];464 const saga = runSaga({465 channel,466 dispatch: (action) => dispatched.push(action),467 getState: () => ({468 account: {469 tracingEnabled: false,470 },471 }),472 }, switchTracing);473 channel.put(permissionsActions.checkAllPermissionsResult(true));474 channel.put(accountActions.startTracingResult(TRACING_RESULTS.SUCCESS));475 await saga.toPromise();476 // Assert477 expect(dispatched).toHaveLength(3);478 expect(dispatched).toEqual([479 permissionsActions.checkAllPermissions(),480 accountActions.startTracing(),481 accountActions.setTracingEnabled(true),482 ]);483 });484 it('should not start tracing when permissions are denied', async () => {485 // Execute486 const channel = stdChannel();487 const dispatched = [];488 const saga = runSaga({489 channel,490 dispatch: (action) => dispatched.push(action),491 getState: () => ({492 account: {493 tracingEnabled: false,494 },495 }),496 }, switchTracing);497 channel.put(permissionsActions.checkAllPermissionsResult(false));498 channel.put(permissionsActions.requestAllPermissionsResult(false));499 await saga.toPromise();500 // Assert501 expect(Alert.alert).toHaveBeenCalled();502 expect(Alert.alert).toHaveBeenCalledWith(503 i18n.translate('common.dialogs.permissions.title'),504 i18n.translate('common.dialogs.permissions.description'),505 [506 {507 text: i18n.translate('common.actions.ok'),508 style: 'default',509 },510 ],511 );512 expect(dispatched).toHaveLength(3);513 expect(dispatched).toEqual([514 permissionsActions.checkAllPermissions(),515 permissionsActions.requestAllPermissions(),516 accountActions.setTracingEnabled(false),517 ]);518 });519 it('should not start tracing when start tracing not returns success', async () => {520 // Execute521 const channel = stdChannel();522 const dispatched = [];523 const saga = runSaga({524 channel,525 dispatch: (action) => dispatched.push(action),526 getState: () => ({527 account: {528 tracingEnabled: false,529 },530 }),531 }, switchTracing);532 channel.put(permissionsActions.checkAllPermissionsResult(true));533 channel.put(accountActions.startTracingResult(TRACING_RESULTS.FAILED));534 await saga.toPromise();535 // Assert536 expect(dispatched).toHaveLength(3);537 expect(dispatched).toEqual([538 permissionsActions.checkAllPermissions(),539 accountActions.startTracing(),540 accountActions.setTracingEnabled(false),541 ]);542 });543 });544 describe('Update Status', () => {545 afterEach(() => {546 jest.resetAllMocks();547 });548 it('should update status on redux', async () => {549 // Prepare550 TracingManager.isTracingEnabled.mockImplementation(() => Promise.resolve(false));551 const newState = {552 lastSyncDate: Moment().toJSON(),553 infectionStatus: 2,554 exposureDays: [],555 errors: [],556 };557 // Execute558 const channel = stdChannel();559 const dispatched = [];560 await runSaga({561 channel,562 dispatch: (action) => dispatched.push(action),563 getState: () => ({564 account: {565 status: defaultStatus,566 },567 }),568 }, updateStatus, { payload: newState }).toPromise();569 // Assert570 expect(TracingManager.isTracingEnabled).toHaveBeenCalled();571 expect(dispatched).toHaveLength(2);572 expect(dispatched).toEqual([573 accountActions.setStatus(newState),574 accountActions.updateStatusResult(newState),575 ]);576 });577 it('should deactivate tracing enabled when GAEN is deactivated', async () => {578 // Prepare579 TracingManager.isTracingEnabled.mockImplementation(() => Promise.resolve(true));580 const newState = {581 lastSyncDate: Moment().toJSON(),582 infectionStatus: 2,583 exposureDays: [],584 errors: [585 ERRORS[Platform.OS].GAEN_UNEXPECTEDLY_DISABLED,586 ],587 };588 // Execute589 const channel = stdChannel();590 const dispatched = [];591 await runSaga({592 channel,593 dispatch: (action) => dispatched.push(action),594 }, updateStatus, { payload: newState }).toPromise();595 // Assert596 expect(TracingManager.isTracingEnabled).not.toHaveBeenCalled();597 expect(dispatched).toHaveLength(3);598 expect(dispatched).toEqual([599 accountActions.setTracingEnabled(false),600 accountActions.setStatus(newState),601 accountActions.updateStatusResult(newState),602 ]);603 });604 it('should activate tracing enabled when GAEN is activated and tracing is enabled', async () => {605 // Prepare606 TracingManager.isTracingEnabled.mockImplementation(() => Promise.resolve(true));607 const newState = {608 lastSyncDate: Moment().toJSON(),609 infectionStatus: 2,610 exposureDays: [],611 errors: [],612 };613 // Execute614 const channel = stdChannel();615 const dispatched = [];616 await runSaga({617 channel,618 dispatch: (action) => dispatched.push(action),619 }, updateStatus, { payload: newState }).toPromise();620 // Assert621 expect(TracingManager.isTracingEnabled).toHaveBeenCalled();622 expect(dispatched).toHaveLength(3);623 expect(dispatched).toEqual([624 accountActions.setTracingEnabled(true),625 accountActions.setStatus(newState),626 accountActions.updateStatusResult(newState),627 ]);628 });629 it('should reset infection status when last exposure was 14 days ago', async () => {630 // Prepare631 TracingManager.isTracingEnabled.mockImplementation(() => Promise.resolve(false));632 const newState = {633 lastSyncDate: Moment().toJSON(),634 infectionStatus: 1,635 exposureDays: [{636 exposedDate: Moment().startOf('day').subtract(15, 'days'),637 }],638 errors: [],639 };640 // Execute641 const channel = stdChannel();642 const dispatched = [];643 await runSaga({644 channel,645 dispatch: (action) => dispatched.push(action),646 getState: () => ({647 account: {648 status: defaultStatus,649 },650 }),651 }, updateStatus, { payload: newState }).toPromise();652 // Assert653 expect(TracingManager.isTracingEnabled).toHaveBeenCalled();654 expect(TracingManager.resetExposureDays).toHaveBeenCalled();655 expect(dispatched).toHaveLength(2);656 expect(dispatched).toEqual([657 accountActions.setStatus(newState),658 accountActions.updateStatusResult(newState),659 ]);660 });661 it('should not reset infection status when last exposure was not 14 days ago', async () => {662 // Prepare663 TracingManager.isTracingEnabled.mockImplementation(() => Promise.resolve(false));664 const newState = {665 lastSyncDate: Moment().toJSON(),666 infectionStatus: 1,667 exposureDays: [{668 exposedDate: Moment().startOf('day').subtract(13, 'days'),669 }],670 errors: [],671 };672 // Execute673 const channel = stdChannel();674 const dispatched = [];675 await runSaga({676 channel,677 dispatch: (action) => dispatched.push(action),678 getState: () => ({679 account: {680 status: defaultStatus,681 },682 }),683 }, updateStatus, { payload: newState }).toPromise();684 // Assert685 expect(TracingManager.isTracingEnabled).toHaveBeenCalled();686 expect(TracingManager.resetExposureDays).not.toHaveBeenCalled();687 expect(dispatched).toHaveLength(2);688 expect(dispatched).toEqual([689 accountActions.setStatus(newState),690 accountActions.updateStatusResult(newState),691 ]);692 });693 });694 describe('Set Errors', () => {695 it('should set errors on redux', async () => {696 // Execute697 const channel = stdChannel();698 const dispatched = [];699 await runSaga({700 channel,701 dispatch: (action) => dispatched.push(action),702 getState: () => ({703 account: {704 status: defaultStatus,705 },706 }),707 }, setErrors, { payload: [] }).toPromise();708 // Assert709 expect(dispatched).toHaveLength(1);710 expect(dispatched).toEqual([711 accountActions.updateStatus(({712 ...defaultStatus,713 errors: [],714 })),715 ]);716 });717 });718 describe('Set Infection Status', () => {719 it('should set infection status on redux', async () => {720 // Execute721 const channel = stdChannel();722 const dispatched = [];723 await runSaga({724 channel,725 dispatch: (action) => dispatched.push(action),726 getState: () => ({727 account: {728 status: defaultStatus,729 },730 }),731 }, setInfectionStatus, { payload: INFECTION_STATUS.EXPOSED }).toPromise();732 // Assert733 expect(dispatched).toHaveLength(1);734 expect(dispatched).toEqual([735 accountActions.updateStatus(({736 ...defaultStatus,737 errors: [],738 infectionStatus: INFECTION_STATUS.EXPOSED,739 })),740 ]);741 });742 });743 describe('Update Language', () => {744 it('should set language and restart device', async () => {745 // Execute746 const channel = stdChannel();747 const dispatched = [];748 await runSaga({749 channel,750 dispatch: (action) => dispatched.push(action),751 }, updateLanguage, { payload: languages.PT.languageTag }).toPromise();752 // Assert753 expect(SplashScreen.show).toHaveBeenCalled();754 expect(RNRestart.Restart).toHaveBeenCalled();755 expect(dispatched).toHaveLength(1);756 expect(dispatched).toEqual([accountActions.setLanguage(languages.PT)]);757 });758 });759 describe('Enable Exposure Notifications', () => {760 it('should start tracing on Android', async () => {761 // Prepare762 Platform.OS = 'android';763 // Execute764 const channel = stdChannel();765 const dispatched = [];766 const saga = runSaga({767 channel,768 dispatch: (action) => dispatched.push(action),769 }, enableExposureNotifications);770 channel.put(accountActions.startTracingResult(TRACING_RESULTS.SUCCESS));771 await saga.toPromise();772 // Assert773 expect(Linking.openURL).not.toHaveBeenCalled();774 expect(dispatched).toHaveLength(1);775 expect(dispatched).toEqual([accountActions.startTracing()]);776 });777 it('should start tracing on iOS and start returns success', async () => {778 // Prepare779 Platform.OS = 'ios';780 // Execute781 const channel = stdChannel();782 const dispatched = [];783 const saga = runSaga({784 channel,785 dispatch: (action) => dispatched.push(action),786 }, enableExposureNotifications);787 channel.put(accountActions.startTracingResult(TRACING_RESULTS.SUCCESS));788 await saga.toPromise();789 // Assert790 expect(Linking.openURL).not.toHaveBeenCalled();791 expect(dispatched).toHaveLength(1);792 expect(dispatched).toEqual([accountActions.startTracing()]);793 });794 it('should start tracing on iOS and start returns fails', async () => {795 // Prepare796 Platform.OS = 'ios';797 Linking.openURL.mockImplementation(() => Promise.resolve());798 // Execute799 const channel = stdChannel();800 const dispatched = [];801 const saga = runSaga({802 channel,803 dispatch: (action) => dispatched.push(action),804 }, enableExposureNotifications);805 channel.put(accountActions.startTracingResult(TRACING_RESULTS.FAILED));806 await saga.toPromise();807 // Assert808 expect(Linking.openURL).toHaveBeenCalled();809 expect(Linking.openURL).toHaveBeenCalledWith('app-settings://');810 expect(dispatched).toHaveLength(1);811 expect(dispatched).toEqual([accountActions.startTracing()]);812 });813 });...
browserDispatcher.js
Source:browserDispatcher.js
...57 return {58 session: new _cdpSessionDispatcher.CDPSessionDispatcher(this._scope, await crBrowser.newBrowserCDPSession())59 };60 }61 async startTracing(params) {62 if (!this._object.options.isChromium) throw new Error(`Tracing is only available in Chromium`);63 const crBrowser = this._object;64 await crBrowser.startTracing(params.page ? params.page._object : undefined, params);65 }66 async stopTracing() {67 if (!this._object.options.isChromium) throw new Error(`Tracing is only available in Chromium`);68 const crBrowser = this._object;69 const buffer = await crBrowser.stopTracing();70 return {71 binary: buffer.toString('base64')72 };73 }74} // This class implements multiplexing browser dispatchers over a single Browser instance.75exports.BrowserDispatcher = BrowserDispatcher;76class ConnectedBrowserDispatcher extends _dispatcher.Dispatcher {77 constructor(scope, browser) {78 super(scope, browser, 'Browser', {79 version: browser.version(),80 name: browser.options.name81 }, true); // When we have a remotely-connected browser, each client gets a fresh Selector instance,82 // so that two clients do not interfere between each other.83 this._type_Browser = true;84 this._contexts = new Set();85 this.selectors = void 0;86 this.selectors = new _selectors.Selectors();87 }88 async newContext(params, metadata) {89 if (params.recordVideo) params.recordVideo.dir = this._object.options.artifactsDir;90 const context = await this._object.newContext(params);91 this._contexts.add(context);92 context._setSelectors(this.selectors);93 context.on(_browserContext.BrowserContext.Events.Close, () => this._contexts.delete(context));94 if (params.storageState) await context.setStorageState(metadata, params.storageState);95 return {96 context: new _browserContextDispatcher.BrowserContextDispatcher(this._scope, context)97 };98 }99 async close() {// Client should not send us Browser.close.100 }101 async killForTests() {// Client should not send us Browser.killForTests.102 }103 async newBrowserCDPSession() {104 if (!this._object.options.isChromium) throw new Error(`CDP session is only available in Chromium`);105 const crBrowser = this._object;106 return {107 session: new _cdpSessionDispatcher.CDPSessionDispatcher(this._scope, await crBrowser.newBrowserCDPSession())108 };109 }110 async startTracing(params) {111 if (!this._object.options.isChromium) throw new Error(`Tracing is only available in Chromium`);112 const crBrowser = this._object;113 await crBrowser.startTracing(params.page ? params.page._object : undefined, params);114 }115 async stopTracing() {116 if (!this._object.options.isChromium) throw new Error(`Tracing is only available in Chromium`);117 const crBrowser = this._object;118 const buffer = await crBrowser.stopTracing();119 return {120 binary: buffer.toString('base64')121 };122 }123 async cleanupContexts() {124 await Promise.all(Array.from(this._contexts).map(context => context.close((0, _instrumentation.internalCallMetadata)())));125 }126}127exports.ConnectedBrowserDispatcher = ConnectedBrowserDispatcher;
XMLHttpRequestTracing.user.js
Source:XMLHttpRequestTracing.user.js
...95 XMLHttpRequest.prototype.send = newSend;
96}
97
98// GM_registerMenuCommand("Trace XmlHttpRequest", startTracing);
...
index.js
Source:index.js
...22 PHASE_INIT_STATE,23 startTracing,24 stopTracing25} from '../profiler';26startTracing(PHASE_APP_INIT);27/**28 * ViewModel constructor29 * @param {Object} options the options of ViewModel30 * @return {ViewModel} ViewModel instance31 */32export function ViewModel(options) {33 startTracing(PHASE_FWK_EVAL);34 if (!(this instanceof ViewModel)) {35 return new ViewModel(options);36 }37 const vm = (this._vm = this);38 if (Object.prototype.toString.call(options) === '[object Object]') {39 Object.keys(options).forEach(key => {40 const value = options[key];41 if (key === 'render') {42 vm.$render = value;43 } else if (key === 'data') {44 initState(vm, value);45 } else if (key === 'styleSheet') {46 initStyleSheet(value);47 } else if (typeof value === 'function') {48 vm[key] = value.bind(vm);49 } else {50 // do nothing51 }52 });53 }54 stopTracing();55}56ViewModel.prototype.$watch = function(getter, callback, meta) {57 return new Observer(this, getter, callback, meta);58};59/**60 * initialize the state of ViewModel instance61 * @param {ViewModel} vm ViewModel instance62 * @param {Object} data the data to be observe63 */64function initState(vm, data) {65 startTracing(PHASE_INIT_STATE);66 startTracing(PHASE_INIT_DATA_GET_DATA);67 if (typeof data === 'function') {68 data = data.call(vm, vm);69 }70 stopTracing(); // PHASE_INIT_DATA_GET_DATA71 startTracing(PHASE_INIT_DATA_PROXY);72 Object.keys(data).forEach(key => proxy(vm, data, key));73 stopTracing(); // PHASE_INIT_DATA_PROXY74 startTracing(PHASE_INIT_DATA_OBSERVE);75 Subject.of(data);76 stopTracing(); // PHASE_INIT_DATA_OBSERVE77 stopTracing(); // PHASE_INIT_STATE78}79/**80 * proxy data81 * @param {ViewModel} target ViewModel instance82 * @param {Object} source the data to be proxy83 * @param {String} key the key to be proxy84 */85function proxy(target, source, key) {86 Object.defineProperty(target, key, {87 enumerable: false,88 configurable: true,...
Tracing.spec.js
Source:Tracing.spec.js
...14afterEach(async () => {15 await closeBrowser();16});17test('Should return speedindex and perceptualSpeedIndex', async () => {18 await startTracing();19 await goto('https://github.com/');20 await endTracing();21 const { speedIndex, perceptualSpeedIndex } = await getSpeedIndex();22 expect(speedIndex).toBeTruthy();23 expect(perceptualSpeedIndex).toBeTruthy();24});25test('Should return performance metric', async () => {26 await startTracing();27 await goto('https://google.com');28 await endTracing();29 const performance = await getPerformanceMetrics();30 expect(performance.firstPaint).toBeLessThan(5 * 1000);31});32test('Should return unused coverage', async () => {33 await startCssTracing();34 await goto('http://github.com/macku/page-coverage');35 const cssCoverage = await stopCssTracing();36 expect(cssCoverage[0].type).toBe('CSS');37 expect(cssCoverage.length).toBeGreaterThan(1);38});39test('should measure page load time for second instance', async () => {40 await startTracing();41 await goto(`www.bing.com`);42 await endTracing();43 const performanceMetrics = await getPerformanceMetrics();44 expect(performanceMetrics.firstPaint).toBeLessThan(5 * 1000);...
App.js
Source:App.js
1import logo from './logo.svg';2import './App.css';3import LandingPage from "./components/LandingPage/LandingPage";4import DetectFaces from "./components/DetectFaces/DetectFaces";5import StartTracing from "./components/StartTracing/StartTracing";6import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';7const App = () => {8return (9 <div className='App'>10 <Router>11 <Switch>12 {/* <Router> */}13 <Route path='/' exact component={LandingPage} />14 <Route path='/Upload' exact component={StartTracing} />15 <Route path='/Detect' exact component={DetectFaces} />16 {/* </Router> */}17 </Switch>18 </Router>19 </div>20);21}22export default App;23//// OLD CODE24// import LandingPage from "./pages/LandingPage";25// import DetectFaces from "./pages/DetectFaces";26// import StartTracing from "./pages/StartTracing";27// import "./App.css";28// import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';29// const App = () => {30// return (31// <>32// <Router>33// <div className="App">34// <Route exact path="/" component={LandingPage}></Route>35// <Route exact path="/detect_faces" component={DetectFaces}></Route>36// <Route exact path="/start_tracing" component={StartTracing}></Route>37// </div>38// </Router>39// </>40// );...
diagnosticPluginDemo.js
Source:diagnosticPluginDemo.js
...3loadPlugin(ID, clientHandler);4(async () => {5 try {6 await openBrowser();7 await startTracing();8 await goto("https://www.youtube.com");9 await endTracing();10 await getTracingLogs();11 await getPerformanceMetrics();12 } catch (e) {13 console.error(e);14 } finally {15 await closeBrowser();16 }...
directors.js
Source:directors.js
1const { startTracing } = require('@splunk/otel');2startTracing({3 serviceName: 'directors-microservice',4});5const express = require('express')6const app = express()7const port = 30018app.get('/directors', async function (req, res) {9 res.type('json')10 res.send(({directors: [11 { name: 'Joe Alves'}, 12 { name: 'Ian Toynton'},13 { name: 'Steven Spielberg'},14 ]}))15})16app.listen( port, () => { console.log(`Listening at http://localhost:${port}`)}...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 await context.tracing.start({ screenshots: true, snapshots: true });6 const page = await context.newPage();7 await page.screenshot({ path: `example.png` });8 await context.tracing.stop({ path: `trace.zip` });9 await browser.close();10})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 await context.tracing.start({ screenshots: true, snapshots: true });6 const page = await context.newPage();7 await page.fill('input[aria-label="Search"]', 'playwright');8 await page.press('input[aria-label="Search"]', 'Enter');9 await page.screenshot({ path: `example.png` });10 await context.tracing.stop({ path: `trace.zip` });11 await browser.close();12})();
Using AI Code Generation
1const fs = require('fs');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.tracing.start({ screenshots: true, snapshots: true });8 await page.tracing.stop({ path: 'trace.zip' });9 await browser.close();10})();11const fs = require('fs');12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 await page.tracing.start({ screenshots: true, snapshots: true });18 await page.tracing.stop({ path: 'trace.zip' });19 await browser.close();20})();21const fs = require('fs');22const { chromium } = require('playwright');23(async () => {24 const browser = await chromium.launch();25 const context = await browser.newContext();26 const page = await context.newPage();27 await page.tracing.start({ screenshots: true, snapshots: true });28 await page.tracing.stop({ path: 'trace.zip' });29 await browser.close();30})();
Using AI Code Generation
1const { chromium } = require('playwright');2const fs = require('fs');3const path = require('path');4(async () => {5 const browser = await chromium.launch({ headless: false });6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.tracing.start({ screenshots: true, snapshots: true });9 await page.tracing.stop({ path: 'trace.zip' });10 await browser.close();11})();
Using AI Code Generation
1const { startTracing } = require('@playwright/test/lib/server/trace/recorder');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 await startTracing(page, { screenshots: true, snapshots: true });7 await page.screenshot({ path: 'example.png' });8 await browser.close();9})();
Using AI Code Generation
1const fs = require('fs');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.tracing.start({ screenshots: true, snapshots: true });8 await page.tracing.stop({ path: 'trace.zip' });9 await browser.close();10})();11const fs = require('fs');12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 await page.tracing.start({ screenshots: true, snapshots: true });18 await page.tracing.stop({ path: 'trace.zip' });19 await browser.close();20})();21const fs = require('fs');22const { chromium } = require('playwright');23(async () => {24 const browser = await chromium.launch();25 const context = await browser.newContext();26 const page = await context.newPage();27 await page.tracing.start({ screenshots: true, snapshots: true });28 await page.tracing.stop({ path: 'trace.zip' });29 await browser.close();30})();
Using AI Code Generation
1const { chromium } = require('playwright');2const fs = require('fs');3const path = require('path');4(async () => {5 const browser = await chromium.launch({ headless: false });6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.tracing.start({ screenshots: true, snapshots: true });9 await page.tracing.stop({ path: 'trace.zip' });10 await browser.close();11})();
Using AI Code Generation
1const { startTracing } = require('@playwright/test/lib/server/trace/recorder');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 await startTracing(page, { screenshots: true, snapshots: true });7 await page.screenshot({ path: 'example.png' });8 await browser.close();9})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false, slowMo: 50 });4 const context = await browser.newContext();5 await context.tracing.start({ screenshots: true, snapshots: true });6 const page = await context.newPage();7 await page.screenshot({ path: `example.png` });8 await context.tracing.stop({ path: `trace.zip` });9 await browser.close();10})();
Using AI Code Generation
1const { chromium } = require('playwright');2const { startTracing } = require('playwright/lib/server/chromium/crPage');3(async () => {4 const browser = await chromium.launch({ headless: false });5 const context = await browser.newContext();6 const page = await context.newPage();7 await startTracing(page, {8 });9 await page.screenshot({ path: `example.png` });10 await page.close();11 await browser.close();12})();13{14 "metadata": {15 },16 {17 "args": {18 "snapshot": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAXAAAABgCAY
Using AI Code Generation
1const { chromium } = require('playwright');2const { startTracing } = require('playwright/lib/server/chromium/crTracing');3const fs = require('fs');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 const tracing = await startTracing(page, fs.createWriteStream('trace.zip'));9 await tracing.stop();10 await browser.close();11})();12#### tracing.stop([options])13### method: Page.tracing.start([options])14const tracing = await page.tracing.start({ screenshots: true, snapshots: true });15await tracing.stop();16### method: Page.tracing.startChunk([options])
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!