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


TypeScript Sinon.createSandbox函數代碼示例

本文整理匯總了TypeScript中Sinon.createSandbox函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript createSandbox函數的具體用法?TypeScript createSandbox怎麽用?TypeScript createSandbox使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


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

示例1: describe

describe('File Manager', () => {
  const configuration = new Configuration('manager.com', 'secret', 'appId');
  const authenticator = new Authenticator(configuration);
  const httpClient = new HTTPClient(authenticator);
  const fileUploader = new FileUploader(configuration, httpClient);
  const fileManager = new FileManager(configuration, httpClient, fileUploader);
  const sandbox = sinon.createSandbox();

  const apiServer = nock('https://manager.com/').defaultReplyHeaders({
    'Content-Type': 'application/json',
  });

  afterEach(() => {
    nock.cleanAll();
    sandbox.verifyAndRestore();
  });

  it('listFiles - default', done => {
    apiServer
      .get('/_api/files/ls_dir')
      .once()
      .query(true)
      .replyWithFile(200, repliesDir + 'list-files-response.json');

    fileManager.listFiles('path').then(data => {
      expect(data).to.deep.equal(
        new ListFilesResponse({
          nextPageToken: 'next',
          files: [
            {
              id: 'd0e18fd468cd4e53bc2bbec3ca4a8676',
              hash: 'd41d8cd98f00b204e9800998ecf8427e',
              path: '/place-holder.txt',
              mimeType: 'text/plain',
              type: '-',
              size: 0,
              acl: 'public',
              bucket: 'bucket-name',
              dateCreated: '2017-02-20T14:23:42Z',
              dateUpdated: '2017-02-20T14:23:42Z',
            },
            {
              id: 'f65c0c70bec44b86bb543cc166800f03',
              hash: null,
              path: '/kb',
              mimeType: DescriptorMimeType.Folder,
              type: 'd',
              size: 0,
              acl: 'public',
              bucket: null,
              dateCreated: '2017-02-20T14:22:51Z',
              dateUpdated: '2017-02-20T14:22:51Z',
            },
          ].map(fileDescriptorData => new FileDescriptor(fileDescriptorData)),
        }),
      );

      done();
    });
  });

  it('listFiles - page', done => {
    apiServer
      .get('/_api/files/ls_dir')
      .once()
      .query({
        path: 'path',
        orderDirection: OrderDirection.ASC,
        nextPageToken: 'c',
        orderBy: 'date',
        pageSize: 10,
        type: FileType.FOLDER,
      })
      .replyWithFile(200, repliesDir + 'list-files-response.json');

    fileManager
      .listFiles('path', {
        orderDirection: OrderDirection.ASC,
        nextPageToken: 'c',
        orderBy: 'date',
        pageSize: 10,
        type: FileType.FOLDER,
      })
      .then(() => {
        done();
      });
  });

  describe('createFolder', () => {
    it('should return resolved promise with public folder(acl set with public by default)', done => {
      apiServer
        .post('/_api/files')
        .once()
        .query(true)
        .replyWithFile(200, repliesDir + 'create-folder-success-response.json');

      fileManager.createFolder({ path: 'bla' }).then(data => {
        expect(data).to.deep.equal(
          new FileDescriptor({
            mimeType: DescriptorMimeType.Folder,
//.........這裏部分代碼省略.........
開發者ID:wix,項目名稱:media-platform-js-sdk,代碼行數:101,代碼來源:file-manager.spec.ts

示例2: describe

  describe("build()", () => {
    const sandbox = Sinon.createSandbox();
    before(() => {
      sandbox.stub(HandlerBuilder.prototype as any, "invoke");
      sandbox.stub(FilterBuilder.prototype, "build");
    });

    after(() => {
      sandbox.restore();
    });

    afterEach(() => {
      sandbox.resetHistory();
    });

    describe("when is a middleware", () => {
      it("should have called invoke method with the correct parameters", inject([InjectorService], (injector: InjectorService) => {
        // GIVEN
        const handlerMetadata = new HandlerMetadata({
          target: Test,
          type: HandlerType.MIDDLEWARE,
          method: "use"
        });

        // WHEN
        const middleware: any = new HandlerBuilder(handlerMetadata).build(injector);
        middleware({request: "request"}, {response: "response"}, "function");

        // @ts-ignore
        HandlerBuilder.prototype.invoke.should.have.been.calledWithExactly({request: "request"}, {response: "response"}, "function");
        FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_REQUEST});
        FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_RESPONSE});
        FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_NEXT_FN});
      }));
    });

    describe("when is a middleware error", () => {
      it("should have called invoke method with the correct parameters", inject([InjectorService], (injector: InjectorService) => {
        // GIVEN
        const handlerMetadata = new HandlerMetadata({
          target: Test,
          type: HandlerType.MIDDLEWARE,
          method: "useErr"
        });
        const error = new Error();
        // WHEN
        const middleware: any = new HandlerBuilder(handlerMetadata).build(injector);
        middleware(error, {request: "request"}, {response: "response"}, "function");

        // @ts-ignore
        HandlerBuilder.prototype.invoke.should.have.been.calledWithExactly({request: "request"}, {response: "response"}, "function", error);
        FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_REQUEST});
        FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_RESPONSE});
        FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_NEXT_FN});
        FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_ERR});
      }));
    });

    describe("when is a controller injectable", () => {
      it("should have called invoke method with the correct parameters", inject([InjectorService], (injector: InjectorService) => {
        // GIVEN
        Metadata.set(PARAM_METADATA, [{service: EXPRESS_NEXT_FN}, {service: EXPRESS_ERR}], Test, "get");
        const handlerMetadata = new HandlerMetadata({
          target: Test,
          type: HandlerType.CONTROLLER,
          method: "get"
        });

        const error = new Error();
        // WHEN
        const middleware: any = new HandlerBuilder(handlerMetadata).build(injector);
        middleware(error, {request: "request"}, {response: "response"}, "function");

        // @ts-ignore
        HandlerBuilder.prototype.invoke.should.have.been.calledWithExactly({request: "request"}, {response: "response"}, "function", error);
        FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_NEXT_FN});
        FilterBuilder.prototype.build.should.have.been.calledWithExactly({service: EXPRESS_ERR});

        Metadata.set(PARAM_METADATA, undefined, Test, "get");
      }));
    });
  });
