當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript SinonSandbox.stub方法代碼示例

本文整理匯總了TypeScript中Sinon.SinonSandbox.stub方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript SinonSandbox.stub方法的具體用法?TypeScript SinonSandbox.stub怎麽用?TypeScript SinonSandbox.stub使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在Sinon.SinonSandbox的用法示例。


在下文中一共展示了SinonSandbox.stub方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: beforeTest

/** Helper methods */
async function beforeTest(
  testConfig: TestEnvironmentConfig,
  t: TestContext & Context<any>,
  customServerAppConfig?: ServerAppConfig
) {
  await TestEnvironment.initialize(testConfig);
  initTestHelper.mockBasicInitEnv(testConfig, customServerAppConfig);
  OneSignal.initialized = false;
  OneSignal.__doNotShowWelcomeNotification = true;
  (window as any).Notification.permission = testConfig.permission || "default";

  const createPlayerPostStub = sinonSandbox.stub(OneSignalApiBase, "post")
    .resolves({success: true, id: playerId});
  const onSessionStub = sinonSandbox.stub(OneSignalApiShared, "updateUserSession")
    .resolves({success: true, id: playerId});

  sinonSandbox.stub(DynamicResourceLoader.prototype, "loadSdkStylesheet").resolves(ResourceLoadState.Loaded);
  sinonSandbox.stub(ServiceWorkerManager.prototype, "installWorker").resolves();
  nock('https://onesignal.com')
    .get(/.*icon$/)
    .reply(200, (_uri: string, _requestBody: string) => {
      return { success: true };
    });

  if (testConfig.httpOrHttps === HttpHttpsEnvironment.Http) {
    stubMessageChannel(t);
    mockIframeMessaging(sinonSandbox);
  }
  return { createPlayerPostStub, onSessionStub };
}
開發者ID:OneSignal,項目名稱:OneSignal-Website-SDK,代碼行數:31,代碼來源:onSession.ts

示例2: Promise

            return new Promise((resolve, reject) => {
                let tokenErrorWasPrinted = false;
                process.argv = command("node bst-speak.js Hello");
                mockery.registerMock("../lib/external/virtual-device", {
                    VirtualDeviceClient: {
                        speak: function() {
                            throw new Error("Token Required");
                        },
                        renderResult: function () {
                          return "";
                        },
                    }
                });

                sandbox.stub(process, "exit", function(exitCode: number) {
                    try {
                        assert.equal(exitCode, 0);
                        assert.equal(true, tokenErrorWasPrinted,  "Warning was not printed");
                    } catch (error) {
                        reject(error);
                    }
                    resolve();
                });

                sandbox.stub(console, "log", function(data: Buffer) {
                    const initialString = "You need a token for this option to work, get it here:";
                    if (data !== undefined && data.indexOf(initialString) !== -1) {
                        tokenErrorWasPrinted = true;
                    }
                });
                NodeUtil.load("../../bin/bst-speak.js");
            });
開發者ID:bespoken,項目名稱:bst,代碼行數:32,代碼來源:bst-speak-test.ts

示例3: beforeEach

    beforeEach(() => {
      destroyStub            = sandbox.stub();
      blocksModule.lastBlock = {
        height       : 10,
        previousBlock: 'previousBlock',
        transactions : [
          { senderPublicKey: 'first' },
          { senderPublicKey: 'second' },
          { senderPublicKey: 'third' },
        ],
        destroy      : destroyStub,
      } as any;
      roundsModule.enqueueResponse('backwardTick', Promise.resolve());
      txLogic.stubs.undoUnconfirmed.resolves([]);
      txLogic.stubs.undo.resolves([]);
      dbStub.stubs.performOps.resolves();
      // accountsModule.stubs.getAccount.callsFake((a) => a);
      accountsModule.stubs.resolveAccountsForTransactions.callsFake((txs)=> {
        const toRet = {};
        txs.forEach((tx) => toRet[tx.senderId] = tx.senderId);
        return toRet;
      });
      sandbox.stub(blocksModel.sequelize, 'transaction').callsFake((cb) => {
        return cb('tx');
      });
      findStub = sandbox.stub(blocksModel, 'findById');
      findStub.onCall(0).resolves(blocksModule.lastBlock);
      findStub.onCall(1).resolves({toJSON() { return { id: 'previousBlock' }}});

      const accountsModel = container.get<any>(Symbols.models.accounts);
      accountsFindStub    = sandbox.stub().returns('senderAccount');
      accountsScopeStub   = sandbox.stub(accountsModel, 'scope').returns({
        find: accountsFindStub
      });
    });
