beforeEach: function() {
   application = startApp();
   sandbox = sinon.sandbox.create();
 },
 beforeEach(() => {
   sandbox = sinon.sandbox.create();
 });
 beforeEach(function () {
   this.sinon = sinon.sandbox.create();
 });
 beforeEach(function () {
   sandbox = sinon.sandbox.create()
   component = this.subject()
 })
 beforeEach(() => {
   sandbox = sinon.sandbox.create();
   isIos = false;
   isSafari = false;
 });
 beforeEach(() => {
   sandbox = sinon.sandbox.create();
   ampdoc = new AmpDocSingle(window);
 });
 beforeEach(function() {
     // Create a sandbox for the test
     sandbox = sinon.sandbox.create();
 });
Beispiel #8
0
describe('donations.routes.test.js', () => {

  var application;
  var application2;
  var user;
  var group;
  var group2;
  var nocks = {};
  var stripeEmail;
  var sandbox = sinon.sandbox.create();

  var stubStripe = () => {
    var mock = stripeMock.accounts.create;
    mock.email = chance.email();
    stripeEmail = mock.email;

    var stub = sinon.stub(app.stripe.accounts, 'create');
    stub.yields(null, mock);
  };

  var mailgunStub = sinon.stub(app.mailgun, 'sendMail');

  beforeEach((done) => {
    utils.cleanAllDb((e, app) => {
      application = app;
      done();
    });
  });

  // Create a stub for clearbit
  beforeEach((done) => {
    utils.clearbitStubBeforeEach(sandbox);
    done();
  });

  // Create a user.
  beforeEach((done) => {
    models.User.create(userData).done((e, u) => {
      expect(e).to.not.exist;
      user = u;
      done();
    });
  });

  // Nock for customers.create.
  beforeEach(() => {
    nocks['customers.create'] = nock(STRIPE_URL)
      .post('/v1/customers')
      .reply(200, stripeMock.customers.create);
  });

  // Nock for retrieving balance transaction
  beforeEach(() => {
    nocks['balance.retrieveTransaction'] = nock(STRIPE_URL)
      .get('/v1/balance/history/txn_165j8oIqnMN1wWwOKlPn1D4y')
      .reply(200, stripeMock.balance);
  });

  beforeEach(() => {
    stubStripe();
  });

  // Create a group.
  beforeEach((done) => {
    request(app)
      .post('/groups')
      .set('Authorization', 'Bearer ' + user.jwt(application))
      .send({
        group: groupData,
        role: roles.HOST
      })
      .expect(200)
      .end((e, res) => {
        expect(e).to.not.exist;
        models.Group
          .find(parseInt(res.body.id))
          .then((g) => {
            group = g;
            done();
          })
          .catch(done);
      });
  });

  beforeEach(() => {
    app.stripe.accounts.create.restore();
    stubStripe();
  });

  // Create a second group.
  beforeEach((done) => {
    request(app)
      .post('/groups')
      .set('Authorization', 'Bearer ' + user.jwt(application))
      .send({
        group: utils.data('group2'),
        role: roles.HOST
      })
      .expect(200)
      .end((e, res) => {
        expect(e).to.not.exist;
        models.Group
          .find(parseInt(res.body.id))
          .then((g) => {
            group2 = g;
            done();
          })
          .catch(done);
      });
  });

  beforeEach(() => {
    app.stripe.accounts.create.restore();
  });

  beforeEach((done) => {
    models.StripeAccount.create({
      accessToken: 'abc'
    })
    .then((account) => user.setStripeAccount(account))
    .then(() => done())
    .catch(done);
  });

  beforeEach((done) => {
    models.ConnectedAccount.create({
      provider: 'paypal',
      // Sandbox api keys
      clientId: 'AZaQpRstiyI1ymEOGUXXuLUzjwm3jJzt0qrI__txWlVM29f0pTIVFk5wM9hLY98w5pKCE7Rik9QYvdYA',
      secret: 'EILQQAMVCuCTyNDDOWTGtS7xBQmfzdMcgSVZJrCaPzRbpGjQFdd8sylTGE-8dutpcV0gJkGnfDE0PmD8'
    })
    .then((account) => account.setUser(user))
    .then(() => done())
    .catch(done);
  });

  // Create an application which has only access to `group`
  beforeEach((done) => {
    models.Application.create(utils.data('application2')).done((e, a) => {
      expect(e).to.not.exist;
      application2 = a;
      application2.addGroup(group2).done(done);
    });
  });

  // Nock for charges.create.
  beforeEach(() => {
    var params = [
      'amount=' + CHARGE * 100,
      'currency=' + CURRENCY,
      'customer=' + stripeMock.customers.create.id,
      'description=' + encodeURIComponent('One time donation to ' + group.name),
      'application_fee=54',
      encodeURIComponent('metadata[groupId]') + '=' + group.id,
      encodeURIComponent('metadata[groupName]') + '=' + encodeURIComponent(groupData.name),
      encodeURIComponent('metadata[customerEmail]') + '=' + encodeURIComponent(user.email),
      encodeURIComponent('metadata[paymentMethodId]') + '=1'
    ].join('&');

    nocks['charges.create'] = nock(STRIPE_URL)
      .post('/v1/charges', params)
      .reply(200, stripeMock.charges.create);
  });

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

  afterEach(() => {
    utils.clearbitStubAfterEach(sandbox);
  });

  /**
   * Post a payment.
   */
  describe('#postPayments', () => {

    describe('Payment success by a group\'s user', () => {

      beforeEach((done) => {
        request(app)
          .post('/groups/' + group.id + '/payments')
          .set('Authorization', 'Bearer ' + user.jwt(application))
          .send({
            payment: {
              stripeToken: STRIPE_TOKEN,
              amount: CHARGE,
              currency: CURRENCY,
              email: user.email
            }
          })
          .expect(200)
          .end(done);
      });

      it('successfully creates a Stripe customer', () => {
        expect(nocks['customers.create'].isDone()).to.be.true;
      });

      it('successfully creates a paymentMethod with the UserId', (done) => {
        models.PaymentMethod
          .findAndCountAll({})
          .then((res) => {
            expect(res.count).to.equal(1);
            expect(res.rows[0]).to.have.property('UserId', user.id);
            expect(res.rows[0]).to.have.property('token', STRIPE_TOKEN);
            expect(res.rows[0]).to.have.property('service', 'stripe');
            expect(res.rows[0]).to.have.property('customerId', stripeMock.customers.create.id);
            done();
          })
          .catch(done);
      });

      it('successfully makes a Stripe charge', () => {
        expect(nocks['charges.create'].isDone()).to.be.true;
      });

      it('successfully gets a Stripe balance', () => {
        expect(nocks['balance.retrieveTransaction'].isDone()).to.be.true;
      });

      it('successfully creates a donation in the database', (done) => {
        models.Donation
          .findAndCountAll({})
          .then((res) => {
            expect(res.count).to.equal(1);
            expect(res.rows[0]).to.have.property('UserId', user.id);
            expect(res.rows[0]).to.have.property('GroupId', group.id);
            expect(res.rows[0]).to.have.property('currency', CURRENCY);
            expect(res.rows[0]).to.have.property('amount', CHARGE*100);
            expect(res.rows[0]).to.have.property('title',
              `Donation to ${group.name}`);
            done();
          })
          .catch(done);
      });

      it('successfully creates a transaction in the database', (done) => {
        models.Transaction
          .findAndCountAll({})
          .then((res) => {
            expect(res.count).to.equal(1);
            expect(res.rows[0]).to.have.property('UserId', user.id);
            expect(res.rows[0]).to.have.property('PaymentMethodId', 1);
            expect(res.rows[0]).to.have.property('currency', CURRENCY);
            expect(res.rows[0]).to.have.property('type', constants.type.DONATION);
            expect(res.rows[0]).to.have.property('amount', CHARGE);
            expect(res.rows[0]).to.have.property('amountInTxnCurrency', 1400); // taken from stripe mocks
            expect(res.rows[0]).to.have.property('txnCurrency', 'USD');
            expect(res.rows[0]).to.have.property('hostFeeInTxnCurrency', 0);
            expect(res.rows[0]).to.have.property('platformFeeInTxnCurrency', 70);
            expect(res.rows[0]).to.have.property('paymentProcessorFeeInTxnCurrency', 155);
            expect(res.rows[0]).to.have.property('txnCurrencyFxRate', 0.785);
            expect(res.rows[0]).to.have.property('netAmountInGroupCurrency', 922)
            expect(res.rows[0]).to.have.property('paidby', user.id.toString());
            expect(res.rows[0]).to.have.property('approved', true);
            expect(res.rows[0].tags[0]).to.be.equal('Donation');
            expect(res.rows[0]).to.have.property('description',
              'Donation to ' + group.name);
            done();
          })
          .catch(done);
      });

    });

    describe('Next payment success with a same stripe token', () => {

      var CHARGE2 = 1.99;

      beforeEach((done) => {
        request(app)
          .post('/groups/' + group.id + '/payments')
          .set('Authorization', 'Bearer ' + user.jwt(application))
          .send({
            payment: {
              stripeToken: STRIPE_TOKEN,
              amount: CHARGE,
              currency: CURRENCY,
              email: user.email
            }
          })
          .expect(200)
          .end(done);
      });

      // New nock for customers.create.
      beforeEach(() => {
        nocks['customers.create2'] = nock(STRIPE_URL)
          .post('/v1/customers')
          .reply(200, stripeMock.customers.create);
      });

      // Nock for charges.create.
      beforeEach(() => {
        var params = [
          'amount=' + CHARGE2 * 100,
          'currency=' + CURRENCY,
          'customer=' + stripeMock.customers.create.id,
          'description=' + encodeURIComponent('One time donation to ' + group.name),
          'application_fee=9',
          encodeURIComponent('metadata[groupId]') + '=' + group.id,
          encodeURIComponent('metadata[groupName]') + '=' + encodeURIComponent(group.name),
          encodeURIComponent('metadata[customerEmail]') + '=' + encodeURIComponent(user.email),
          encodeURIComponent('metadata[paymentMethodId]') + '=1'
        ].join('&');

        nocks['charges.create2'] = nock(STRIPE_URL)
          .post('/v1/charges', params)
          .reply(200, stripeMock.charges.create);
      });

      // Nock for retrieving balance transaction
      beforeEach(() => {
        nocks['balance.retrieveTransaction'] = nock(STRIPE_URL)
          .get('/v1/balance/history/txn_165j8oIqnMN1wWwOKlPn1D4y')
          .reply(200, stripeMock.balance);
      });

      beforeEach((done) => {
        request(app)
          .post('/groups/' + group.id + '/payments')
          .set('Authorization', 'Bearer ' + user.jwt(application))
          .send({
            payment: {
              stripeToken: STRIPE_TOKEN,
              amount: CHARGE2,
              currency: CURRENCY,
              email: user.email
            }
          })
          .expect(200)
          .end(done);
      });

      it('does not re-create a Stripe Customer with a same token', () => {
        expect(nocks['customers.create2'].isDone()).to.be.false;
      });

      it('does not re-create a paymentMethod', (done) => {
        models.PaymentMethod
          .findAndCountAll({})
          .then((res) => {
            expect(res.count).to.equal(1);
            done();
          })
          .catch(done);
      });

      it('successfully makes a new Stripe charge', () => {
        expect(nocks['charges.create2'].isDone()).to.be.true;
      });

      it('successfully creates a donation in the database', (done) => {
        models.Donation
          .findAndCountAll({})
          .then((res) => {
            expect(res.count).to.equal(2);
            expect(res.rows[1]).to.have.property('amount', CHARGE2*100);
            done();
          })
          .catch(done);
      });

      it('successfully gets a Stripe balance', () => {
        expect(nocks['balance.retrieveTransaction'].isDone()).to.be.true;
      });

      it('successfully creates a new transaction', (done) => {
        models.Transaction
          .findAndCountAll({order: 'id'})
          .then((res) => {
            expect(res.count).to.equal(2);
            expect(res.rows[1]).to.have.property('amount', CHARGE2);
            done();
          })
          .catch(done);
      });

    });

    describe('Payment success by a user that is not part of the group yet', () => {

      // Nock for charges.create.
      beforeEach(() => {
        var params = [
          'amount=' + CHARGE * 100,
          'currency=' + CURRENCY,
          'customer=' + stripeMock.customers.create.id,
          'description=' + encodeURIComponent('One time donation to ' + group2.name),
          'application_fee=54',
          encodeURIComponent('metadata[groupId]') + '=' + group2.id,
          encodeURIComponent('metadata[groupName]') + '=' + encodeURIComponent(group2.name),
          encodeURIComponent('metadata[customerEmail]') + '=' + encodeURIComponent(EMAIL),
          encodeURIComponent('metadata[paymentMethodId]') + '=1'
        ].join('&');

        nocks['charges.create'] = nock(STRIPE_URL)
          .post('/v1/charges', params)
          .reply(200, stripeMock.charges.create);
      });

      beforeEach((done) => {
        request(app)
          .post('/groups/' + group2.id + '/payments')
          .send({
            api_key: application.api_key,
            payment: {
              stripeToken: STRIPE_TOKEN,
              amount: CHARGE,
              currency: CURRENCY,
              email: EMAIL
            }
          })
          .expect(200)
          .end(done);
      });

      it('successfully adds the user to the group as a backer', (done) => {
        group2
          .getUsers()
          .then((users) => {
            expect(users).to.have.length(2);
            var backer = _.find(users, {email: EMAIL});
            expect(backer.UserGroup.role).to.equal(roles.BACKER);
            done();
          })
          .catch(done);
      });

    });

    describe('Payment success by a user who is a MEMBER of the group and should become BACKER', () => {

      // Add a user as a MEMBER
      beforeEach((done) => {
        models.User.create(utils.data('user4')).done((e, u) => {
          expect(e).to.not.exist;
          user4 = u;
          group2
            .addUserWithRole(user4, roles.MEMBER)
            .done(done);
        });
      });

      // Nock for charges.create.
      beforeEach(() => {
        var params = [
          'amount=' + CHARGE * 100,
          'currency=' + CURRENCY,
          'customer=' + stripeMock.customers.create.id,
          'description=' + encodeURIComponent('One time donation to ' + group2.name),
          'application_fee=54',
          encodeURIComponent('metadata[groupId]') + '=' + group2.id,
          encodeURIComponent('metadata[groupName]') + '=' + encodeURIComponent(group2.name),
          encodeURIComponent('metadata[customerEmail]') + '=' + encodeURIComponent(user4.email),
          encodeURIComponent('metadata[paymentMethodId]') + '=1'
        ].join('&');

        nocks['charges.create'] = nock(STRIPE_URL)
          .post('/v1/charges', params)
          .reply(200, stripeMock.charges.create);
      });

      beforeEach((done) => {
        request(app)
          .post('/groups/' + group2.id + '/payments')
          .set('Authorization', 'Bearer ' + user4.jwt(application2))
          .send({
            payment: {
              stripeToken: STRIPE_TOKEN,
              amount: CHARGE,
              currency: CURRENCY,
              email: user4.email
            }
          })
          .expect(200)
          .end(done);
      });

      it('successfully adds the user to the group as a backer', (done) => {
        group2
          .getUsers()
          .then((users) => {
            expect(users).to.have.length(3);
            var backer = _.find(users, {email: user4.email});
            expect(backer.UserGroup.role).to.equal(roles.BACKER);
            done();
          })
          .catch(done);
      });

    });

    describe('Payment success by anonymous user', () => {

      var data = {
        stripeToken: STRIPE_TOKEN,
        amount: CHARGE,
        currency: CURRENCY,
        description: 'super description',
        vendor: '@vendor',
        paidby: '@paidby',
        tags: ['tag1', 'tag2'],
        status: 'super status',
        link: 'www.opencollective.com',
        comment: 'super comment',
        email: userData.email
      };

      // Nock for charges.create.
      beforeEach(() => {
        var params = [
          'amount=' + CHARGE * 100,
          'currency=' + CURRENCY,
          'customer=' + stripeMock.customers.create.id,
          'description=' + encodeURIComponent('One time donation to ' + group2.name),
          'application_fee=54',
          encodeURIComponent('metadata[groupId]') + '=' + group2.id,
          encodeURIComponent('metadata[groupName]') + '=' + encodeURIComponent(group2.name),
          encodeURIComponent('metadata[customerEmail]') + '=' + encodeURIComponent(userData.email),
          encodeURIComponent('metadata[paymentMethodId]') + '=1'
        ].join('&');

        nocks['charges.create'] = nock(STRIPE_URL)
          .post('/v1/charges', params)
          .reply(200, stripeMock.charges.create);
      });

      beforeEach('successfully makes a anonymous payment', (done) => {
        request(app)
          .post('/groups/' + group2.id + '/payments')
          .send({
            api_key: application2.api_key,
            payment: data
          })
          .expect(200)
          .end((e) => {
            expect(e).to.not.exist;
            done();
          });
      });

      it('successfully creates a Stripe customer', () => {
        expect(nocks['customers.create'].isDone()).to.be.true;
      });

      it('successfully creates a paymentMethod', (done) => {
        models.PaymentMethod
          .findAndCountAll({})
          .then((res) => {
            expect(res.count).to.equal(1);
            expect(res.rows[0]).to.have.property('UserId', 1);
            done();
          })
          .catch(done);
      });

      it('successfully makes a Stripe charge', () => {
        expect(nocks['charges.create'].isDone()).to.be.true;
      });

      it('successfully creates a user', (done) => {

        models.User.findAndCountAll({
          where: {
              email: userData.email
            }
        })
        .then((res) => {
          expect(res.count).to.equal(1);
          expect(res.rows[0]).to.have.property('email', userData.email);
          done();
        })
        .catch(done)
      })

      it('successfully creates a donation in the database', (done) => {
        models.Donation
          .findAndCountAll({})
          .then((res) => {
            expect(res.count).to.equal(1);
            expect(res.rows[0]).to.have.property('UserId', user.id);
            expect(res.rows[0]).to.have.property('GroupId', group2.id);
            expect(res.rows[0]).to.have.property('currency', CURRENCY);
            expect(res.rows[0]).to.have.property('amount', CHARGE*100);
            expect(res.rows[0]).to.have.property('title',
              'Donation to ' + group.name);
            done();
          })
          .catch(done);
      });

      it('successfully gets a Stripe balance', () => {
        expect(nocks['balance.retrieveTransaction'].isDone()).to.be.true;
      });

      it('successfully creates a transaction in the database', (done) => {
        models.Transaction
          .findAndCountAll({})
          .then((res) => {
            expect(res.count).to.equal(1);
            expect(res.rows[0]).to.have.property('GroupId', group2.id);
            expect(res.rows[0]).to.have.property('UserId', user.id);
            expect(res.rows[0]).to.have.property('PaymentMethodId', 1);
            expect(res.rows[0]).to.have.property('currency', CURRENCY);
            expect(res.rows[0]).to.have.property('tags');
            expect(res.rows[0]).to.have.property('payoutMethod', null);
            expect(res.rows[0]).to.have.property('amount', data.amount);
            expect(res.rows[0]).to.have.property('paidby', String(user.id));
            done();
          })
          .catch(done);
      });

      it('successfully send a thank you email', (done) => {
        expect(mailgunStub.lastCall.args[0].to).to.equal(userData.email);
        done();
      });

    });

    describe('Recurring payment success', () => {

      var data = {
        stripeToken: STRIPE_TOKEN,
        amount: 10,
        currency: CURRENCY,
        interval: 'month',
        description: 'super description',
        vendor: '@vendor',
        paidby: '@paidby',
        tags: ['tag1', 'tag2'],
        status: 'super status',
        link: 'www.opencollective.com',
        comment: 'super comment',
        email: EMAIL
      };

      var customerId = stripeMock.customers.create.id;
      var planId = generatePlanId({
        currency: CURRENCY,
        interval: data.interval,
        amount: data.amount * 100
      });

      var plan = _.extend({}, stripeMock.plans.create, {
        amount: data.amount,
        interval: data.interval,
        name: planId,
        id: planId
      });

      beforeEach(() => {
        nocks['plans.create'] = nock(STRIPE_URL)
          .post('/v1/plans')
          .reply(200, plan);
        var params = [
          `plan=${planId}`,
          'application_fee_percent=5',
          encodeURIComponent('metadata[groupId]') + '=' + group2.id,
          encodeURIComponent('metadata[groupName]') + '=' + encodeURIComponent(group2.name),
          encodeURIComponent('metadata[paymentMethodId]') + '=1'
        ].join('&');

      nocks['subscriptions.create'] = nock(STRIPE_URL)
        .post(`/v1/customers/${customerId}/subscriptions`, params)
        .reply(200, stripeMock.subscriptions.create);
      });

      describe('plan does not exist', () => {
        beforeEach((done) => {

          nocks['plans.retrieve'] = nock(STRIPE_URL)
            .get('/v1/plans/' + planId)
            .reply(200, {
              error: stripeMock.plans.create_not_found
            });

          request(app)
            .post('/groups/' + group2.id + '/payments')
            .send({
              api_key: application2.api_key,
              payment: data
            })
            .expect(200)
            .end((e, res) => {
              expect(e).to.not.exist;
              done();
            });
        });

        it('creates a plan if it doesn\'t exist', () => {
          expect(nocks['plans.retrieve'].isDone()).to.be.true;
          expect(nocks['plans.create'].isDone()).to.be.true;
        });

      });

      describe('plan exists', () => {

        beforeEach((done) => {

          nocks['plans.retrieve'] = nock(STRIPE_URL)
            .get('/v1/plans/' + planId)
            .reply(200, plan);

          request(app)
            .post('/groups/' + group2.id + '/payments')
            .send({
              api_key: application2.api_key,
              payment: data
            })
            .expect(200)
            .end((e, res) => {
              expect(e).to.not.exist;
              done();
            });
        });

        it('uses the existing plan', () => {
          expect(nocks['plans.create'].isDone()).to.be.false;
          expect(nocks['plans.retrieve'].isDone()).to.be.true;
        });

        it('creates a subscription', () => {
          expect(nocks['subscriptions.create'].isDone()).to.be.true;
        });

        it('successfully creates a donation in the database', (done) => {
          models.Donation
            .findAndCountAll({})
            .then((res) => {
              expect(res.count).to.equal(1);
              expect(res.rows[0]).to.have.property('UserId', 2);
              expect(res.rows[0]).to.have.property('GroupId', group2.id);
              expect(res.rows[0]).to.have.property('currency', CURRENCY);
              expect(res.rows[0]).to.have.property('amount', data.amount*100);
              expect(res.rows[0]).to.have.property('SubscriptionId');
              expect(res.rows[0]).to.have.property('title',
                `Donation to ${group.name}`);
              done();
            })
            .catch(done);
        });

        it('does not create a transaction', (done) => {
          models.Transaction
            .findAndCountAll({})
            .then((res) => {
              expect(res.count).to.equal(0);
              done();
            })
            .catch(done);
        });


        it('creates a Subscription model', (done) => {
          models.Subscription
            .findAndCountAll({})
            .then((res) => {
              const subscription = res.rows[0];

              expect(res.count).to.equal(1);
              expect(subscription).to.have.property('amount', data.amount);
              expect(subscription).to.have.property('interval', plan.interval);
              expect(subscription).to.have.property('stripeSubscriptionId', stripeMock.subscriptions.create.id);
              expect(subscription).to.have.property('data');
              expect(subscription).to.have.property('isActive', false);
              expect(subscription).to.have.property('currency', CURRENCY);
              done();
            })
            .catch(done);
        });

        it('fails if the interval is not month or year', (done) => {

          request(app)
            .post('/groups/' + group2.id + '/payments')
            .send({
              api_key: application2.api_key,
              payment: _.extend({}, data, {interval: 'something'})
            })
            .expect(400, {
              error: {
                code: 400,
                type: 'bad_request',
                message: 'Interval should be month or year.'
              }
            })
            .end(done);
        });
      });
    });

    describe('Paypal recurring donation', () => {
      describe('success', () => {
        var links;
        const token = 'EC-123';

        beforeEach((done) => {
          request(app)
            .post(`/groups/${group.id}/payments/paypal`)
            .send({
              payment: {
                amount: 10,
                currency: 'USD',
                interval: 'month'
              },
              api_key: application2.api_key
            })
            .end((err, res) => {
              expect(err).to.not.exist;
              links = res.body.links;
              done();
            });
        });

        it('creates a transaction and returns the links', (done) => {
          expect(links[0]).to.have.property('method', 'REDIRECT');
          expect(links[0]).to.have.property('rel', 'approval_url');
          expect(links[0]).to.have.property('href');

          expect(links[1]).to.have.property('method', 'POST');
          expect(links[1]).to.have.property('rel', 'execute');
          expect(links[1]).to.have.property('href');

          models.Transaction.findAndCountAll({
            include: [{
              model: models.Subscription
            }],
            paranoid: false
          })
          .then((res) => {
            expect(res.count).to.equal(1);
            const transaction = res.rows[0];
            const subscription = transaction.Subscription;

            expect(transaction).to.have.property('GroupId', group.id);
            expect(transaction).to.have.property('currency', 'USD');
            expect(transaction).to.have.property('tags');
            expect(transaction).to.have.property('interval', 'month');
            expect(transaction).to.have.property('amount', 10);

            expect(subscription).to.have.property('data');
            expect(subscription).to.have.property('interval', 'month');
            expect(subscription).to.have.property('amount', 10);

            done();
          })
          .catch(done);
        });

        it('executes the billing agreement', (done) => {
          const email = '*****@*****.**';

          // Taken from https://github.com/paypal/PayPal-node-SDK/blob/71dcd3a5e2e288e2990b75a54673fb67c1d6855d/test/mocks/generate_token.js
          nock('https://api.sandbox.paypal.com:443')
            .post('/v1/oauth2/token', "grant_type=client_credentials")
            .reply(200, "{\"scope\":\"https://uri.paypal.com/services/invoicing openid https://api.paypal.com/v1/developer/.* https://api.paypal.com/v1/payments/.* https://api.paypal.com/v1/vault/credit-paymentMethod/.* https://api.paypal.com/v1/vault/credit-paymentMethod\",\"access_token\":\"IUIkXAOcYVNHe5zcQajcNGwVWfoUcesp7-YURMLohPI\",\"token_type\":\"Bearer\",\"app_id\":\"APP-2EJ531395M785864S\",\"expires_in\":28800}");

          const executeRequest = nock('https://api.sandbox.paypal.com:443')
            .post(`/v1/payments/billing-agreements/${token}/agreement-execute`)
            .reply(200, {
              id: 'I-123',
              payer: {
                payment_method: 'paypal',
                status: 'verified',
                payer_info: {
                  email
                }
              }
            });

          request(app)
            .get(`/groups/${group.id}/transactions/1/callback?token=${token}`) // hardcode transaction id
            .end((err, res) => {
              expect(err).to.not.exist;
              expect(executeRequest.isDone()).to.be.true;
              const text = res.text;

              models.Transaction.findAndCountAll({
                include: [
                  { model: models.Subscription },
                  { model: models.User }
                ]
              })
              .then((res) => {
                expect(res.count).to.equal(1);
                const transaction = res.rows[0];
                const subscription = transaction.Subscription;
                const user = transaction.User;

                expect(subscription).to.have.property('data');
                expect(subscription.data).to.have.property('billingAgreementId');
                expect(subscription.data).to.have.property('plan');

                expect(user).to.have.property('email', email);

                expect(text).to.contain(`userid=${user.id}`)
                expect(text).to.contain('has_full_account=false')
                expect(text).to.contain('status=payment_success')

                return group.getUsers();
              })
              .then((users) => {
                const backer = _.find(users, {email: email});
                expect(backer.UserGroup.role).to.equal(roles.BACKER);
                done();
              })
              .catch(done);
            });
        });
      });
    });

    describe('Paypal single donation', () => {
      describe('success', () => {
        var links;
        const token = 'EC-123';
        const paymentId = 'PAY-123';
        const PayerID = 'ABC123';

        beforeEach((done) => {
          request(app)
            .post(`/groups/${group.id}/payments/paypal`)
            .send({
              payment: {
                amount: 10,
                currency: 'USD'
              },
              api_key: application2.api_key
            })
            .end((err, res) => {
              expect(err).to.not.exist;
              links = res.body.links;
              done();
            });
        });

        it('creates a transaction and returns the links', (done) => {
          const redirect = _.find(links, { method: 'REDIRECT' });

          expect(redirect).to.have.property('method', 'REDIRECT');
          expect(redirect).to.have.property('rel', 'approval_url');
          expect(redirect).to.have.property('href');

          models.Transaction.findAndCountAll({ paranoid: false })
          .then((res) => {
            expect(res.count).to.equal(1);
            const transaction = res.rows[0];

            expect(transaction).to.have.property('GroupId', group.id);
            expect(transaction).to.have.property('currency', 'USD');
            expect(transaction).to.have.property('tags');
            expect(transaction).to.have.property('interval', null);
            expect(transaction).to.have.property('SubscriptionId', null);
            expect(transaction).to.have.property('amount', 10);

            done();
          })
          .catch(done);
        });

        it('executes the billing agreement', (done) => {
          const email = '*****@*****.**';

          // Taken from https://github.com/paypal/PayPal-node-SDK/blob/71dcd3a5e2e288e2990b75a54673fb67c1d6855d/test/mocks/generate_token.js
          nock('https://api.sandbox.paypal.com:443')
            .post('/v1/oauth2/token', "grant_type=client_credentials")
            .reply(200, "{\"scope\":\"https://uri.paypal.com/services/invoicing openid https://api.paypal.com/v1/developer/.* https://api.paypal.com/v1/payments/.* https://api.paypal.com/v1/vault/credit-paymentMethod/.* https://api.paypal.com/v1/vault/credit-paymentMethod\",\"access_token\":\"IUIkXAOcYVNHe5zcQajcNGwVWfoUcesp7-YURMLohPI\",\"token_type\":\"Bearer\",\"app_id\":\"APP-2EJ531395M785864S\",\"expires_in\":28800}");

          const executeRequest = nock('https://api.sandbox.paypal.com')
            .post(`/v1/payments/payment/${paymentId}/execute`, { payer_id: PayerID})
            .reply(200, {
              id: 'I-123',
              payer: {
                payment_method: 'paypal',
                status: 'verified',
                payer_info: {
                  email
                }
              }
            });

          request(app)
            .get(`/groups/${group.id}/transactions/1/callback?token=${token}&paymentId=${paymentId}&PayerID=${PayerID}`) // hardcode transaction id
            .end((err, res) => {
              expect(err).to.not.exist;
              expect(executeRequest.isDone()).to.be.true;
              const text = res.text;

              models.Transaction.findAndCountAll({
                include: [
                  { model: models.Subscription },
                  { model: models.User }
                ]
              })
              .then((res) => {
                expect(res.count).to.equal(1);
                const transaction = res.rows[0];
                const user = transaction.User;

                expect(user).to.have.property('email', email);

                expect(text).to.contain(`userid=${user.id}`)
                expect(text).to.contain('has_full_account=false')
                expect(text).to.contain('status=payment_success')

                return group.getUsers();
              })
              .then((users) => {
                const backer = _.find(users, {email: email});
                expect(backer.UserGroup.role).to.equal(roles.BACKER);
                done();
              })
              .catch(done);
            });
        });
      });

      describe('errors', () => {
        it('fails if the interval is wrong', (done) => {
          request(app)
            .post(`/groups/${group.id}/payments/paypal`)
            .send({
              payment: {
                amount: 10,
                currency: 'USD',
                interval: 'abc'
              },
              api_key: application2.api_key
            })
            .expect(400, {
              error: {
                code: 400,
                type: 'bad_request',
                message: 'Interval should be month or year.'
              }
            })
            .end(done);
        });

        it('fails if it has no amount', (done) => {
          request(app)
            .post(`/groups/${group.id}/payments/paypal`)
            .send({
              payment: {
                currency: 'USD',
                interval: 'month'
              },
              api_key: application2.api_key
            })
            .expect(400, {
              error: {
                code: 400,
                type: 'bad_request',
                message: 'Payment Amount missing.'
              }
            })
            .end(done);
        });
      });
    });

    describe('Payment errors', () => {

      beforeEach(() => {
        nock.cleanAll();
        nocks['customers.create'] = nock(STRIPE_URL)
          .post('/v1/customers')
          .replyWithError(stripeMock.customers.createError);
      });

      it('fails if the accessToken contains live', (done) => {
        const payment = {
          stripeToken: STRIPE_TOKEN,
          amount: CHARGE,
          currency: CURRENCY
        };

        models.StripeAccount.create({ accessToken: 'sk_live_abc'})
        .then((account) => user.setStripeAccount(account))
        .then(() => {
          request(app)
            .post('/groups/' + group.id + '/payments')
            .set('Authorization', 'Bearer ' + user.jwt(application))
            .send({ payment })
            .expect(400, {
              error: {
                code: 400,
                type: 'bad_request',
                message: `You can't use a Stripe live key on ${process.env.NODE_ENV}`
              }
            })
            .end(done);
        })

      });

      it('fails paying because of a paymentMethod declined', (done) => {
        request(app)
          .post('/groups/' + group.id + '/payments')
          .set('Authorization', 'Bearer ' + user.jwt(application))
          .send({
            payment: {
              stripeToken: STRIPE_TOKEN,
              amount: CHARGE,
              currency: CURRENCY
            }
          })
          .expect(400)
          .then(res => {
            const error = res.body.error;
            expect(error.message).to.equal('Your paymentMethod was declined');
            expect(error.type).to.equal('StripePaymentMethodError');
            expect(error.code).to.equal(400);
            done();
          });
      });

    });

  });

});
Beispiel #9
0
 beforeEach(function() {
     sandbox = sinon.sandbox.create();
     mockConsoleWarning = sandbox.stub(console, 'warn');
 });
 beforeEach(() => {
   sandbox = sinon.sandbox.create();
   sandbox.stub(CollectionActions, "load").returns({type: null});
 });
