Best JavaScript code snippet using karma
CFRPageActions.test.js
Source:CFRPageActions.test.js
1import { CFRPageActions, PageAction } from "lib/CFRPageActions.jsm";2import { FAKE_RECOMMENDATION } from "./constants";3import { GlobalOverrider } from "test/unit/utils";4describe("CFRPageActions", () => {5 let sandbox;6 let clock;7 let fakeRecommendation;8 let fakeHost;9 let fakeBrowser;10 let dispatchStub;11 let globals;12 let containerElem;13 let elements;14 let announceStub;15 let remoteL10n;16 const elementIDs = [17 "urlbar",18 "urlbar-input",19 "contextual-feature-recommendation",20 "cfr-button",21 "cfr-label",22 "contextual-feature-recommendation-notification",23 "cfr-notification-header-label",24 "cfr-notification-header-link",25 "cfr-notification-header-image",26 "cfr-notification-author",27 "cfr-notification-footer",28 "cfr-notification-footer-text",29 "cfr-notification-footer-filled-stars",30 "cfr-notification-footer-empty-stars",31 "cfr-notification-footer-users",32 "cfr-notification-footer-spacer",33 "cfr-notification-footer-learn-more-link",34 "cfr-notification-footer-pintab-animation-container",35 "cfr-notification-footer-animation-button",36 "cfr-notification-footer-animation-label",37 ];38 const elementClassNames = ["popup-notification-body-container"];39 beforeEach(() => {40 sandbox = sinon.createSandbox();41 clock = sandbox.useFakeTimers();42 announceStub = sandbox.stub();43 const A11yUtils = { announce: announceStub };44 fakeRecommendation = { ...FAKE_RECOMMENDATION };45 fakeHost = "mozilla.org";46 fakeBrowser = {47 documentURI: {48 scheme: "https",49 host: fakeHost,50 },51 ownerGlobal: window,52 };53 dispatchStub = sandbox.stub();54 remoteL10n = {55 l10n: {},56 reloadL10n: sandbox.stub(),57 };58 const gURLBar = document.createElement("div");59 gURLBar.textbox = document.createElement("div");60 globals = new GlobalOverrider();61 globals.set({62 RemoteL10n: remoteL10n,63 promiseDocumentFlushed: sandbox64 .stub()65 .callsFake(fn => Promise.resolve(fn())),66 PopupNotifications: {67 show: sandbox.stub(),68 remove: sandbox.stub(),69 },70 PrivateBrowsingUtils: { isWindowPrivate: sandbox.stub().returns(false) },71 gBrowser: { selectedBrowser: fakeBrowser },72 A11yUtils,73 gURLBar,74 });75 document.createXULElement = document.createElement;76 elements = {};77 const [body] = document.getElementsByTagName("body");78 containerElem = document.createElement("div");79 body.appendChild(containerElem);80 for (const id of elementIDs) {81 const elem = document.createElement("div");82 elem.setAttribute("id", id);83 containerElem.appendChild(elem);84 elements[id] = elem;85 }86 for (const className of elementClassNames) {87 const elem = document.createElement("div");88 elem.setAttribute("class", className);89 containerElem.appendChild(elem);90 elements[className] = elem;91 }92 });93 afterEach(() => {94 CFRPageActions.clearRecommendations();95 containerElem.remove();96 sandbox.restore();97 globals.restore();98 });99 describe("PageAction", () => {100 let pageAction;101 beforeEach(() => {102 pageAction = new PageAction(window, dispatchStub);103 });104 describe("#addImpression", () => {105 it("should call _sendTelemetry with the impression payload", () => {106 const recommendation = {107 id: "foo",108 content: { bucket_id: "bar" },109 };110 sandbox.spy(pageAction, "_sendTelemetry");111 pageAction.addImpression(recommendation);112 assert.calledWith(pageAction._sendTelemetry, {113 message_id: "foo",114 bucket_id: "bar",115 event: "IMPRESSION",116 });117 });118 it("should include modelVersion if presented in the message", () => {119 const recommendation = {120 id: "foo",121 content: { bucket_id: "bar" },122 personalizedModelVersion: "model_version_1",123 };124 sandbox.spy(pageAction, "_sendTelemetry");125 pageAction.addImpression(recommendation);126 assert.calledWith(pageAction._sendTelemetry, {127 message_id: "foo",128 bucket_id: "bar",129 event: "IMPRESSION",130 event_context: {131 modelVersion: "model_version_1",132 },133 });134 });135 });136 describe("#showAddressBarNotifier", () => {137 it("should un-hideAddressBarNotifier the element and set the right label value", async () => {138 await pageAction.showAddressBarNotifier(fakeRecommendation);139 assert.isFalse(pageAction.container.hidden);140 assert.equal(141 pageAction.label.value,142 fakeRecommendation.content.notification_text143 );144 });145 it("should wait for the document layout to flush", async () => {146 sandbox.spy(pageAction.label, "getClientRects");147 await pageAction.showAddressBarNotifier(fakeRecommendation);148 assert.calledOnce(global.promiseDocumentFlushed);149 assert.callOrder(150 global.promiseDocumentFlushed,151 pageAction.label.getClientRects152 );153 });154 it("should set the CSS variable --cfr-label-width correctly", async () => {155 await pageAction.showAddressBarNotifier(fakeRecommendation);156 const expectedWidth = pageAction.label.getClientRects()[0].width;157 assert.equal(158 pageAction.urlbarinput.style.getPropertyValue("--cfr-label-width"),159 `${expectedWidth}px`160 );161 });162 it("should cause an expansion, and dispatch an impression if `expand` is true", async () => {163 sandbox.spy(pageAction, "_clearScheduledStateChanges");164 sandbox.spy(pageAction, "_expand");165 sandbox.spy(pageAction, "_dispatchImpression");166 await pageAction.showAddressBarNotifier(fakeRecommendation);167 assert.notCalled(pageAction._dispatchImpression);168 clock.tick(1001);169 assert.notEqual(170 pageAction.urlbarinput.getAttribute("cfr-recommendation-state"),171 "expanded"172 );173 await pageAction.showAddressBarNotifier(fakeRecommendation, true);174 assert.calledOnce(pageAction._clearScheduledStateChanges);175 clock.tick(1001);176 assert.equal(177 pageAction.urlbarinput.getAttribute("cfr-recommendation-state"),178 "expanded"179 );180 assert.calledOnce(pageAction._dispatchImpression);181 assert.calledWith(pageAction._dispatchImpression, fakeRecommendation);182 });183 it("should send telemetry if `expand` is true and the id and bucket_id are provided", async () => {184 await pageAction.showAddressBarNotifier(fakeRecommendation, true);185 assert.calledWith(dispatchStub, {186 type: "DOORHANGER_TELEMETRY",187 data: {188 action: "cfr_user_event",189 source: "CFR",190 message_id: fakeRecommendation.id,191 bucket_id: fakeRecommendation.content.bucket_id,192 event: "IMPRESSION",193 },194 });195 });196 });197 describe("#hideAddressBarNotifier", () => {198 it("should hideAddressBarNotifier the container, cancel any state changes, and remove the state attribute", () => {199 sandbox.spy(pageAction, "_clearScheduledStateChanges");200 pageAction.hideAddressBarNotifier();201 assert.isTrue(pageAction.container.hidden);202 assert.calledOnce(pageAction._clearScheduledStateChanges);203 assert.isNull(204 pageAction.urlbar.getAttribute("cfr-recommendation-state")205 );206 });207 it("should remove the `currentNotification`", () => {208 const notification = {};209 pageAction.currentNotification = notification;210 pageAction.hideAddressBarNotifier();211 assert.calledWith(global.PopupNotifications.remove, notification);212 });213 });214 describe("#_expand", () => {215 beforeEach(() => {216 pageAction._clearScheduledStateChanges();217 pageAction.urlbar.removeAttribute("cfr-recommendation-state");218 });219 it("without a delay, should clear other state changes and set the state to 'expanded'", () => {220 sandbox.spy(pageAction, "_clearScheduledStateChanges");221 pageAction._expand();222 assert.calledOnce(pageAction._clearScheduledStateChanges);223 assert.equal(224 pageAction.urlbarinput.getAttribute("cfr-recommendation-state"),225 "expanded"226 );227 });228 it("with a delay, should set the expanded state after the correct amount of time", () => {229 const delay = 1234;230 pageAction._expand(delay);231 // We expect that an expansion has been scheduled232 assert.lengthOf(pageAction.stateTransitionTimeoutIDs, 1);233 clock.tick(delay + 1);234 assert.equal(235 pageAction.urlbarinput.getAttribute("cfr-recommendation-state"),236 "expanded"237 );238 });239 });240 describe("#_collapse", () => {241 beforeEach(() => {242 pageAction._clearScheduledStateChanges();243 pageAction.urlbar.removeAttribute("cfr-recommendation-state");244 });245 it("without a delay, should clear other state changes and set the state to collapsed only if it's already expanded", () => {246 sandbox.spy(pageAction, "_clearScheduledStateChanges");247 pageAction._collapse();248 assert.calledOnce(pageAction._clearScheduledStateChanges);249 assert.isNull(250 pageAction.urlbarinput.getAttribute("cfr-recommendation-state")251 );252 pageAction.urlbarinput.setAttribute(253 "cfr-recommendation-state",254 "expanded"255 );256 pageAction._collapse();257 assert.equal(258 pageAction.urlbarinput.getAttribute("cfr-recommendation-state"),259 "collapsed"260 );261 });262 it("with a delay, should set the collapsed state after the correct amount of time", () => {263 const delay = 1234;264 pageAction._collapse(delay);265 clock.tick(delay + 1);266 // The state was _not_ "expanded" and so should not have been set to "collapsed"267 assert.isNull(268 pageAction.urlbar.getAttribute("cfr-recommendation-state")269 );270 pageAction._expand();271 pageAction._collapse(delay);272 // We expect that a collapse has been scheduled273 assert.lengthOf(pageAction.stateTransitionTimeoutIDs, 1);274 clock.tick(delay + 1);275 // This time it was "expanded" so should now (after the delay) be "collapsed"276 assert.equal(277 pageAction.urlbarinput.getAttribute("cfr-recommendation-state"),278 "collapsed"279 );280 });281 });282 describe("#_clearScheduledStateChanges", () => {283 it("should call .clearTimeout on all stored timeoutIDs", () => {284 pageAction.stateTransitionTimeoutIDs = [42, 73, 1997];285 sandbox.spy(pageAction.window, "clearTimeout");286 pageAction._clearScheduledStateChanges();287 assert.calledThrice(pageAction.window.clearTimeout);288 assert.calledWith(pageAction.window.clearTimeout, 42);289 assert.calledWith(pageAction.window.clearTimeout, 73);290 assert.calledWith(pageAction.window.clearTimeout, 1997);291 });292 });293 describe("#_popupStateChange", () => {294 it("should collapse the notification on 'dismissed'", () => {295 pageAction._expand();296 pageAction._popupStateChange("dismissed");297 assert.equal(298 pageAction.urlbarinput.getAttribute("cfr-recommendation-state"),299 "collapsed"300 );301 });302 it("should remove the notification on 'removed'", () => {303 pageAction._expand();304 const fakeNotification = {};305 pageAction.currentNotification = fakeNotification;306 pageAction._popupStateChange("removed");307 assert.calledOnce(global.PopupNotifications.remove);308 assert.calledWith(global.PopupNotifications.remove, fakeNotification);309 });310 it("should do nothing for other states", () => {311 pageAction._popupStateChange("opened");312 assert.notCalled(global.PopupNotifications.remove);313 });314 });315 describe("#dispatchUserAction", () => {316 it("should call ._dispatchToASRouter with the right action", () => {317 const fakeAction = {};318 pageAction.dispatchUserAction(fakeAction);319 assert.calledOnce(dispatchStub);320 assert.calledWith(321 dispatchStub,322 { type: "USER_ACTION", data: fakeAction },323 { browser: fakeBrowser }324 );325 });326 });327 describe("#_dispatchImpression", () => {328 it("should call ._dispatchToASRouter with the right action", () => {329 pageAction._dispatchImpression("fake impression");330 assert.calledWith(dispatchStub, {331 type: "IMPRESSION",332 data: "fake impression",333 });334 });335 });336 describe("#_sendTelemetry", () => {337 it("should call ._dispatchToASRouter with the right action", () => {338 const fakePing = { message_id: 42 };339 pageAction._sendTelemetry(fakePing);340 assert.calledWith(dispatchStub, {341 type: "DOORHANGER_TELEMETRY",342 data: { action: "cfr_user_event", source: "CFR", message_id: 42 },343 });344 });345 });346 describe("#_blockMessage", () => {347 it("should call ._dispatchToASRouter with the right action", () => {348 pageAction._blockMessage("fake id");349 assert.calledOnce(dispatchStub);350 assert.calledWith(dispatchStub, {351 type: "BLOCK_MESSAGE_BY_ID",352 data: { id: "fake id" },353 });354 });355 });356 describe("#getStrings", () => {357 let formatMessagesStub;358 const localeStrings = [359 {360 value: "ä½ å¥½ä¸ç",361 attributes: [362 { name: "first_attr", value: 42 },363 { name: "second_attr", value: "some string" },364 { name: "third_attr", value: [1, 2, 3] },365 ],366 },367 ];368 beforeEach(() => {369 formatMessagesStub = sandbox370 .stub()371 .withArgs({ id: "hello_world" })372 .resolves(localeStrings);373 global.RemoteL10n.l10n.formatMessages = formatMessagesStub;374 });375 it("should return the argument if a string_id is not defined", async () => {376 assert.deepEqual(await pageAction.getStrings({}), {});377 assert.equal(await pageAction.getStrings("some string"), "some string");378 });379 it("should get the right locale string", async () => {380 assert.equal(381 await pageAction.getStrings({ string_id: "hello_world" }),382 localeStrings[0].value383 );384 });385 it("should return the right sub-attribute if specified", async () => {386 assert.equal(387 await pageAction.getStrings(388 { string_id: "hello_world" },389 "second_attr"390 ),391 "some string"392 );393 });394 it("should attach attributes to string overrides", async () => {395 const fromJson = { value: "Add Now", attributes: { accesskey: "A" } };396 const result = await pageAction.getStrings(fromJson);397 assert.equal(result, fromJson.value);398 assert.propertyVal(result.attributes, "accesskey", "A");399 });400 it("should return subAttributes when doing string overrides", async () => {401 const fromJson = { value: "Add Now", attributes: { accesskey: "A" } };402 const result = await pageAction.getStrings(fromJson, "accesskey");403 assert.equal(result, "A");404 });405 it("should resolve ftl strings and attach subAttributes", async () => {406 const fromFtl = { string_id: "cfr-doorhanger-extension-ok-button" };407 formatMessagesStub.resolves([408 { value: "Add Now", attributes: [{ name: "accesskey", value: "A" }] },409 ]);410 const result = await pageAction.getStrings(fromFtl);411 assert.equal(result, "Add Now");412 assert.propertyVal(result.attributes, "accesskey", "A");413 });414 it("should return subAttributes from ftl ids", async () => {415 const fromFtl = { string_id: "cfr-doorhanger-extension-ok-button" };416 formatMessagesStub.resolves([417 { value: "Add Now", attributes: [{ name: "accesskey", value: "A" }] },418 ]);419 const result = await pageAction.getStrings(fromFtl, "accesskey");420 assert.equal(result, "A");421 });422 it("should report an error when no attributes are present but subAttribute is requested", async () => {423 const fromJson = { value: "Foo" };424 const stub = sandbox.stub(global.Cu, "reportError");425 await pageAction.getStrings(fromJson, "accesskey");426 assert.calledOnce(stub);427 stub.restore();428 });429 });430 describe("#_showPopupOnClick", () => {431 let translateElementsStub;432 let setAttributesStub;433 let getStringsStub;434 beforeEach(async () => {435 CFRPageActions.PageActionMap.set(fakeBrowser.ownerGlobal, pageAction);436 await CFRPageActions.addRecommendation(437 fakeBrowser,438 fakeHost,439 fakeRecommendation,440 dispatchStub441 );442 getStringsStub = sandbox.stub(pageAction, "getStrings").resolves("");443 getStringsStub444 .callsFake(async a => a) // eslint-disable-line max-nested-callbacks445 .withArgs({ string_id: "primary_button_id" })446 .resolves({ value: "Primary Button", attributes: { accesskey: "p" } })447 .withArgs({ string_id: "secondary_button_id" })448 .resolves({449 value: "Secondary Button",450 attributes: { accesskey: "s" },451 })452 .withArgs({ string_id: "secondary_button_id_2" })453 .resolves({454 value: "Secondary Button 2",455 attributes: { accesskey: "a" },456 })457 .withArgs({ string_id: "secondary_button_id_3" })458 .resolves({459 value: "Secondary Button 3",460 attributes: { accesskey: "g" },461 })462 .withArgs(463 sinon.match({464 string_id: "cfr-doorhanger-extension-learn-more-link",465 })466 )467 .resolves("Learn more")468 .withArgs(469 sinon.match({ string_id: "cfr-doorhanger-extension-total-users" })470 )471 .callsFake(async ({ args }) => `${args.total} users`); // eslint-disable-line max-nested-callbacks472 translateElementsStub = sandbox.stub().resolves();473 setAttributesStub = sandbox.stub();474 global.RemoteL10n.l10n.setAttributes = setAttributesStub;475 global.RemoteL10n.l10n.translateElements = translateElementsStub;476 });477 it("should call `.hideAddressBarNotifier` and do nothing if there is no recommendation for the selected browser", async () => {478 sandbox.spy(pageAction, "hideAddressBarNotifier");479 CFRPageActions.RecommendationMap.delete(fakeBrowser);480 await pageAction._showPopupOnClick({});481 assert.calledOnce(pageAction.hideAddressBarNotifier);482 assert.notCalled(global.PopupNotifications.show);483 });484 it("should cancel any planned state changes", async () => {485 sandbox.spy(pageAction, "_clearScheduledStateChanges");486 assert.notCalled(pageAction._clearScheduledStateChanges);487 await pageAction._showPopupOnClick({});488 assert.calledOnce(pageAction._clearScheduledStateChanges);489 });490 it("should set the right text values", async () => {491 await pageAction._showPopupOnClick({});492 const headerLabel = elements["cfr-notification-header-label"];493 const headerLink = elements["cfr-notification-header-link"];494 const headerImage = elements["cfr-notification-header-image"];495 const footerText = elements["cfr-notification-footer-text"];496 const footerLink = elements["cfr-notification-footer-learn-more-link"];497 assert.equal(498 headerLabel.value,499 fakeRecommendation.content.heading_text500 );501 assert.isTrue(502 headerLink503 .getAttribute("href")504 .endsWith(fakeRecommendation.content.info_icon.sumo_path)505 );506 assert.equal(507 headerImage.getAttribute("tooltiptext"),508 fakeRecommendation.content.info_icon.label509 );510 assert.equal(footerText.textContent, fakeRecommendation.content.text);511 assert.equal(footerLink.value, "Learn more");512 assert.equal(513 footerLink.getAttribute("href"),514 fakeRecommendation.content.addon.amo_url515 );516 });517 it("should add the rating correctly", async () => {518 await pageAction._showPopupOnClick();519 const footerFilledStars =520 elements["cfr-notification-footer-filled-stars"];521 const footerEmptyStars =522 elements["cfr-notification-footer-empty-stars"];523 // .toFixed to sort out some floating precision errors524 assert.equal(525 footerFilledStars.style.width,526 `${(4.2 * 17).toFixed(1)}px`527 );528 assert.equal(529 footerEmptyStars.style.width,530 `${(0.8 * 17).toFixed(1)}px`531 );532 });533 it("should add the number of users correctly", async () => {534 await pageAction._showPopupOnClick();535 const footerUsers = elements["cfr-notification-footer-users"];536 assert.isNull(footerUsers.getAttribute("hidden"));537 assert.equal(538 footerUsers.getAttribute("value"),539 `${fakeRecommendation.content.addon.users} users`540 );541 });542 it("should send the right telemetry", async () => {543 await pageAction._showPopupOnClick();544 assert.calledWith(dispatchStub, {545 type: "DOORHANGER_TELEMETRY",546 data: {547 action: "cfr_user_event",548 source: "CFR",549 message_id: fakeRecommendation.id,550 bucket_id: fakeRecommendation.content.bucket_id,551 event: "CLICK_DOORHANGER",552 },553 });554 });555 it("should send modelVersion if presented in the message", async () => {556 const recommendationWithModelVersion = {557 ...fakeRecommendation,558 personalizedModelVersion: "model_version_1",559 };560 CFRPageActions.clearRecommendations();561 await CFRPageActions.addRecommendation(562 fakeBrowser,563 fakeHost,564 recommendationWithModelVersion,565 dispatchStub566 );567 await pageAction._showPopupOnClick();568 assert.calledWith(dispatchStub, {569 type: "DOORHANGER_TELEMETRY",570 data: {571 action: "cfr_user_event",572 source: "CFR",573 message_id: fakeRecommendation.id,574 bucket_id: fakeRecommendation.content.bucket_id,575 event: "CLICK_DOORHANGER",576 event_context: { modelVersion: "model_version_1" },577 },578 });579 });580 it("should set the main action correctly", async () => {581 sinon582 .stub(CFRPageActions, "_fetchLatestAddonVersion")583 .resolves("latest-addon.xpi");584 await pageAction._showPopupOnClick();585 const mainAction = global.PopupNotifications.show.firstCall.args[4]; // eslint-disable-line prefer-destructuring586 assert.deepEqual(mainAction.label, {587 value: "Primary Button",588 attributes: { accesskey: "p" },589 });590 sandbox.spy(pageAction, "hideAddressBarNotifier");591 await mainAction.callback();592 assert.calledOnce(pageAction.hideAddressBarNotifier);593 // Should block the message594 assert.calledWith(dispatchStub, {595 type: "BLOCK_MESSAGE_BY_ID",596 data: { id: fakeRecommendation.id },597 });598 // Should trigger the action599 assert.calledWith(600 dispatchStub,601 {602 type: "USER_ACTION",603 data: { id: "primary_action", data: { url: "latest-addon.xpi" } },604 },605 { browser: fakeBrowser }606 );607 // Should send telemetry608 assert.calledWith(dispatchStub, {609 type: "DOORHANGER_TELEMETRY",610 data: {611 action: "cfr_user_event",612 source: "CFR",613 message_id: fakeRecommendation.id,614 bucket_id: fakeRecommendation.content.bucket_id,615 event: "INSTALL",616 },617 });618 // Should remove the recommendation619 assert.isFalse(CFRPageActions.RecommendationMap.has(fakeBrowser));620 });621 it("should set the secondary action correctly", async () => {622 await pageAction._showPopupOnClick();623 // eslint-disable-next-line prefer-destructuring624 const [625 secondaryAction,626 ] = global.PopupNotifications.show.firstCall.args[5];627 assert.deepEqual(secondaryAction.label, {628 value: "Secondary Button",629 attributes: { accesskey: "s" },630 });631 sandbox.spy(pageAction, "hideAddressBarNotifier");632 CFRPageActions.RecommendationMap.set(fakeBrowser, {});633 secondaryAction.callback();634 // Should send telemetry635 assert.calledWith(dispatchStub, {636 type: "DOORHANGER_TELEMETRY",637 data: {638 action: "cfr_user_event",639 source: "CFR",640 message_id: fakeRecommendation.id,641 bucket_id: fakeRecommendation.content.bucket_id,642 event: "DISMISS",643 },644 });645 // Don't remove the recommendation on `DISMISS` action646 assert.isTrue(CFRPageActions.RecommendationMap.has(fakeBrowser));647 assert.notCalled(pageAction.hideAddressBarNotifier);648 });649 it("should send right telemetry for BLOCK secondary action", async () => {650 await pageAction._showPopupOnClick();651 // eslint-disable-next-line prefer-destructuring652 const blockAction = global.PopupNotifications.show.firstCall.args[5][1];653 assert.deepEqual(blockAction.label, {654 value: "Secondary Button 2",655 attributes: { accesskey: "a" },656 });657 sandbox.spy(pageAction, "hideAddressBarNotifier");658 sandbox.spy(pageAction, "_blockMessage");659 CFRPageActions.RecommendationMap.set(fakeBrowser, {});660 blockAction.callback();661 assert.calledOnce(pageAction.hideAddressBarNotifier);662 assert.calledOnce(pageAction._blockMessage);663 // Should send telemetry664 assert.calledWith(dispatchStub, {665 type: "DOORHANGER_TELEMETRY",666 data: {667 action: "cfr_user_event",668 source: "CFR",669 message_id: fakeRecommendation.id,670 bucket_id: fakeRecommendation.content.bucket_id,671 event: "BLOCK",672 },673 });674 // Should remove the recommendation675 assert.isFalse(CFRPageActions.RecommendationMap.has(fakeBrowser));676 });677 it("should send right telemetry for MANAGE secondary action", async () => {678 await pageAction._showPopupOnClick();679 // eslint-disable-next-line prefer-destructuring680 const manageAction =681 global.PopupNotifications.show.firstCall.args[5][2];682 assert.deepEqual(manageAction.label, {683 value: "Secondary Button 3",684 attributes: { accesskey: "g" },685 });686 sandbox.spy(pageAction, "hideAddressBarNotifier");687 CFRPageActions.RecommendationMap.set(fakeBrowser, {});688 manageAction.callback();689 // Should send telemetry690 assert.calledWith(dispatchStub, {691 type: "DOORHANGER_TELEMETRY",692 data: {693 action: "cfr_user_event",694 source: "CFR",695 message_id: fakeRecommendation.id,696 bucket_id: fakeRecommendation.content.bucket_id,697 event: "MANAGE",698 },699 });700 // Don't remove the recommendation on `MANAGE` action701 assert.isTrue(CFRPageActions.RecommendationMap.has(fakeBrowser));702 assert.notCalled(pageAction.hideAddressBarNotifier);703 });704 it("should call PopupNotifications.show with the right arguments", async () => {705 await pageAction._showPopupOnClick();706 assert.calledWith(707 global.PopupNotifications.show,708 fakeBrowser,709 "contextual-feature-recommendation",710 fakeRecommendation.content.addon.title,711 "cfr",712 sinon.match.any, // Corresponds to the main action, tested above713 sinon.match.any, // Corresponds to the secondary action, tested above714 {715 popupIconURL: fakeRecommendation.content.addon.icon,716 hideClose: true,717 eventCallback: pageAction._popupStateChange,718 }719 );720 });721 it("should show the bullet list details", async () => {722 fakeRecommendation.content.layout = "message_and_animation";723 await pageAction._showPopupOnClick();724 assert.calledOnce(translateElementsStub);725 });726 it("should set the data-l10n-id on the list element", async () => {727 fakeRecommendation.content.layout = "message_and_animation";728 await pageAction._showPopupOnClick();729 assert.calledOnce(setAttributesStub);730 assert.calledWith(731 setAttributesStub,732 sinon.match.any,733 fakeRecommendation.content.descriptionDetails.steps[0].string_id734 );735 });736 it("should set the correct data-notification-category", async () => {737 fakeRecommendation.content.layout = "message_and_animation";738 await pageAction._showPopupOnClick();739 assert.equal(740 elements["contextual-feature-recommendation-notification"].dataset741 .notificationCategory,742 fakeRecommendation.content.layout743 );744 });745 it("should send PIN event on primary action click", async () => {746 fakeRecommendation.content.layout = "message_and_animation";747 sandbox.stub(pageAction, "_sendTelemetry");748 await pageAction._showPopupOnClick();749 const [750 ,751 ,752 ,753 ,754 { callback },755 ] = global.PopupNotifications.show.firstCall.args;756 callback();757 // First call is triggered by `_showPopupOnClick`758 assert.propertyVal(759 pageAction._sendTelemetry.secondCall.args[0],760 "event",761 "PIN"762 );763 });764 });765 });766 describe("CFRPageActions", () => {767 beforeEach(() => {768 // Spy on the prototype methods to inspect calls for any PageAction instance769 sandbox.spy(PageAction.prototype, "showAddressBarNotifier");770 sandbox.spy(PageAction.prototype, "hideAddressBarNotifier");771 });772 describe("updatePageActions", () => {773 let savedRec;774 beforeEach(() => {775 const win = fakeBrowser.ownerGlobal;776 CFRPageActions.PageActionMap.set(777 win,778 new PageAction(win, dispatchStub)779 );780 const { id, content } = fakeRecommendation;781 savedRec = {782 id,783 host: fakeHost,784 content,785 };786 CFRPageActions.RecommendationMap.set(fakeBrowser, savedRec);787 });788 it("should do nothing if a pageAction doesn't exist for the window", () => {789 const win = fakeBrowser.ownerGlobal;790 CFRPageActions.PageActionMap.delete(win);791 CFRPageActions.updatePageActions(fakeBrowser);792 assert.notCalled(PageAction.prototype.showAddressBarNotifier);793 assert.notCalled(PageAction.prototype.hideAddressBarNotifier);794 });795 it("should do nothing if the browser is not the `selectedBrowser`", () => {796 const someOtherFakeBrowser = {};797 CFRPageActions.updatePageActions(someOtherFakeBrowser);798 assert.notCalled(PageAction.prototype.showAddressBarNotifier);799 assert.notCalled(PageAction.prototype.hideAddressBarNotifier);800 });801 it("should hideAddressBarNotifier the pageAction if a recommendation doesn't exist for the given browser", () => {802 CFRPageActions.RecommendationMap.delete(fakeBrowser);803 CFRPageActions.updatePageActions(fakeBrowser);804 assert.calledOnce(PageAction.prototype.hideAddressBarNotifier);805 });806 it("should show the pageAction if a recommendation exists and the host matches", () => {807 CFRPageActions.updatePageActions(fakeBrowser);808 assert.calledOnce(PageAction.prototype.showAddressBarNotifier);809 assert.calledWith(810 PageAction.prototype.showAddressBarNotifier,811 savedRec812 );813 });814 it("should show the pageAction if a recommendation exists and it doesn't have a host defined", () => {815 const recNoHost = { ...savedRec, host: undefined };816 CFRPageActions.RecommendationMap.set(fakeBrowser, recNoHost);817 CFRPageActions.updatePageActions(fakeBrowser);818 assert.calledOnce(PageAction.prototype.showAddressBarNotifier);819 assert.calledWith(820 PageAction.prototype.showAddressBarNotifier,821 recNoHost822 );823 });824 it("should hideAddressBarNotifier the pageAction and delete the recommendation if the recommendation exists but the host doesn't match", () => {825 const someOtherFakeHost = "subdomain.mozilla.com";826 fakeBrowser.documentURI.host = someOtherFakeHost;827 assert.isTrue(CFRPageActions.RecommendationMap.has(fakeBrowser));828 CFRPageActions.updatePageActions(fakeBrowser);829 assert.calledOnce(PageAction.prototype.hideAddressBarNotifier);830 assert.isFalse(CFRPageActions.RecommendationMap.has(fakeBrowser));831 });832 it("should not call `delete` if retain is true", () => {833 savedRec.retain = true;834 fakeBrowser.documentURI.host = "subdomain.mozilla.com";835 assert.isTrue(CFRPageActions.RecommendationMap.has(fakeBrowser));836 CFRPageActions.updatePageActions(fakeBrowser);837 assert.propertyVal(savedRec, "retain", false);838 assert.calledOnce(PageAction.prototype.hideAddressBarNotifier);839 assert.isTrue(CFRPageActions.RecommendationMap.has(fakeBrowser));840 });841 it("should call `delete` if retain is false", () => {842 savedRec.retain = false;843 fakeBrowser.documentURI.host = "subdomain.mozilla.com";844 assert.isTrue(CFRPageActions.RecommendationMap.has(fakeBrowser));845 CFRPageActions.updatePageActions(fakeBrowser);846 assert.propertyVal(savedRec, "retain", false);847 assert.calledOnce(PageAction.prototype.hideAddressBarNotifier);848 assert.isFalse(CFRPageActions.RecommendationMap.has(fakeBrowser));849 });850 });851 describe("forceRecommendation", () => {852 it("should succeed and add an element to the RecommendationMap", async () => {853 assert.isTrue(854 await CFRPageActions.forceRecommendation(855 { browser: fakeBrowser },856 fakeRecommendation,857 dispatchStub858 )859 );860 assert.deepInclude(CFRPageActions.RecommendationMap.get(fakeBrowser), {861 id: fakeRecommendation.id,862 content: fakeRecommendation.content,863 });864 });865 it("should create a PageAction if one doesn't exist for the window, save it in the PageActionMap, and call `show`", async () => {866 const win = fakeBrowser.ownerGlobal;867 assert.isFalse(CFRPageActions.PageActionMap.has(win));868 await CFRPageActions.forceRecommendation(869 { browser: fakeBrowser },870 fakeRecommendation,871 dispatchStub872 );873 const pageAction = CFRPageActions.PageActionMap.get(win);874 assert.equal(win, pageAction.window);875 assert.equal(dispatchStub, pageAction._dispatchToASRouter);876 assert.calledOnce(PageAction.prototype.showAddressBarNotifier);877 });878 });879 describe("addRecommendation", () => {880 it("should fail and not add a recommendation if the browser is part of a private window", async () => {881 global.PrivateBrowsingUtils.isWindowPrivate.returns(true);882 assert.isFalse(883 await CFRPageActions.addRecommendation(884 fakeBrowser,885 fakeHost,886 fakeRecommendation,887 dispatchStub888 )889 );890 assert.isFalse(CFRPageActions.RecommendationMap.has(fakeBrowser));891 });892 it("should fail and not add a recommendation if the browser is not the selected browser", async () => {893 global.gBrowser.selectedBrowser = {}; // Some other browser894 assert.isFalse(895 await CFRPageActions.addRecommendation(896 fakeBrowser,897 fakeHost,898 fakeRecommendation,899 dispatchStub900 )901 );902 });903 it("should fail and not add a recommendation if the host doesn't match", async () => {904 const someOtherFakeHost = "subdomain.mozilla.com";905 assert.isFalse(906 await CFRPageActions.addRecommendation(907 fakeBrowser,908 someOtherFakeHost,909 fakeRecommendation,910 dispatchStub911 )912 );913 });914 it("should otherwise succeed and add an element to the RecommendationMap", async () => {915 assert.isTrue(916 await CFRPageActions.addRecommendation(917 fakeBrowser,918 fakeHost,919 fakeRecommendation,920 dispatchStub921 )922 );923 assert.deepInclude(CFRPageActions.RecommendationMap.get(fakeBrowser), {924 id: fakeRecommendation.id,925 host: fakeHost,926 content: fakeRecommendation.content,927 });928 });929 it("should create a PageAction if one doesn't exist for the window, save it in the PageActionMap, and call `show`", async () => {930 const win = fakeBrowser.ownerGlobal;931 assert.isFalse(CFRPageActions.PageActionMap.has(win));932 await CFRPageActions.addRecommendation(933 fakeBrowser,934 fakeHost,935 fakeRecommendation,936 dispatchStub937 );938 const pageAction = CFRPageActions.PageActionMap.get(win);939 assert.equal(win, pageAction.window);940 assert.equal(dispatchStub, pageAction._dispatchToASRouter);941 assert.calledOnce(PageAction.prototype.showAddressBarNotifier);942 });943 it("should add the right url if we fetched and addon install URL", async () => {944 fakeRecommendation.template = "cfr_doorhanger";945 await CFRPageActions.addRecommendation(946 fakeBrowser,947 fakeHost,948 fakeRecommendation,949 dispatchStub950 );951 const recommendation = CFRPageActions.RecommendationMap.get(952 fakeBrowser953 );954 // sanity check - just go through some of the rest of the attributes to make sure they were untouched955 assert.equal(recommendation.id, fakeRecommendation.id);956 assert.equal(957 recommendation.content.heading_text,958 fakeRecommendation.content.heading_text959 );960 assert.equal(961 recommendation.content.addon,962 fakeRecommendation.content.addon963 );964 assert.equal(965 recommendation.content.text,966 fakeRecommendation.content.text967 );968 assert.equal(969 recommendation.content.buttons.secondary,970 fakeRecommendation.content.buttons.secondary971 );972 assert.equal(973 recommendation.content.buttons.primary.action.id,974 fakeRecommendation.content.buttons.primary.action.id975 );976 delete fakeRecommendation.template;977 });978 it("should prevent a second message if one is currently displayed", async () => {979 const secondMessage = { ...fakeRecommendation, id: "second_message" };980 let messageAdded = await CFRPageActions.addRecommendation(981 fakeBrowser,982 fakeHost,983 fakeRecommendation,984 dispatchStub985 );986 assert.isTrue(messageAdded);987 assert.deepInclude(CFRPageActions.RecommendationMap.get(fakeBrowser), {988 id: fakeRecommendation.id,989 host: fakeHost,990 content: fakeRecommendation.content,991 });992 messageAdded = await CFRPageActions.addRecommendation(993 fakeBrowser,994 fakeHost,995 secondMessage,996 dispatchStub997 );998 // Adding failed999 assert.isFalse(messageAdded);1000 // First message is still there1001 assert.deepInclude(CFRPageActions.RecommendationMap.get(fakeBrowser), {1002 id: fakeRecommendation.id,1003 host: fakeHost,1004 content: fakeRecommendation.content,1005 });1006 });1007 it("should send impressions just for the first message", async () => {1008 const secondMessage = { ...fakeRecommendation, id: "second_message" };1009 await CFRPageActions.addRecommendation(1010 fakeBrowser,1011 fakeHost,1012 fakeRecommendation,1013 dispatchStub1014 );1015 await CFRPageActions.addRecommendation(1016 fakeBrowser,1017 fakeHost,1018 secondMessage,1019 dispatchStub1020 );1021 // Doorhanger telemetry + Impression for just 1 message1022 assert.calledTwice(dispatchStub);1023 const [firstArgs] = dispatchStub.firstCall.args;1024 const [secondArgs] = dispatchStub.secondCall.args;1025 assert.equal(firstArgs.data.id, secondArgs.data.message_id);1026 });1027 });1028 describe("clearRecommendations", () => {1029 const createFakePageAction = () => ({1030 hideAddressBarNotifier: sandbox.stub(),1031 });1032 const windows = [{}, {}, { closed: true }];1033 const browsers = [{}, {}, {}, {}];1034 beforeEach(() => {1035 CFRPageActions.PageActionMap.set(windows[0], createFakePageAction());1036 CFRPageActions.PageActionMap.set(windows[2], createFakePageAction());1037 for (const browser of browsers) {1038 CFRPageActions.RecommendationMap.set(browser, {});1039 }1040 globals.set({ Services: { wm: { getEnumerator: () => windows } } });1041 });1042 it("should hideAddressBarNotifier the PageActions of any existing, non-closed windows", () => {1043 const pageActions = windows.map(win =>1044 CFRPageActions.PageActionMap.get(win)1045 );1046 CFRPageActions.clearRecommendations();1047 // Only the first window had a PageAction and wasn't closed1048 assert.calledOnce(pageActions[0].hideAddressBarNotifier);1049 assert.isUndefined(pageActions[1]);1050 assert.notCalled(pageActions[2].hideAddressBarNotifier);1051 });1052 it("should clear the PageActionMap and the RecommendationMap", () => {1053 CFRPageActions.clearRecommendations();1054 // Both are WeakMaps and so are not iterable, cannot be cleared, and1055 // cannot have their length queried directly, so we have to check1056 // whether previous elements still exist1057 assert.lengthOf(windows, 3);1058 for (const win of windows) {1059 assert.isFalse(CFRPageActions.PageActionMap.has(win));1060 }1061 assert.lengthOf(browsers, 4);1062 for (const browser of browsers) {1063 assert.isFalse(CFRPageActions.RecommendationMap.has(browser));1064 }1065 });1066 });1067 describe("reloadL10n", () => {1068 const createFakePageAction = () => ({1069 hideAddressBarNotifier() {},1070 reloadL10n: sandbox.stub(),1071 });1072 const windows = [{}, {}, { closed: true }];1073 beforeEach(() => {1074 CFRPageActions.PageActionMap.set(windows[0], createFakePageAction());1075 CFRPageActions.PageActionMap.set(windows[2], createFakePageAction());1076 globals.set({ Services: { wm: { getEnumerator: () => windows } } });1077 });1078 it("should call reloadL10n for all the PageActions of any existing, non-closed windows", () => {1079 const pageActions = windows.map(win =>1080 CFRPageActions.PageActionMap.get(win)1081 );1082 CFRPageActions.reloadL10n();1083 // Only the first window had a PageAction and wasn't closed1084 assert.calledOnce(pageActions[0].reloadL10n);1085 assert.isUndefined(pageActions[1]);1086 assert.notCalled(pageActions[2].reloadL10n);1087 });1088 });1089 });...
launcher.spec.js
Source:launcher.spec.js
1'use strict'2const Promise = require('bluebird')3const di = require('di')4const events = require('../../lib/events')5const launcher = require('../../lib/launcher')6const createMockTimer = require('./mocks/timer')7// promise mock8const stubPromise = (obj, method, stubAction) => {9 const promise = new Promise((resolve) => {10 obj[method].resolve = resolve11 })12 sinon.stub(obj, method).callsFake(() => {13 if (stubAction) stubAction()14 return promise15 })16}17function FakeBrowser (id, name, baseBrowserDecorator) {18 this.id = id19 this.name = name20 this.DEFAULT_CMD = {21 linux: '/script',22 darwin: '/script',23 win32: 'script.exe'24 }25 this.ENV_CMD = 'SCRIPT_BIN'26 baseBrowserDecorator(this)27 FakeBrowser._instances.push(this)28 sinon.stub(this, 'start').callsFake(() => {29 this.state = this.STATE_BEING_CAPTURED30 this._done()31 })32 stubPromise(this, 'forceKill')33 sinon.stub(this, 'restart')34}35function ScriptBrowser (id, name, baseBrowserDecorator) {36 this.id = id37 this.name = name38 this.DEFAULT_CMD = {39 linux: '/script',40 darwin: '/script',41 win32: 'script.exe'42 }43 this.ENV_CMD = 'SCRIPT_BIN'44 baseBrowserDecorator(this)45 ScriptBrowser._instances.push(this)46 sinon.stub(this, 'start').callsFake(() => {47 this.state = this.STATE_BEING_CAPTURED48 this._done()49 })50 stubPromise(this, 'forceKill')51 sinon.stub(this, 'restart')52}53describe('launcher', () => {54 // mock out id generator55 let lastGeneratedId = null56 launcher.Launcher.generateId = () => ++lastGeneratedId57 before(() => {58 Promise.setScheduler((fn) => fn())59 })60 after(() => {61 Promise.setScheduler((fn) => process.nextTick(fn))62 })63 beforeEach(() => {64 lastGeneratedId = 065 FakeBrowser._instances = []66 ScriptBrowser._instances = []67 })68 describe('Launcher', () => {69 let emitter70 let server71 let config72 let l73 beforeEach(() => {74 emitter = new events.EventEmitter()75 server = {'loadErrors': []}76 config = {77 captureTimeout: 0,78 protocol: 'http:',79 hostname: 'localhost',80 port: 1234,81 urlRoot: '/root/'82 }83 const injector = new di.Injector([{84 'launcher:Fake': ['type', FakeBrowser],85 'launcher:Script': ['type', ScriptBrowser],86 'server': ['value', server],87 'emitter': ['value', emitter],88 'config': ['value', config],89 'timer': ['factory', createMockTimer]90 }])91 l = new launcher.Launcher(server, emitter, injector)92 })93 describe('launch', () => {94 it('should inject and start all browsers', (done) => {95 l.launch(['Fake'], 1)96 const browser = FakeBrowser._instances.pop()97 l.jobs.on('end', () => {98 expect(browser.start).to.have.been.calledWith('http://localhost:1234/root/')99 expect(browser.id).to.equal(lastGeneratedId)100 expect(browser.name).to.equal('Fake')101 done()102 })103 })104 describe('with upstream proxy settings', () => {105 beforeEach(() => {106 emitter = new events.EventEmitter()107 server = {'loadErrors': []}108 config = {109 captureTimeout: 0,110 protocol: 'http:',111 hostname: 'localhost',112 port: 1234,113 urlRoot: '/root/',114 upstreamProxy: {115 path: '/__proxy__/',116 hostname: 'proxy',117 port: '5678',118 protocol: 'https:'119 }120 }121 const injector = new di.Injector([{122 'launcher:Fake': ['type', FakeBrowser],123 'launcher:Script': ['type', ScriptBrowser],124 'server': ['value', server],125 'emitter': ['value', emitter],126 'config': ['value', config],127 'timer': ['factory', createMockTimer]128 }])129 l = new launcher.Launcher(server, emitter, injector)130 })131 it('should inject and start all browsers', (done) => {132 l.launch(['Fake'], 1)133 const browser = FakeBrowser._instances.pop()134 l.jobs.on('end', () => {135 expect(browser.start).to.have.been.calledWith('https://proxy:5678/__proxy__/root/')136 expect(browser.id).to.equal(lastGeneratedId)137 expect(browser.name).to.equal('Fake')138 done()139 })140 })141 })142 it('should not start when server has load errors', (done) => {143 server.loadErrors = ['error']144 l.launch(['Fake'], 1)145 l.jobs.on('end', () => {146 expect(FakeBrowser._instances).to.be.empty147 done()148 })149 })150 it('should allow launching a script', (done) => {151 l.launch(['/usr/local/bin/special-browser'], 1)152 const script = ScriptBrowser._instances.pop()153 l.jobs.on('end', () => {154 expect(script.start).to.have.been.calledWith('http://localhost:1234/root/')155 expect(script.name).to.equal('/usr/local/bin/special-browser')156 done()157 })158 })159 it('should use the non default host', (done) => {160 config.hostname = 'whatever'161 l.launch(['Fake'], 1)162 const browser = FakeBrowser._instances.pop()163 l.jobs.on('end', () => {164 expect(browser.start).to.have.been.calledWith('http://whatever:1234/root/')165 done()166 })167 })168 })169 describe('restart', () => {170 it('should restart the browser', () => {171 l.launch(['Fake'], 1)172 const browser = FakeBrowser._instances.pop()173 expect(l.restart(lastGeneratedId)).to.equal(true)174 expect(browser.restart).to.have.been.called175 })176 it('should return false if the browser was not launched by launcher (manual)', () => {177 l.launch([], 1)178 expect(l.restart('manual-id')).to.equal(false)179 })180 })181 describe('kill', () => {182 it('should kill browser with given id', (done) => {183 l.launch(['Fake'], 1)184 const browser = FakeBrowser._instances.pop()185 l.kill(browser.id, done)186 expect(browser.forceKill).to.have.been.called187 browser.forceKill.resolve()188 })189 it('should return false if browser does not exist, but still resolve the callback', (done) => {190 l.launch(['Fake'], 1)191 const browser = FakeBrowser._instances.pop()192 expect(l.kill('weird-id', done)).to.equal(false)193 expect(browser.forceKill).not.to.have.been.called194 })195 it('should not require a callback', (done) => {196 l.launch(['Fake'], 1)197 FakeBrowser._instances.pop()198 l.kill('weird-id')199 process.nextTick(done)200 })201 })202 describe('killAll', () => {203 it('should kill all running processe', () => {204 l.launch(['Fake', 'Fake'], 1)205 l.killAll()206 let browser = FakeBrowser._instances.pop()207 expect(browser.forceKill).to.have.been.called208 browser = FakeBrowser._instances.pop()209 expect(browser.forceKill).to.have.been.called210 })211 it('should call callback when all processes killed', () => {212 const exitSpy = sinon.spy()213 l.launch(['Fake', 'Fake'], 1)214 l.killAll(exitSpy)215 expect(exitSpy).not.to.have.been.called216 // finish the first browser217 let browser = FakeBrowser._instances.pop()218 browser.forceKill.resolve()219 scheduleNextTick(() => {220 expect(exitSpy).not.to.have.been.called221 })222 scheduleNextTick(() => {223 // finish the second browser224 browser = FakeBrowser._instances.pop()225 browser.forceKill.resolve()226 })227 scheduleNextTick(() => {228 expect(exitSpy).to.have.been.called229 })230 })231 it('should call callback even if no browsers lanunched', (done) => {232 l.killAll(done)233 })234 })235 describe('areAllCaptured', () => {236 it('should return true if only if all browsers captured', () => {237 l._browsers = [{238 isCaptured: () => true239 }, {240 isCaptured: () => false241 }]242 expect(l.areAllCaptured()).to.be.equal(false)243 l._browsers = [{244 isCaptured: () => true245 }, {246 isCaptured: () => true247 }]248 expect(l.areAllCaptured()).to.be.equal(true)249 })250 })251 describe('markCaptured', () => {252 it('should not fail if an un-launched browser attaches', () => {253 expect(() => l.markCaptured('not-a-thing')).to.not.throw()254 })255 })256 describe('onExit', () => {257 it('should kill all browsers', (done) => {258 l.launch(['Fake', 'Fake'], 1)259 emitter.emitAsync('exit').then(done)260 let browser = FakeBrowser._instances.pop()261 browser.forceKill.resolve()262 browser = FakeBrowser._instances.pop()263 browser.forceKill.resolve()264 })265 })266 })...
repo.js
Source:repo.js
1var common = require('../common-tap.js')2var mr = require('npm-registry-mock')3var test = require('tap').test4var rimraf = require('rimraf')5var fs = require('fs')6var path = require('path')7var fakeBrowser = path.join(__dirname, '_script.sh')8var outFile = path.join(__dirname, '/_output')9var opts = { cwd: __dirname }10common.pendIfWindows('This is trickier to convert without opening new shells')11test('setup', function (t) {12 var s = '#!/usr/bin/env bash\n' +13 'echo "$@" > ' + JSON.stringify(__dirname) + '/_output\n'14 fs.writeFileSync(fakeBrowser, s, 'ascii')15 fs.chmodSync(fakeBrowser, '0755')16 t.pass('made script')17 t.end()18})19test('npm repo underscore', function (t) {20 mr({ port: common.port }, function (er, s) {21 common.npm([22 'repo', 'underscore',23 '--registry=' + common.registry,24 '--loglevel=silent',25 '--browser=' + fakeBrowser26 ], opts, function (err, code, stdout, stderr) {27 t.ifError(err, 'repo command ran without error')28 t.equal(code, 0, 'exit ok')29 var res = fs.readFileSync(outFile, 'ascii')30 s.close()31 t.equal(res, 'https://github.com/jashkenas/underscore\n')32 rimraf.sync(outFile)33 t.end()34 })35 })36})37test('npm repo optimist - github (https://)', function (t) {38 mr({ port: common.port }, function (er, s) {39 common.npm([40 'repo', 'optimist',41 '--registry=' + common.registry,42 '--loglevel=silent',43 '--browser=' + fakeBrowser44 ], opts, function (err, code, stdout, stderr) {45 t.ifError(err, 'repo command ran without error')46 t.equal(code, 0, 'exit ok')47 var res = fs.readFileSync(outFile, 'ascii')48 s.close()49 t.equal(res, 'https://github.com/substack/node-optimist\n')50 rimraf.sync(outFile)51 t.end()52 })53 })54})55test('npm repo npm-test-peer-deps - no repo', function (t) {56 mr({ port: common.port }, function (er, s) {57 common.npm([58 'repo', 'npm-test-peer-deps',59 '--registry=' + common.registry,60 '--loglevel=silent',61 '--browser=' + fakeBrowser62 ], opts, function (err, code, stdout, stderr) {63 t.ifError(err, 'repo command ran without error')64 t.equal(code, 1, 'exit not ok')65 s.close()66 t.end()67 })68 })69})70test('npm repo test-repo-url-http - non-github (http://)', function (t) {71 mr({ port: common.port }, function (er, s) {72 common.npm([73 'repo', 'test-repo-url-http',74 '--registry=' + common.registry,75 '--loglevel=silent',76 '--browser=' + fakeBrowser77 ], opts, function (err, code, stdout, stderr) {78 t.ifError(err, 'repo command ran without error')79 t.equal(code, 0, 'exit ok')80 var res = fs.readFileSync(outFile, 'ascii')81 s.close()82 t.equal(res, 'http://gitlab.com/evanlucas/test-repo-url-http\n')83 rimraf.sync(outFile)84 t.end()85 })86 })87})88test('npm repo test-repo-url-https - non-github (https://)', function (t) {89 mr({ port: common.port }, function (er, s) {90 common.npm([91 'repo', 'test-repo-url-https',92 '--registry=' + common.registry,93 '--loglevel=silent',94 '--browser=' + fakeBrowser95 ], opts, function (err, code, stdout, stderr) {96 t.ifError(err, 'repo command ran without error')97 t.equal(code, 0, 'exit ok')98 var res = fs.readFileSync(outFile, 'ascii')99 s.close()100 t.equal(res, 'https://gitlab.com/evanlucas/test-repo-url-https\n')101 rimraf.sync(outFile)102 t.end()103 })104 })105})106test('npm repo test-repo-url-ssh - non-github (ssh://)', function (t) {107 mr({ port: common.port }, function (er, s) {108 common.npm([109 'repo', 'test-repo-url-ssh',110 '--registry=' + common.registry,111 '--loglevel=silent',112 '--browser=' + fakeBrowser113 ], opts, function (err, code, stdout, stderr) {114 t.ifError(err, 'repo command ran without error')115 t.equal(code, 0, 'exit ok')116 var res = fs.readFileSync(outFile, 'ascii')117 s.close()118 t.equal(res, 'https://gitlab.com/evanlucas/test-repo-url-ssh\n')119 rimraf.sync(outFile)120 t.end()121 })122 })123})124test('cleanup', function (t) {125 fs.unlinkSync(fakeBrowser)126 t.pass('cleaned up')127 t.end()...
adduser-oauth.js
Source:adduser-oauth.js
1var fs = require('fs')2var path = require('path')3var mkdirp = require('mkdirp')4var rimraf = require('rimraf')5var mr = require('npm-registry-mock')6var test = require('tap').test7var common = require('../common-tap.js')8var opts = { cwd: __dirname }9var pkg = path.resolve(__dirname, 'adduser-oauth')10var fakeBrowser = path.resolve(pkg, '_script.sh')11var configfile = path.resolve(pkg, '_npmrc')12var outfile = path.resolve(pkg, '_outfile')13var ssoUri = common.registry + '/-/oauth/foo'14common.pendIfWindows('This is trickier to convert without opening new shells')15function mocks (server) {16 server.filteringRequestBody(function (r) {17 if (r.match(/"_id":"org\.couchdb\.user:npm_oauth_auth_dummy_user"/)) {18 return 'auth'19 } else {20 return 'invalid'21 }22 })23 server.post('/-/v1/login', 'invalid').reply(404, 'not found')24 server.put('/-/user/org.couchdb.user:npm_oauth_auth_dummy_user', 'auth')25 .reply(201, { token: 'foo', sso: ssoUri })26}27test('setup', function (t) {28 mkdirp.sync(pkg)29 fs.writeFileSync(configfile, '')30 var s = '#!/usr/bin/env bash\n' +31 'echo "$@" > ' + outfile + '\n'32 fs.writeFileSync(fakeBrowser, s, 'ascii')33 fs.chmodSync(fakeBrowser, '0755')34 t.pass('made script')35 t.end()36})37test('npm login', function (t) {38 mr({ port: common.port, plugin: mocks }, function (er, s) {39 s.get(40 '/-/whoami', { authorization: 'Bearer foo' }41 ).max(1).reply(401, {})42 common.npm(43 [44 'login',45 '--registry', common.registry,46 '--auth-type=oauth',47 '--loglevel', 'silent',48 '--userconfig', configfile,49 '--browser', fakeBrowser50 ],51 opts,52 function (err, code, stdout, stderr) {53 t.ifError(err, 'npm ran without issue')54 t.equal(code, 0, 'exited OK')55 t.notOk(stderr, 'no error output')56 stderr && t.comment('stderr - ', stderr)57 t.matches(stdout, /Logged in as igotauthed/,58 'successfully authenticated and output the given username')59 s.close()60 rimraf.sync(configfile)61 rimraf.sync(outfile)62 t.end()63 }64 )65 s.get(66 '/-/whoami', { authorization: 'Bearer foo' }67 ).reply(200, { username: 'igotauthed' })68 })69})70test('cleanup', function (t) {71 rimraf.sync(pkg)72 t.pass('cleaned up')73 t.end()...
adduser-saml.js
Source:adduser-saml.js
1var fs = require('fs')2var path = require('path')3var mkdirp = require('mkdirp')4var rimraf = require('rimraf')5var mr = require('npm-registry-mock')6var test = require('tap').test7var common = require('../common-tap.js')8var opts = { cwd: __dirname }9var pkg = path.resolve(__dirname, 'adduser-saml')10var fakeBrowser = path.resolve(pkg, '_script.sh')11var configfile = path.resolve(pkg, '_npmrc')12var outfile = path.resolve(pkg, '_outfile')13var ssoUri = common.registry + '/-/saml/foo'14common.pendIfWindows('This is trickier to convert without opening new shells')15function mocks (server) {16 server.filteringRequestBody(function (r) {17 if (r.match(/"_id":"org\.couchdb\.user:npm_saml_auth_dummy_user"/)) {18 return 'auth'19 } else {20 return 'invalid'21 }22 })23 server.post('/-/v1/login', 'invalid').reply(404, 'not found')24 server.put('/-/user/org.couchdb.user:npm_saml_auth_dummy_user', 'auth')25 .reply(201, { token: 'foo', sso: ssoUri })26}27test('setup', function (t) {28 mkdirp.sync(pkg)29 fs.writeFileSync(configfile, '')30 var s = '#!/usr/bin/env bash\n' +31 'echo "$@" > ' + outfile + '\n'32 fs.writeFileSync(fakeBrowser, s, 'ascii')33 fs.chmodSync(fakeBrowser, '0755')34 t.pass('made script')35 t.end()36})37test('npm login', function (t) {38 mr({ port: common.port, plugin: mocks }, function (er, s) {39 s.get(40 '/-/whoami', { authorization: 'Bearer foo' }41 ).max(1).reply(401, {})42 common.npm(43 [44 'login',45 '--registry', common.registry,46 '--auth-type=saml',47 '--loglevel', 'silent',48 '--userconfig', configfile,49 '--browser', fakeBrowser50 ],51 opts,52 function (err, code, stdout, stderr) {53 t.ifError(err, 'npm ran without issue')54 t.equal(code, 0, 'exited OK')55 t.notOk(stderr, 'no error output')56 stderr && t.comment('stderr - ', stderr)57 t.matches(stdout, /Logged in as igotauthed/,58 'successfully authenticated and output the given username')59 s.close()60 rimraf.sync(configfile)61 rimraf.sync(outfile)62 t.end()63 }64 )65 s.get(66 '/-/whoami', { authorization: 'Bearer foo' }67 ).reply(200, { username: 'igotauthed' })68 })69})70test('cleanup', function (t) {71 rimraf.sync(pkg)72 t.pass('cleaned up')73 t.end()...
WebExample.js
Source:WebExample.js
1import React from "react";2import PropTypes from "prop-types";3import Media from "react-media";4import { Block } from "jsxstyle";5import { Route } from "react-router-dom";6import Bundle from "./Bundle";7import FakeBrowser from "./FakeBrowser";8import SourceViewer from "./SourceViewer";9import Loading from "./Loading";10const WebExample = ({ example }) => (11 <Bundle load={example.load}>12 {Example => (13 <Bundle load={example.loadSource}>14 {src =>15 Example && src ? (16 <Media query="(min-width: 1170px)">17 {largeScreen => (18 <Block19 minHeight="100vh"20 background="rgb(45, 45, 45)"21 padding="40px"22 >23 <Route24 render={({ location }) => (25 <FakeBrowser26 key={location.key /*force new instance*/}27 position={largeScreen ? "fixed" : "static"}28 width={largeScreen ? "400px" : "auto"}29 height={largeScreen ? "auto" : "70vh"}30 left="290px"31 top="40px"32 bottom="40px"33 >34 <Example />35 </FakeBrowser>36 )}37 />38 <SourceViewer39 code={src}40 fontSize="11px"41 marginLeft={largeScreen ? "440px" : null}42 marginTop={largeScreen ? null : "40px"}43 />44 </Block>45 )}46 </Media>47 ) : (48 <Loading />49 )50 }51 </Bundle>52 )}53 </Bundle>54);55WebExample.propTypes = {56 example: PropTypes.object57};...
Using AI Code Generation
1describe('test', function() {2 var fakeBrowser;3 beforeEach(function() {4 fakeBrowser = new FakeBrowser();5 });6 it('should run', function() {7 expect(fakeBrowser).toBeDefined();8 });9});10describe('test2', function() {11 var fakeBrowser;12 beforeEach(function() {13 fakeBrowser = new FakeBrowser();14 });15 it('should run', function() {16 expect(fakeBrowser).toBeDefined();17 });18});19Chrome 27.0.1453 (Mac OS X 10.8.0) ERROR20Chrome 27.0.1653 (Mac OS X 10.8.0) ERROR21Chrome 27.0.1453 (Mac OS X 10.8.0): Executed 0 of 2 ERROR (0.002 secs / 0 secs)22preprocessors: {23}24preprocessors: {25}
Using AI Code Generation
1describe('test', function() {2 var fakeBrowser;3 beforeEach(function() {4 fakeBrowser = new FakeBrowser();5 });6 it('should run', function() {7 expect(fakeBrowser).toBeDefined();8 });9});
Using AI Code Generation
1var fb = new FakeBrowser();2fb.init();3fb.iframe.contentWindow.document.write('<!DOCTYPE html><html><head></head><body><div id="test"></div></body></html>');4fb.iframe.contentWindow.document.close();5var doc = fb.iframe.contentWindow.document;6var div = doc.getElementById("test");7var t / new Test();8t.test(div);9var t2 = new Test2();10t2.test(div);11fb.destroy();12describe('test2', function() {13 var fakeBrowser;14 beforeEach(function() {15 fakeBrowser = new FakeBrowser();16 });17 it('should run', function() {18 expect(fakeBrowser).toBeDefined();19 });20});21Chrome 27.0.1453 (Mac OS X 10.8.0) ERROR22Chrome 27.0.1453 (Mac OS X 10.8.0) ERROR23Chrome 27.0.1453 (Mac OS X 10.8.0): Executed 0 of 2 ERROR (0.002 secs / 0 secs)24preprocessors: {25}26preprocessors: {27}
Using AI Code Generation
1describe('Test', function() {2 var fakeBrowser;3 beforeEach(function() {4 fakeBrowser = new FakeBrowser();5 });6 it('should work', function() {7 });8});
Using AI Code Generation
1var fb = new FakeBrowser();2fb.init();3fb.iframe.contentWindow.document.write('<!DOCTYPE html><html><head></head><body><div id="test"></div></body></html>');4fb.iframe.contentWindow.document.close();5var doc = fb.iframe.contentWindow.document;6var div = doc.getElementById("test");7var t = new Test();8t.test(div);9var t2 = new Test2();10t2.test(div);11fb.destroy();
Using AI Code Generation
1describe('Test', function() {2 var fakeBrowser;3 beforeEach(function() {4 fakeBrowser = new FakeBrowser();5 });6 it('should get the correct result', function() {7 var result = fakeBrowser.evaluate(function() {8 return test();9 });10 expect(result).toEqual('Hello World');11 });12}
Using AI Code Generation
1describe('test', function () {2 it('test', function () {3 var fakeBrowser = new FakeBrowser();4 fakeBrowser.init();5 fakeBrowser.onUrlChange(function (url) {6 console.log('url changed to: ' + url);7 });8 });9});10module.exports = function (config) {11 config.set({12 customLaunchers: {13 'FakeBrowser': {14 }15 }16 });17};18fakeBrowser.onUrlChange(function (url) {19 console.log('url changed to: ' + url);20});21var fakeBrowser = new FakeBrowser();22fakeBrowser.init();23var element = fakeBrowser.createElement('my-element');24fakeBrowser.appendChild(element);
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!!