開發者ID:RiseVision,項目名稱:rise-node,代碼行數:35,代碼來源:chain.spec.ts

示例4: beforeEach

 beforeEach(() => {
   sandbox    = sinon.createSandbox();
   serverStub = {
     close : sandbox.stub(),
     listen: sandbox.stub(),
   };
 });
開發者ID:RiseVision,項目名稱:rise-node,代碼行數:7,代碼來源:AppManager.spec.ts

示例5: it

        it("Toggles verbosity", function(done) {
            LoggingHelper.initialize(true);
            let logger = function (log: string) {
                assert(log.indexOf("Verbosity1") === -1);
                assert(log.indexOf("Verbosity3") === -1);

                if (log.indexOf("Verbosity2") !== -1) {
                    LoggingHelper.setVerbose(false);
                    winston.log("verbose", "Verbosity3");
                    winston.info("Verbosity4");
                }

                if (log.indexOf("Verbosity4") !== -1) {
                    done();
                }
            };

            // Stub stderr and stdout - seems winston sends to both
            // Though seemingly debug goes to stderr and info goes to stdout!
            sandbox.stub(process.stderr, "write", logger);
            sandbox.stub(process.stdout, "write", logger);

            winston.debug("Verbosity1", function () {
                LoggingHelper.setVerbose(true);
                winston.log("verbose", "Verbosity2");
            });
        });
開發者ID:bespoken,項目名稱:bst,代碼行數:27,代碼來源:logging-helper-test.ts

示例6: test

test('device ID is available after register event', async t => {
  const vapidKeys = generateVapidKeys();

  await testCase(
    t,
    BrowserUserAgent.ChromeMacSupported,
    vapidKeys.uniquePublic,
    vapidKeys.sharedPublic,
    SubscriptionStrategyKind.SubscribeNew,
    null,
    null
  );

  const serviceWorkerRegistration = await ServiceWorkerManager.getRegistration();
  const pushSubscription = await serviceWorkerRegistration.pushManager.getSubscription();
  const rawPushSubscription = RawPushSubscription.setFromW3cSubscription(pushSubscription);
  const randomPlayerId = Random.getRandomUuid();

  const registerEventPromise = new Promise(resolve => {
    OneSignal.emitter.on('register', async () => {
      const subscription = await Database.getSubscription();
      t.is(subscription.deviceId, randomPlayerId);
      resolve();
    });
  });

  const playerUpdateStub = sandbox.stub(OneSignal.context.updateManager, "sendPlayerUpdate").resolves();
  const playerCreateStub = sandbox.stub(OneSignal.context.updateManager, "sendPlayerCreate").resolves(randomPlayerId);

  await OneSignal.context.subscriptionManager.registerSubscription(rawPushSubscription);
  t.is(playerUpdateStub.calledOnce, false);
  t.is(playerCreateStub.calledOnce, true);
  await registerEventPromise;
});
開發者ID:OneSignal,項目名稱:OneSignal-Website-SDK,代碼行數:34,代碼來源:SubscriptionManager.ts