Beispiel #11
0
 beforeEach(function (done) {
   s = sinon.sandbox.create()
   done()
 })
Beispiel #12
0
 beforeEach(function () {
   sandbox = sinon.sandbox.create();
   sandbox.stub(lib, 'fetch');
 });
Beispiel #13
0
  describe('add', () => {
    const sandbox = sinon.sandbox.create();

    const keystoreData = '1:IxR0geiUTMJp8ueHDkqeUJ0I9eEw4NJPXIJi22UDyfGfJSy4mH'
      + 'BBuGPkkAix/x/YFfIxo4tiKGdJ2oVTtU8LgKDkVoGdL+z7ylY4n3myatt6osqhI4lzJ9M'
      + 'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ==';

    beforeEach(() => {
      mockFs({
        '/data': {
          'test.keystore': JSON.stringify(keystoreData),
        }
      });

      sandbox.stub(prompt, 'confirm');
      sandbox.stub(prompt, 'question');

      sandbox.stub(Logger.prototype, 'log');
      sandbox.stub(Logger.prototype, 'error');
    });

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

    it('returns an error for a nonexistent keystore', async () => {
      const keystore = new Keystore('/data/nonexistent.keystore');
      const message = 'ERROR: Kibana keystore not found. Use \'create\' command to create one.';

      await add(keystore, 'foo');

      sinon.assert.calledOnce(Logger.prototype.error);
      sinon.assert.calledWith(Logger.prototype.error, message);
    });

    it('does not attempt to create a keystore', async () => {
      const keystore = new Keystore('/data/nonexistent.keystore');
      sandbox.stub(keystore, 'save');

      await add(keystore, 'foo');

      sinon.assert.notCalled(keystore.save);
    });

    it('prompts for existing key', async () => {
      prompt.confirm.returns(Promise.resolve(true));
      prompt.question.returns(Promise.resolve('bar'));

      const keystore = new Keystore('/data/test.keystore');
      await add(keystore, 'a2');

      sinon.assert.calledOnce(prompt.confirm);
      sinon.assert.calledOnce(prompt.question);

      const { args } = prompt.confirm.getCall(0);

      expect(args[0]).toEqual('Setting a2 already exists. Overwrite?');
    });

    it('aborts if overwrite is denied', async () => {
      prompt.confirm.returns(Promise.resolve(false));

      const keystore = new Keystore('/data/test.keystore');
      await add(keystore, 'a2');

      sinon.assert.notCalled(prompt.question);

      sinon.assert.calledOnce(Logger.prototype.log);
      sinon.assert.calledWith(Logger.prototype.log, 'Exiting without modifying keystore.');
    });

    it('overwrites without prompt if force is supplied', async () => {
      prompt.question.returns(Promise.resolve('bar'));

      const keystore = new Keystore('/data/test.keystore');
      sandbox.stub(keystore, 'save');

      await add(keystore, 'a2', { force: true });

      sinon.assert.notCalled(prompt.confirm);
      sinon.assert.calledOnce(keystore.save);
    });

    it('trims value', async () => {
      prompt.question.returns(Promise.resolve('bar\n'));

      const keystore = new Keystore('/data/test.keystore');
      sandbox.stub(keystore, 'save');

      await add(keystore, 'foo');

      expect(keystore.data.foo).toEqual('bar');
    });

    it('persists updated keystore', async () => {
      prompt.question.returns(Promise.resolve('bar\n'));


      const keystore = new Keystore('/data/test.keystore');
      sandbox.stub(keystore, 'save');

      await add(keystore, 'foo');

      sinon.assert.calledOnce(keystore.save);
    });

    it('accepts stdin', async () => {
      const keystore = new Keystore('/data/test.keystore');
      sandbox.stub(keystore, 'save');

      const stdin = new PassThrough();
      process.nextTick(() => {
        stdin.write('kibana\n');
        stdin.end();
      });

      await add(keystore, 'foo', { stdin: true, stdinStream: stdin });

      expect(keystore.data.foo).toEqual('kibana');
    });
  });