開發者ID:Romakita,項目名稱:ts-express-decorators,代碼行數:82,代碼來源:HandlerBuilder.spec.ts

示例3: beforeEach

 beforeEach(() => {
     sandbox = sinon.createSandbox();
 });
開發者ID:winseros,項目名稱:gulp-armapbo-plugin,代碼行數:3,代碼來源:pboBuilder.spec.ts

示例4: describe

describe("AsyncSettings", function() {
  const sinon = sinonStatic.createSandbox();

  let browserApi: typeof SinonChrome;
  let stubbedStorage: typeof SinonChrome.storage;
  let stubbedStorageArea: SinonChrome.storage.StubbedStorageArea;
  let log: Log;
  let asyncSettings: AsyncSettings;

  function createAsyncSettings(
      defaultSettings = {},
      storageReadyPromise = Promise.resolve(),
  ) {
    const storageAvailabilityController = new Module("", log);
    storageReadyPromise.then(() => storageAvailabilityController.startup());
    const storageApiWrapper = new StorageApiWrapper(
        null, log, stubbedStorage, storageAvailabilityController as any,
    );
    storageApiWrapper.startup();
    return new AsyncSettings(
        log,
        null,
        storageApiWrapper,
        defaultSettings,
    );
  }

  before(function() {
    browserApi = createBrowserApi();
    log = new Log();
  });

  beforeEach(function() {
    // MUST be in beforeEach (due to browserApi.flush() in afterEach):
    stubbedStorage = browserApi.storage;
    stubbedStorageArea = stubbedStorage.local;
  });

  afterEach(function() {
    browserApi.flush();
    sinon.reset();
  });

  describe(".get()", function() {
    it("should throw for a pref without a default", async function() {
      // setup
      stubbedStorageArea.get.resolves({});
      asyncSettings = createAsyncSettings();
      asyncSettings.startup();
      await asyncSettings.whenReady;

      // exercise + verify
      assert.throws(() => asyncSettings.get("foo"));
    });

    it("should return the default if no value is set", async function() {
      // setup
      stubbedStorageArea.get.resolves({
        foo: "bar",
      });
      asyncSettings = createAsyncSettings({
        foo: "bar",
      });
      asyncSettings.startup();
      await asyncSettings.whenReady;

      // exercise
      const result = await asyncSettings.get("foo");

      // verify
      sinon.assert.callCount(stubbedStorageArea.get, 1);
      sinon.assert.calledWithMatch(stubbedStorageArea.get, {foo: "bar"});
      assert.deepEqual(result, {foo: "bar"});
    });

    it("should return the stored value for a pref with both a default and a value", async function() {
      // setup
      stubbedStorageArea.get.resolves({
        foo: "BAZ",
      });
      asyncSettings = createAsyncSettings({
        foo: "baz",
      });
      asyncSettings.startup();
      await asyncSettings.whenReady;

      // exercise
      const result = await asyncSettings.get("foo");

      // verify
      sinon.assert.callCount(stubbedStorageArea.get, 1);
      sinon.assert.calledWithMatch(stubbedStorageArea.get, {foo: "baz"});
      assert.deepEqual(result, {foo: "BAZ"});
    });
  });

  describe(".onChanged", function() {
    it("should ignore prefs without a default value", async function() {
      // setup
      asyncSettings = createAsyncSettings();
//.........這裏部分代碼省略.........
開發者ID:RequestPolicyContinued,項目名稱:requestpolicy,代碼行數:101,代碼來源:test-async-settings.ts

示例5: describe

describe('archive manager', () => {
  const configuration = new Configuration('manager.com', 'secret', 'appId');
  const authenticator = new Authenticator(configuration);
  const httpClient = new HTTPClient(authenticator);
  const archiveManager = new ArchiveManager(configuration, httpClient);
  const sandbox = sinon.createSandbox();

  const apiServer = nock('https://manager.com/').defaultReplyHeaders({
    'Content-Type': 'application/json',
  });

  afterEach(() => {
    nock.cleanAll();
    sandbox.verifyAndRestore();
  });

  it('create archive', done => {
    apiServer
      .post('/_api/archive/create')
      .once()
      .query(true)
      .replyWithFile(200, repliesDir + 'create-archive-pending-response.json');

    const createArchiveRequest = new CreateArchiveRequest({
      destination: {
        directory: '/fish',
        acl: ACL.PUBLIC,
      },
      sources: [
        {
          fileId: 'archive-file',
        },
      ],
      archiveType: 'zip',
    });

    archiveManager
      .createArchive(createArchiveRequest)
      .then((job: Job<CreateArchiveSpecification>) => {
        expect(job.id).to.equal(
          '6b4da966844d4ae09417300f3811849b_dd0ecc5cbaba4f1b9aba08cc6fa7348b',
        );
        done();
      });
  });

  it('should create archive observable', done => {
    apiServer
      .post('/_api/archive/create')
      .once()
      .query(true)
      .replyWithFile(
        200,
        path.join(repliesDir, 'create-archive-pending-response.json'),
      );

    apiServer
      .get(
        '/_api/jobs/6b4da966844d4ae09417300f3811849b_dd0ecc5cbaba4f1b9aba08cc6fa7348b',
      )
      .once()
      .replyWithFile(
        200,
        path.join(repliesDir, 'create-archive-success-response.json'),
      );

    const progressSpy = sandbox.spy();
    archiveManager
      .createArchiveObservable({
        destination: {
          directory: '/fish',
          acl: ACL.PUBLIC,
        },
        sources: [
          {
            fileId: 'archive-file',
          },
        ],
        archiveType: 'zip',
      })
      .subscribe(progressSpy, done, () => {
        expect(progressSpy).to.have.been.calledTwice;
        expect(progressSpy.firstCall.args[0].id).to.equal(
          '6b4da966844d4ae09417300f3811849b_dd0ecc5cbaba4f1b9aba08cc6fa7348b',
        );
        expect(progressSpy.firstCall.args[0].status).to.equal('pending');
        expect(progressSpy.secondCall.args[0].id).to.equal(
          '6b4da966844d4ae09417300f3811849b_dd0ecc5cbaba4f1b9aba08cc6fa7348b',
        );
        expect(progressSpy.secondCall.args[0].status).to.equal('success');
        done();
      });
  });

  it('should create archive observable error', done => {
    apiServer
      .post('/_api/archive/create')
      .once()
      .query(true)
      .replyWithFile(
//.........這裏部分代碼省略.........
開發者ID:wix,項目名稱:media-platform-js-sdk,代碼行數:101,代碼來源:archive-manager.spec.ts

示例6: beforeEach

 beforeEach(function () {
   sandbox = sinon.createSandbox();
 });
開發者ID:robertohuertasm,項目名稱:vscode-icons,代碼行數:3,代碼來源:folderExtensions.test.ts

示例7: describe

describe('Settings', () => {
  const sandbox = Sinon.createSandbox();

  describe('isAudioNotificationSupported', () => {
    context('on macOS', () => {
      beforeEach(() => {
        sandbox.stub(process, 'platform').value('darwin');
      });

      afterEach(() => {
        sandbox.restore();
      });

      it('should return true', () => {
        assert.isTrue(Settings.isAudioNotificationSupported());
      });
    });

    context('on Windows', () => {
      context('version 7', () => {
        beforeEach(() => {
          sandbox.stub(process, 'platform').value('win32');
          sandbox.stub(os, 'release').returns('7.0.0');
        });

        afterEach(() => {
          sandbox.restore();
        });

        it('should return false', () => {
          assert.isFalse(Settings.isAudioNotificationSupported());
        });
      });

      context('version 8+', () => {
        beforeEach(() => {
          sandbox.stub(process, 'platform').value('win32');
          sandbox.stub(os, 'release').returns('8.0.0');
        });

        afterEach(() => {
          sandbox.restore();
        });

        it('should return true', () => {
          assert.isTrue(Settings.isAudioNotificationSupported());
        });
      });
    });

    context('on Linux', () => {
      beforeEach(() => {
        sandbox.stub(process, 'platform').value('linux');
      });

      afterEach(() => {
        sandbox.restore();
      });

      it('should return false', () => {
        assert.isFalse(Settings.isAudioNotificationSupported());
      });
    });
  });

  describe('isNotificationGroupingSupported', () => {
    context('on macOS', () => {
      beforeEach(() => {
        sandbox.stub(process, 'platform').value('darwin');
      });

      afterEach(() => {
        sandbox.restore();
      });

      it('should return true', () => {
        assert.isTrue(Settings.isNotificationGroupingSupported());
      });
    });

    context('on Windows', () => {
      context('version 7', () => {
        beforeEach(() => {
          sandbox.stub(process, 'platform').value('win32');
          sandbox.stub(os, 'release').returns('7.0.0');
        });

        afterEach(() => {
          sandbox.restore();
        });

        it('should return false', () => {
          assert.isFalse(Settings.isNotificationGroupingSupported());
        });
      });

      context('version 8+', () => {
        beforeEach(() => {
          sandbox.stub(process, 'platform').value('win32');
          sandbox.stub(os, 'release').returns('8.0.0');
//.........這裏部分代碼省略.........
開發者ID:VetoPlayer,項目名稱:Signal-Desktop,代碼行數:101,代碼來源:Settings_test.ts

示例8: beforeEach

 beforeEach(() => {
   sandbox = sinon.createSandbox();
   container = createContainer();
   loggerStub = container.get(Symbols.helpers.logger);
   instance = new BlockProgressLogger(10, 2, 'My message', loggerStub);
 });
開發者ID:RiseVision,項目名稱:rise-node,代碼行數:6,代碼來源:blocksProgressLogger.spec.ts

示例9: beforeEach

  beforeEach(() => {
    sandbox    = sinon.createSandbox();
    container = createContainer();
    clock      = sandbox.useFakeTimers();
    fakeConfig = { forging: { secret: ['secret1', 'secret2'] } };

    jobsQueueStub           = container.get(Symbols.helpers.jobsQueue);
    loggerStub              = container.get(Symbols.helpers.logger);
    edStub                  = container.get(Symbols.helpers.ed);
    slotsStub               = container.get(Symbols.helpers.slots);
    appStateStub            = container.get(Symbols.logic.appState);
    broadcasterLogicStub    = container.get(Symbols.logic.broadcaster);
    accountsModuleStub      = container.get(Symbols.modules.accounts);
    blocksModuleStub        = container.get(Symbols.modules.blocks);
    delegatesModuleStub     = container.get(Symbols.modules.delegates);
    transactionsModuleStub  = container.get(Symbols.modules.transactions);
    blocksProcessModuleStub = container.get(Symbols.modules.blocksSubModules.process);
    sequenceStub            = {
      addAndPromise: sandbox.spy((w) => {
        return Promise.resolve(
          w()
        );
      }),
    };

    instance = new ForgeModule();
    instance = instance as any;

    instance.enabledKeys         = {};
    instance.config              = fakeConfig;
    instance.constants           = constants;
    instance.jobsQueue           = jobsQueueStub;
    instance.logger              = loggerStub;
    instance.ed                  = edStub;
    instance.defaultSequence     = sequenceStub;
    instance.slots               = slotsStub;
    instance.appState            = appStateStub;
    instance.broadcasterLogic    = broadcasterLogicStub;
    instance.accountsModule      = accountsModuleStub;
    instance.blocksModule        = blocksModuleStub;
    instance.delegatesModule     = delegatesModuleStub;
    instance.transactionsModule  = transactionsModuleStub;
    instance.blocksProcessModule = blocksProcessModuleStub;

    sha256Spy              = sandbox.spy(supersha, 'sha256');
    blocksModuleStub.lastBlock = BlocksModel.classFromPOJO({
      blockSignature      : Buffer.from('blockSignature'),
      generatorPublicKey  : Buffer.from('pubKey'),
      height              : 12422,
      id                  : 'blockID',
      numberOfTransactions: 0,
      payloadHash         : Buffer.from('payload'),
      payloadLength       : 0,
      previousBlock       : 'previous',
      reward              : 15,
      timestamp           : Date.now(),
      totalAmount         : 0,
      totalFee            : 0,
      version             : 1,
    });
    loadKeypairs               = () => {
      instance.enabledKeys = {
        aaaa: true,
        bbbb: true,
        cccc: true,
      };
      instance.keypairs    = {
        aaaa: { publicKey: Buffer.from('aaaa', 'hex') },
        bbbb: { publicKey: Buffer.from('bbbb', 'hex') },
        cccc: { publicKey: Buffer.from('cccc', 'hex') },
      };
    };
  });
開發者ID:RiseVision,項目名稱:rise-node,代碼行數:73,代碼來源:forge.spec.ts

示例10: beforeEach

  beforeEach(() => {
    sandbox = sinon.createSandbox();
    container = createContainer();
    instance = new TransactionPool();
    fakeBus = {message: sandbox.stub().resolves()};
    fakeAppState = {get: sandbox.stub()};
    jqStub = container.get(Symbols.helpers.jobsQueue);
    loggerStub = container.get(Symbols.helpers.logger);
    transactionLogicStub = container.get(Symbols.logic.transaction);
    accountsModuleStub = container.get(Symbols.modules.accounts);
    balanceSequenceStub = container.getTagged(Symbols.helpers.sequence,
      Symbols.helpers.sequence, Symbols.tags.helpers.balancesSequence);

    // dependencies
    (instance as any).bus = fakeBus;
    (instance as any).jobsQueue = jqStub;
    (instance as any).logger = loggerStub;
    (instance as any).appState = fakeAppState;
    (instance as any).balancesSequence = balanceSequenceStub;
    (instance as any).transactionLogic = transactionLogicStub;
    (instance as any).accountsModule = accountsModuleStub;
    (instance as any).config = {
      broadcasts: {
        broadcastInterval: 1500,
        releaseLimit: 100,
      },
      transactions: {
        maxTxsPerQueue: 50,
      },
    };
    instance.afterConstruction();
    spiedQueues = {
      bundled: {},
      multisignature: {},
      queued: {},
      unconfirmed: {},
    };
    // we preserve behavior of the inner queues but we spy on all methods.
    ['unconfirmed', 'bundled', 'queued', 'multisignature'].forEach((queueName) => {
      if (typeof spiedQueues[queueName] === 'undefined') {
        spiedQueues[queueName] = {};
      }
      ['has', 'remove', 'add', 'get', 'reindex', 'list', 'listWithPayload'].forEach((method: string) => {
        spiedQueues[queueName][method] = sandbox.spy(instance[queueName], method);
      });
    });

    tx = {
      amount         : 108910891000000,
      asset          : {},
      fee            : 10,
      id             : '8139741256612355994',
      recipientId    : '15256762582730568272R',
      senderId       : '1233456789012345R',
      senderPublicKey: Buffer.from('6588716f9c941530c74eabdf0b27b1a2bac0a1525e9605a37e6c0b3817e58fe3', 'hex'),
      signature      : Buffer.from('f8fbf9b8433bf1bbea971dc8b14c6772d33c7dd285d84c5e6c984b10c4141e9f' +
                       'a56ace902b910e05e98b55898d982b3d5b9bf8bd897083a7d1ca1d5028703e03', 'hex'),
      timestamp      : 0,
      type           : TransactionType.SEND,
    };

    // Clone the tx to separate objects with different IDs
    tx2 = Object.assign({}, tx);
    tx2.id = 'tx2';

    tx3 = Object.assign({}, tx);
    tx3.id = 'tx3';
    sandbox.resetHistory();
  });
開發者ID:RiseVision,項目名稱:rise-node,代碼行數:69,代碼來源:transactionPool.spec.ts


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