示例7: beforeEach

 beforeEach(() => {
   appStateStub.enqueueResponse('get', false); // loader.isSyncing
   appStateStub.enqueueResponse('get', true);  // rounds.isLoaded
   appStateStub.enqueueResponse('get', false); // rounds.isTicking
   appStateStub.enqueueResponse('get', 10); // node.consensus
   appStateStub.enqueueResponse('getComputed', false); // node.poorConsensus
   loadKeypairs();
   // currentSlot must not be the same slot of lastBlock => This will pass
   slotsStub.enqueueResponse('getSlotNumber', 97);
   slotsStub.enqueueResponse('getSlotNumber', 98);
   // currentSlot must have the same slotNumber of blockData => This will get catched
   slotsStub.enqueueResponse('getSlotNumber', 100);
   slotsStub.enqueueResponse('getSlotNumber', 100);
   getBlockSlotDataStub = sandbox.stub(instance, 'getBlockSlotData').resolves({ time: 11111, keypair: {} });
   broadcasterLogicStub.enqueueResponse('getPeers', Promise.resolve());
   blocksProcessModuleStub.enqueueResponse('generateBlock', Promise.resolve());
   catcherStub   = sandbox.stub(helpers, 'catchToLoggerAndRemapError');
   catcherStub.callsFake((rejectString) => {
     return (err: Error) => {
       catcherLastErr = err;
       return Promise.reject(rejectString);
     };
   });
   catcherLastErr = null;
 });
開發者ID:RiseVision,項目名稱:rise-node,代碼行數:25,代碼來源:forge.spec.ts

示例8: test

test("getCurrentNotificationType for granted permission: new user", async t => {
  sinonSandbox.stub(OneSignal.context.permissionManager, "getNotificationPermission")
    .resolves(NotificationPermission.Granted);
  sinonSandbox.stub(OneSignal.context.subscriptionManager, "isAlreadyRegisteredWithOneSignal").resolves(false);
    
  t.is(await MainHelper.getCurrentNotificationType(), SubscriptionStateKind.Default);
});
開發者ID:OneSignal,項目名稱:OneSignal-Website-SDK,代碼行數:7,代碼來源:MainHelper.ts

示例9: test

test("sendExternalUserIdUpdate makes an api call with the provided external user id", async t => {
  const deviceId = Random.getRandomUuid();
  const externalUserId = "external_email@example.com";
  
  sandbox.stub(OneSignal.context.updateManager, "getDeviceId").resolves(deviceId);
  const updatePlayerSpy = sandbox.stub(OneSignalApiShared, "updatePlayer");
  await OneSignal.context.updateManager.sendExternalUserIdUpdate(externalUserId);

  t.is(updatePlayerSpy.getCalls().length, 1);
  t.is(updatePlayerSpy.getCall(0).args[0], OneSignal.context.appConfig.appId);
  t.is(updatePlayerSpy.getCall(0).args[1], deviceId);
  t.is(updatePlayerSpy.getCall(0).args[2].hasOwnProperty("external_user_id"), true);
  t.is(updatePlayerSpy.getCall(0).args[2].external_user_id, externalUserId);

  await OneSignal.context.updateManager.sendExternalUserIdUpdate(undefined);

  t.is(updatePlayerSpy.getCalls().length, 2);
  t.is(updatePlayerSpy.getCall(1).args[0], OneSignal.context.appConfig.appId);
  t.is(updatePlayerSpy.getCall(1).args[1], deviceId);
  t.is(updatePlayerSpy.getCall(1).args[2].hasOwnProperty("external_user_id"), true);
  t.is(updatePlayerSpy.getCall(1).args[2].external_user_id, "");

  await OneSignal.context.updateManager.sendExternalUserIdUpdate(null);

  t.is(updatePlayerSpy.getCalls().length, 3);
  t.is(updatePlayerSpy.getCall(2).args[0], OneSignal.context.appConfig.appId);
  t.is(updatePlayerSpy.getCall(2).args[1], deviceId);
  t.is(updatePlayerSpy.getCall(2).args[2].hasOwnProperty("external_user_id"), true);
  t.is(updatePlayerSpy.getCall(2).args[2].external_user_id, "");
});
開發者ID:OneSignal,項目名稱:OneSignal-Website-SDK,代碼行數:30,代碼來源:UpdateManager.ts


注:本文中的Sinon.SinonSandbox.stub方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。