Beispiel #14
0
 beforeEach(function() {
   sandbox = sinon.sandbox.create();
   user = new User("foo");
   user.ondisconnect = sinon.spy();
 });
Beispiel #15
0
 beforeEach(() => {
     modelManager = new ModelManager();
     modelManager.addModelFile(testModel);
     sandbox = sinon.sandbox.create();
 });
Beispiel #16
0
 beforeEach(() => {
     sandbox = sinon.sandbox.create();
     container = new NodeContainer();
 });
function TripLifeCycle(localNetworkConfig, foreignNetworkConfig, tripConfig) {
  this.localNetworkConfig = localNetworkConfig;
  this.foreignNetworkConfig = foreignNetworkConfig;
  this.tripConfig = tripConfig;
  this.sandbox = sinon.sandbox.create();
  this.localClient;
  this.localClientSpy;
  this.localNetworkSpy;
  this.localNetwork;
  this.localProduct;
  this.foreignClient;
  this.foreignClientSpy;
  this.foreignNetworkSpy;
  this.foreignNetwork;
  this.foreignProduct;
  this.trip;
  this.sentForeignStatuses = [];
  this.currentUpdateCall = -1;
  var self = this;
  
  if(localNetworkConfig.endpointType === 'socket') {
    this.localClient = new SocketClient(localNetworkConfig.clientId, localNetworkConfig.name, localNetworkConfig.clientId,
      apiConfig.secureConnection);
  } else {
    this.localClient = new RestfulClient(localNetworkConfig.clientId, localNetworkConfig.name, apiConfig, 
      localNetworkConfig.tripthru.token, apiConfig.cert, apiConfig.key, apiConfig.passphrase, apiConfig.secureConnection);
  }
  this.localNetwork = NetworkFactory.createNetwork(this.localClient, localNetworkConfig);
	this.localProduct = this.localNetwork.products[0];
  if(localNetworkConfig.endpointType === 'socket') {
    this.localClient.setListener(this.localNetwork);
  }
  
  if(foreignNetworkConfig.endpointType === 'socket') {
    this.foreignClient = new SocketClient(foreignNetworkConfig.clientId, foreignNetworkConfig.name, foreignNetworkConfig.clientId,
      apiConfig.secureConnection);
  } else {
    this.foreignClient = new RestfulClient(foreignNetworkConfig.clientId, foreignNetworkConfig.name, apiConfig, 
      foreignNetworkConfig.tripthru.token, apiConfig.cert, apiConfig.key, apiConfig.passphrase, apiConfig.secureConnection);
  }
  // Wrap update trip status to track status changes
  var originalUpdateTripStatus = this.foreignClient.updateTripStatus;
  this.foreignClient.updateTripStatus = function(request) {
    self.sentForeignStatuses.push(request.status);
    return originalUpdateTripStatus.apply(this, [request]);
  };
  this.foreignNetwork = NetworkFactory.createNetwork(this.foreignClient, foreignNetworkConfig);
	this.foreignProduct = this.foreignNetwork.products[0];
  if(foreignNetworkConfig.endpointType === 'socket') {
    this.foreignClient.setListener(this.foreignNetwork);
  }
	
	this.trip = this.localProduct.createTrip(tripConfig.customer, tripConfig.pickupTime, tripConfig.from, tripConfig.to);
   
	this.localClientSpy = {
	  setNetworkInfo: this.sandbox.spy(this.localClient, 'setNetworkInfo'),
	  dispatchTrip: this.sandbox.spy(this.localClient, 'dispatchTrip'),
	  updateTripStatus: this.sandbox.spy(this.localClient, 'updateTripStatus'),
	  requestPayment: this.sandbox.spy(this.localClient, 'requestPayment'),
	  acceptPayment: this.sandbox.spy(this.localClient, 'acceptPayment')
	};
	this.localNetworkSpy = {
	  dispatchTrip: this.sandbox.spy(this.localNetwork, 'dispatchTrip'),
	  updateTripStatus: this.sandbox.spy(this.localNetwork, 'updateTripStatus'),
	  requestPayment: this.sandbox.spy(this.localNetwork, 'requestPayment'),
	  acceptPayment: this.sandbox.spy(this.localNetwork, 'acceptPayment')
	};
	this.localNetwork.getQuote = function(req) {
	  return Promise.resolve(TripThruApiFactory.createFailResponse('test client', resultCodes.rejected));
	};
	this.foreignClientSpy = {
	  setNetworkInfo: this.sandbox.spy(this.foreignClient, 'setNetworkInfo'),
	  dispatchTrip: this.sandbox.spy(this.foreignClient, 'dispatchTrip'),
	  updateTripStatus: this.sandbox.spy(this.foreignClient, 'updateTripStatus'),
	  requestPayment: this.sandbox.spy(this.foreignClient, 'requestPayment'),
	  acceptPayment: this.sandbox.spy(this.foreignClient, 'acceptPayment')
	};
	this.foreignNetworkSpy = {
	  dispatchTrip: this.sandbox.spy(this.foreignNetwork, 'dispatchTrip'),
	  updateTripStatus: this.sandbox.spy(this.foreignNetwork, 'updateTripStatus'),
	  requestPayment: this.sandbox.spy(this.foreignNetwork, 'requestPayment'),
	  acceptPayment: this.sandbox.spy(this.foreignNetwork, 'acceptPayment')
	};
	this.foreignNetwork.getQuote = function(req) {
	  return Promise.resolve(TripThruApiFactory.createFailResponse('test client', resultCodes.rejected));
	};
};
Beispiel #18
0
before(() => {
  sandbox = sinon.sandbox.create();

  connectionService = require('lib/modules/connection');
  connectionRepository = require('lib/modules/connection/repository');
});
Beispiel #19
0
 beforeEach(() => {
   sandbox = sinon.sandbox.create();
   ampdocShell = new AmpDocShell(window);
 });
Beispiel #20
0
exports.setUp = function (done) {
   setup.restore();
   sandbox = sinon.sandbox.create();
   done();
};
Beispiel #21
0
describe('With custom domain we can', function() {

    var sandbox = sinon.sandbox.create();

    var CONFIG = {
        clientId: 'clientId',
        clientSecret: 'clientSecret',
        scopes: ['corbel-qa:client'],
        urlBase: 'https://{{module}}-corbel.io/'
    };

    var RESOURCE_COLLECTION_URL = CONFIG.urlBase.replace('{{module}}', 'resources') + '{{domain}}/resource/{{resource}}' ;
    var WEBFS_URL = CONFIG.urlBase.replace('{{module}}', 'webfs') + '{{domain}}/{{resource}}' ;

    var corbelDriver, corbelRequestStub;

    beforeEach(function() {
        corbelDriver = corbel.getDriver(CONFIG);
        corbelRequestStub = sandbox.stub(corbel.request, 'send');
        corbelRequestStub.returns(Promise.resolve());
    });

    afterEach(function() {
        sandbox.restore();
    });

    it('add a custom domain value', function() {
        var resource = 'resource:entity';
        var customDomain = 'oneTestDomain';

        var url = RESOURCE_COLLECTION_URL.replace('{{resource}}', resource).replace('{{domain}}', customDomain);
        expect(corbelDriver.domain(customDomain).resources.collection(resource).getURL()).to.be.equal(url);
    });

    it('does not persist the value on resources configuration for consecutive calls', function(done){
        var resource = 'resource:entity';
        var customDomain = 'oneTestDomainTwo';

        var urlWithDomain = RESOURCE_COLLECTION_URL.replace('{{resource}}', resource).replace('{{domain}}', customDomain);
        var urlWithoutDomain = RESOURCE_COLLECTION_URL.replace('{{resource}}', resource).replace('{{domain}}', 'unauthenticated');

        expect(corbelDriver.domain(customDomain).resources.collection(resource).getURL()).to.be.equal(urlWithDomain);

        corbelDriver.domain(customDomain).resources.collection(resource)
            .get()
            .then(function(){
                expect(corbelDriver.resources.collection(resource).getURL()).to.be.equal(urlWithoutDomain);
            })
            .should.notify(done);
    });

    it('does not persist the value on webfs configuration for consecutive calls', function(done){
        var resource = 'index.html';
        var customDomain = 'oneTestDomainTwo';

        var urlWithDomain = WEBFS_URL.replace('{{resource}}', resource).replace('{{domain}}', customDomain + '/path');
        var urlWithoutDomain = WEBFS_URL.replace('{{resource}}', resource).replace('{{domain}}', 'unauthenticated' + '/path');

        expect(corbelDriver.domain(customDomain).webfs.webfs(resource)._buildUriWithDomain(resource)).to.be.equal(urlWithDomain);

        corbelDriver.domain(customDomain).webfs.webfs(resource).get()
            .then(function(){
                expect(corbelDriver.webfs.webfs(resource)._buildUriWithDomain(resource)).to.be.equal(urlWithoutDomain);
            })
            .should.notify(done);
    });
});
Beispiel #22
0
describe('Console Proxy Route', () => {
  const sandbox = sinon.sandbox.create();
  const teardowns = [];
  let request;

  beforeEach(() => {
    teardowns.push(() => sandbox.restore());

    sandbox.stub(Wreck, 'request', createWreckResponseStub());

    request = async (method, path) => {
      const server = new Server();

      server.connection({ port: 0 });
      server.route(createProxyRoute({
        baseUrl: 'http://localhost:9200'
      }));

      teardowns.push(() => server.stop());

      const params = [];
      if (path != null) params.push(`path=${path}`);
      if (method != null) params.push(`method=${method}`);
      return await server.inject({
        method: 'POST',
        url: `/api/console/proxy${params.length ? `?${params.join('&')}` : ''}`,
      });
    };
  });

  afterEach(async () => {
    await Promise.all(teardowns.splice(0).map(fn => fn()));
  });

  describe('query string', () => {
    describe('path', () => {
      describe('contains full url', () => {
        it('treats the url as a path', async () => {
          await request('GET', 'http://evil.com/test');
          sinon.assert.calledOnce(Wreck.request);
          const args = Wreck.request.getCall(0).args;
          expect(args[1]).to.be('http://localhost:9200/http://evil.com/test');
        });
      });
      describe('is missing', () => {
        it('returns a 400 error', async () => {
          const { statusCode } = await request('GET', undefined);
          expect(statusCode).to.be(400);
          sinon.assert.notCalled(Wreck.request);
        });
      });
      describe('is empty', () => {
        it('returns a 400 error', async () => {
          const { statusCode } = await request('GET', '');
          expect(statusCode).to.be(400);
          sinon.assert.notCalled(Wreck.request);
        });
      });
      describe('starts with a slash', () => {
        it('combines well with the base url', async () => {
          await request('GET', '/index/type/id');
          sinon.assert.calledOnce(Wreck.request);
          expect(Wreck.request.getCall(0).args[1]).to.be('http://localhost:9200/index/type/id');
        });
      });
      describe(`doesn't start with a slash`, () => {
        it('combines well with the base url', async () => {
          await request('GET', 'index/type/id');
          sinon.assert.calledOnce(Wreck.request);
          expect(Wreck.request.getCall(0).args[1]).to.be('http://localhost:9200/index/type/id');
        });
      });
    });
    describe('method', () => {
      describe('is missing', () => {
        it('returns a 400 error', async () => {
          const { statusCode } = await request(null, '/');
          expect(statusCode).to.be(400);
          sinon.assert.notCalled(Wreck.request);
        });
      });
      describe('is empty', () => {
        it('returns a 400 error', async () => {
          const { statusCode } = await request('', '/');
          expect(statusCode).to.be(400);
          sinon.assert.notCalled(Wreck.request);
        });
      });
      describe('is an invalid http method', () => {
        it('returns a 400 error', async () => {
          const { statusCode } = await request('foo', '/');
          expect(statusCode).to.be(400);
          sinon.assert.notCalled(Wreck.request);
        });
      });
      describe('is mixed case', () => {
        it('sends a request with the exact method', async () => {
          const { statusCode } = await request('HeAd', '/');
          expect(statusCode).to.be(200);
          sinon.assert.calledOnce(Wreck.request);
          expect(Wreck.request.getCall(0).args[0]).to.be('HeAd');
        });
      });
    });
  });
});
 beforeEach(function () {
   installer = new CygwinInstall(installerDataSvc, downloadUrl, null);
   sandbox = sinon.sandbox.create();
 });
Beispiel #24
0
 beforeEach(function () {
     sandbox = sinon.sandbox.create();
     req = {};
     res = {};
     next = sandbox.spy();
 });
Beispiel #25
0
var should = require('should'), // jshint ignore:line
    sinon = require('sinon'),

// Stuff we are testing
    helpers = require('../../../server/helpers'),

    sandbox = sinon.sandbox.create();

describe('{{tags}} helper', function () {
    afterEach(function () {
        sandbox.restore();
    });

    it('can return string with tags', function () {
        var tags = [{name: 'foo'}, {name: 'bar'}],
            rendered = helpers.tags.call(
                {tags: tags},
                {hash: {autolink: 'false'}}
            );
        should.exist(rendered);

        String(rendered).should.equal('foo, bar');
    });

    it('can use a different separator', function () {
        var tags = [{name: 'haunted'}, {name: 'ghost'}],
            rendered = helpers.tags.call(
                {tags: tags},
                {hash: {separator: '|', autolink: 'false'}}
            );
    setup(function (done) {
      sandbox = sinon.sandbox.create();

      done();
    });
 beforeEach(() => {
   Util.cleanDirectory('tmp');
   sandbox = sinon.sandbox.create();
 });
 setUp: function(done) {
   this.sandbox = sinon.sandbox.create();
   done();
 },
Beispiel #29
0
 beforeEach(function () {
   sandbox = sinon.sandbox.create();
 });
Beispiel #30
0
 beforeEach(() => {
   sandbox = sinon.sandbox.create();
   div = document.createElement('div');
   element = new BaseElement(div);
 });