fix test lint

This commit is contained in:
Matteo Pagliazzi
2019-10-08 20:45:38 +02:00
parent e37f4467f8
commit 85fb5f33aa
367 changed files with 6635 additions and 6080 deletions

View File

@@ -2,19 +2,20 @@ import moment from 'moment';
import {
generateGroup,
} from '../../../../../helpers/api-unit.helper.js';
} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import amzLib from '../../../../../../website/server/libs/payments/amazon';
import payments from '../../../../../../website/server/libs/payments/payments';
import common from '../../../../../../website/common';
import { createNonLeaderGroupMember } from '../paymentHelpers';
const i18n = common.i18n;
const { i18n } = common;
describe('Amazon Payments - Cancel Subscription', () => {
const subKey = 'basic_3mo';
let user, group, headers, billingAgreementId, subscriptionBlock, subscriptionLength;
let user; let group; let headers; let billingAgreementId; let subscriptionBlock; let
subscriptionLength;
let getBillingAgreementDetailsSpy;
let paymentCancelSubscriptionSpy;
@@ -50,7 +51,7 @@ describe('Amazon Payments - Cancel Subscription', () => {
getBillingAgreementDetailsSpy = sinon.stub(amzLib, 'getBillingAgreementDetails')
.resolves({
BillingAgreementDetails: {
BillingAgreementStatus: {State: 'Open'},
BillingAgreementStatus: { State: 'Open' },
},
});
}
@@ -81,7 +82,7 @@ describe('Amazon Payments - Cancel Subscription', () => {
getBillingAgreementDetailsSpy = sinon.stub(amzLib, 'getBillingAgreementDetails');
getBillingAgreementDetailsSpy.resolves({
BillingAgreementDetails: {
BillingAgreementStatus: {State: 'Closed'},
BillingAgreementStatus: { State: 'Closed' },
},
});
@@ -89,7 +90,7 @@ describe('Amazon Payments - Cancel Subscription', () => {
paymentCancelSubscriptionSpy.resolves({});
});
afterEach(function () {
afterEach(() => {
amzLib.getBillingAgreementDetails.restore();
payments.cancelSubscription.restore();
});
@@ -97,7 +98,7 @@ describe('Amazon Payments - Cancel Subscription', () => {
it('should throw an error if we are missing a subscription', async () => {
user.purchased.plan.customerId = undefined;
await expect(amzLib.cancelSubscription({user}))
await expect(amzLib.cancelSubscription({ user }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -108,7 +109,7 @@ describe('Amazon Payments - Cancel Subscription', () => {
it('should cancel a user subscription', async () => {
billingAgreementId = user.purchased.plan.customerId;
await amzLib.cancelSubscription({user, headers});
await amzLib.cancelSubscription({ user, headers });
expectAmazonCancelUserSubscriptionSpy();
expectAmazonStubs();
@@ -117,10 +118,10 @@ describe('Amazon Payments - Cancel Subscription', () => {
it('should close a user subscription if amazon not closed', async () => {
amzLib.getBillingAgreementDetails.restore();
expectBillingAggreementDetailSpy();
let closeBillingAgreementSpy = sinon.stub(amzLib, 'closeBillingAgreement').resolves({});
const closeBillingAgreementSpy = sinon.stub(amzLib, 'closeBillingAgreement').resolves({});
billingAgreementId = user.purchased.plan.customerId;
await amzLib.cancelSubscription({user, headers});
await amzLib.cancelSubscription({ user, headers });
expectAmazonStubs();
expect(closeBillingAgreementSpy).to.be.calledOnce;
@@ -132,7 +133,7 @@ describe('Amazon Payments - Cancel Subscription', () => {
});
it('should throw an error if group is not found', async () => {
await expect(amzLib.cancelSubscription({user, groupId: 'fake-id'}))
await expect(amzLib.cancelSubscription({ user, groupId: 'fake-id' }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 404,
name: 'NotFound',
@@ -141,9 +142,9 @@ describe('Amazon Payments - Cancel Subscription', () => {
});
it('should throw an error if user is not group leader', async () => {
let nonLeader = await createNonLeaderGroupMember(group);
const nonLeader = await createNonLeaderGroupMember(group);
await expect(amzLib.cancelSubscription({user: nonLeader, groupId: group._id}))
await expect(amzLib.cancelSubscription({ user: nonLeader, groupId: group._id }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -154,7 +155,7 @@ describe('Amazon Payments - Cancel Subscription', () => {
it('should cancel a group subscription', async () => {
billingAgreementId = group.purchased.plan.customerId;
await amzLib.cancelSubscription({user, groupId: group._id, headers});
await amzLib.cancelSubscription({ user, groupId: group._id, headers });
expectAmazonCancelGroupSubscriptionSpy(group._id);
expectAmazonStubs();
@@ -163,10 +164,10 @@ describe('Amazon Payments - Cancel Subscription', () => {
it('should close a group subscription if amazon not closed', async () => {
amzLib.getBillingAgreementDetails.restore();
expectBillingAggreementDetailSpy();
let closeBillingAgreementSpy = sinon.stub(amzLib, 'closeBillingAgreement').resolves({});
const closeBillingAgreementSpy = sinon.stub(amzLib, 'closeBillingAgreement').resolves({});
billingAgreementId = group.purchased.plan.customerId;
await amzLib.cancelSubscription({user, groupId: group._id, headers});
await amzLib.cancelSubscription({ user, groupId: group._id, headers });
expectAmazonStubs();
expect(closeBillingAgreementSpy).to.be.calledOnce;

View File

@@ -3,11 +3,12 @@ import amzLib from '../../../../../../website/server/libs/payments/amazon';
import payments from '../../../../../../website/server/libs/payments/payments';
import common from '../../../../../../website/common';
const i18n = common.i18n;
const { i18n } = common;
describe('Amazon Payments - Checkout', () => {
const subKey = 'basic_3mo';
let user, orderReferenceId, headers;
let user; let orderReferenceId; let
headers;
let setOrderReferenceDetailsSpy;
let confirmOrderReferenceSpy;
let authorizeSpy;
@@ -62,7 +63,7 @@ describe('Amazon Payments - Checkout', () => {
expect(closeOrderReferenceSpy).to.be.calledWith({ AmazonOrderReferenceId: orderReferenceId });
}
beforeEach(function () {
beforeEach(() => {
user = new User();
headers = {};
orderReferenceId = 'orderReferenceId';
@@ -88,7 +89,7 @@ describe('Amazon Payments - Checkout', () => {
sinon.stub(common, 'uuid').returns('uuid-generated');
});
afterEach(function () {
afterEach(() => {
amzLib.setOrderReferenceDetails.restore();
amzLib.confirmOrderReference.restore();
amzLib.authorize.restore();
@@ -101,7 +102,7 @@ describe('Amazon Payments - Checkout', () => {
function expectBuyGemsStub (paymentMethod, gift) {
expect(paymentBuyGemsStub).to.be.calledOnce;
let expectedArgs = {
const expectedArgs = {
user,
paymentMethod,
headers,
@@ -112,7 +113,7 @@ describe('Amazon Payments - Checkout', () => {
it('should purchase gems', async () => {
sinon.stub(user, 'canGetGems').resolves(true);
await amzLib.checkout({user, orderReferenceId, headers});
await amzLib.checkout({ user, orderReferenceId, headers });
expectBuyGemsStub(amzLib.constants.PAYMENT_METHOD);
expectAmazonStubs();
@@ -121,9 +122,9 @@ describe('Amazon Payments - Checkout', () => {
});
it('should error if gem amount is too low', async () => {
let receivingUser = new User();
const receivingUser = new User();
receivingUser.save();
let gift = {
const gift = {
type: 'gems',
gems: {
amount: 0,
@@ -131,7 +132,9 @@ describe('Amazon Payments - Checkout', () => {
},
};
await expect(amzLib.checkout({gift, user, orderReferenceId, headers}))
await expect(amzLib.checkout({
gift, user, orderReferenceId, headers,
}))
.to.eventually.be.rejected.and.to.eql({
httpCode: 400,
message: 'Amount must be at least 1.',
@@ -141,18 +144,19 @@ describe('Amazon Payments - Checkout', () => {
it('should error if user cannot get gems gems', async () => {
sinon.stub(user, 'canGetGems').resolves(false);
await expect(amzLib.checkout({user, orderReferenceId, headers})).to.eventually.be.rejected.and.to.eql({
httpCode: 401,
message: i18n.t('groupPolicyCannotGetGems'),
name: 'NotAuthorized',
});
await expect(amzLib.checkout({ user, orderReferenceId, headers }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
message: i18n.t('groupPolicyCannotGetGems'),
name: 'NotAuthorized',
});
user.canGetGems.restore();
});
it('should gift gems', async () => {
let receivingUser = new User();
const receivingUser = new User();
await receivingUser.save();
let gift = {
const gift = {
type: 'gems',
uuid: receivingUser._id,
gems: {
@@ -160,16 +164,18 @@ describe('Amazon Payments - Checkout', () => {
},
};
amount = 16 / 4;
await amzLib.checkout({gift, user, orderReferenceId, headers});
await amzLib.checkout({
gift, user, orderReferenceId, headers,
});
expectBuyGemsStub(amzLib.constants.PAYMENT_METHOD_GIFT, gift);
expectAmazonStubs();
});
it('should gift a subscription', async () => {
let receivingUser = new User();
const receivingUser = new User();
receivingUser.save();
let gift = {
const gift = {
type: 'subscription',
subscription: {
key: subKey,
@@ -178,7 +184,9 @@ describe('Amazon Payments - Checkout', () => {
};
amount = common.content.subscriptionBlocks[subKey].price;
await amzLib.checkout({user, orderReferenceId, headers, gift});
await amzLib.checkout({
user, orderReferenceId, headers, gift,
});
gift.member = receivingUser;
expect(paymentCreateSubscritionStub).to.be.calledOnce;

View File

@@ -2,18 +2,19 @@ import cc from 'coupon-code';
import {
generateGroup,
} from '../../../../../helpers/api-unit.helper.js';
} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import { model as Coupon } from '../../../../../../website/server/models/coupon';
import amzLib from '../../../../../../website/server/libs/payments/amazon';
import payments from '../../../../../../website/server/libs/payments/payments';
import common from '../../../../../../website/common';
const i18n = common.i18n;
const { i18n } = common;
describe('Amazon Payments - Subscribe', () => {
const subKey = 'basic_3mo';
let user, group, amount, billingAgreementId, sub, coupon, groupId, headers;
let user; let group; let amount; let billingAgreementId; let sub; let coupon; let groupId; let
headers;
let amazonSetBillingAgreementDetailsSpy;
let amazonConfirmBillingAgreementSpy;
let amazonAuthorizeOnBillingAgreementSpy;
@@ -60,7 +61,7 @@ describe('Amazon Payments - Subscribe', () => {
sinon.stub(common, 'uuid').returns('uuid-generated');
});
afterEach(function () {
afterEach(() => {
amzLib.setBillingAgreementDetails.restore();
amzLib.confirmBillingAgreement.restore();
amzLib.authorizeOnBillingAgreement.restore();
@@ -168,7 +169,7 @@ describe('Amazon Payments - Subscribe', () => {
sub.key = 'google_6mo';
coupon = 'example-coupon';
let couponModel = new Coupon();
const couponModel = new Coupon();
couponModel.event = 'google_6mo';
await couponModel.save();
@@ -195,9 +196,9 @@ describe('Amazon Payments - Subscribe', () => {
sub.key = 'google_6mo';
coupon = 'example-coupon';
let couponModel = new Coupon();
const couponModel = new Coupon();
couponModel.event = 'google_6mo';
let updatedCouponModel = await couponModel.save();
const updatedCouponModel = await couponModel.save();
sinon.stub(cc, 'validate').returns(updatedCouponModel._id);

View File

@@ -2,16 +2,17 @@ import uuid from 'uuid';
import {
generateGroup,
} from '../../../../../helpers/api-unit.helper.js';
} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import { model as Group } from '../../../../../../website/server/models/group';
import amzLib from '../../../../../../website/server/libs/payments/amazon';
import payments from '../../../../../../website/server/libs/payments/payments';
describe('#upgradeGroupPlan', () => {
let spy, data, user, group, uuidString;
let spy; let data; let user; let group; let
uuidString;
beforeEach(async function () {
beforeEach(async () => {
user = new User();
user.profile.name = 'sender';
@@ -46,7 +47,7 @@ describe('#upgradeGroupPlan', () => {
data.sub.quantity = 3;
});
afterEach(function () {
afterEach(() => {
amzLib.authorizeOnBillingAgreement.restore();
uuid.v4.restore();
});
@@ -55,7 +56,7 @@ describe('#upgradeGroupPlan', () => {
data.paymentMethod = amzLib.constants.PAYMENT_METHOD;
await payments.createSubscription(data);
let updatedGroup = await Group.findById(group._id).exec();
const updatedGroup = await Group.findById(group._id).exec();
updatedGroup.memberCount += 1;
await updatedGroup.save();

View File

@@ -1,21 +1,22 @@
/* eslint-disable camelcase */
import iapModule from '../../../../../website/server/libs/inAppPurchases';
import moment from 'moment';
import payments from '../../../../../website/server/libs/payments/payments';
import applePayments from '../../../../../website/server/libs/payments/apple';
import iap from '../../../../../website/server/libs/inAppPurchases';
import {model as User} from '../../../../../website/server/models/user';
import { model as User } from '../../../../../website/server/models/user';
import common from '../../../../../website/common';
import moment from 'moment';
import {mockFindById, restoreFindById} from '../../../../helpers/mongoose.helper';
import { mockFindById, restoreFindById } from '../../../../helpers/mongoose.helper';
const i18n = common.i18n;
const { i18n } = common;
describe('Apple Payments', () => {
let subKey = 'basic_3mo';
describe('Apple Payments', () => {
const subKey = 'basic_3mo';
describe('verifyGemPurchase', () => {
let sku, user, token, receipt, headers;
let iapSetupStub, iapValidateStub, iapIsValidatedStub, paymentBuyGemsStub, iapGetPurchaseDataStub;
let sku; let user; let token; let receipt; let
headers;
let iapSetupStub; let iapValidateStub; let iapIsValidatedStub; let paymentBuyGemsStub; let
iapGetPurchaseDataStub;
beforeEach(() => {
token = 'testToken';
@@ -24,33 +25,34 @@ describe('Apple Payments', () => {
receipt = `{"token": "${token}", "productId": "${sku}"}`;
headers = {};
iapSetupStub = sinon.stub(iapModule, 'setup')
iapSetupStub = sinon.stub(iap, 'setup')
.resolves();
iapValidateStub = sinon.stub(iapModule, 'validate')
iapValidateStub = sinon.stub(iap, 'validate')
.resolves({});
iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(true);
iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
.returns([{productId: 'com.habitrpg.ios.Habitica.21gems',
transactionId: token,
iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
.returns([{
productId: 'com.habitrpg.ios.Habitica.21gems',
transactionId: token,
}]);
paymentBuyGemsStub = sinon.stub(payments, 'buyGems').resolves({});
});
afterEach(() => {
iapModule.setup.restore();
iapModule.validate.restore();
iapModule.isValidated.restore();
iapModule.getPurchaseData.restore();
iap.setup.restore();
iap.validate.restore();
iap.isValidated.restore();
iap.getPurchaseData.restore();
payments.buyGems.restore();
});
it('should throw an error if receipt is invalid', async () => {
iapModule.isValidated.restore();
iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
iap.isValidated.restore();
iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(false);
await expect(applePayments.verifyGemPurchase({user, receipt, headers}))
await expect(applePayments.verifyGemPurchase({ user, receipt, headers }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -60,9 +62,9 @@ describe('Apple Payments', () => {
it('should throw an error if getPurchaseData is invalid', async () => {
iapGetPurchaseDataStub.restore();
iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData').returns([]);
iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData').returns([]);
await expect(applePayments.verifyGemPurchase({user, receipt, headers}))
await expect(applePayments.verifyGemPurchase({ user, receipt, headers }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -72,7 +74,7 @@ describe('Apple Payments', () => {
it('errors if the user cannot purchase gems', async () => {
sinon.stub(user, 'canGetGems').resolves(false);
await expect(applePayments.verifyGemPurchase({user, receipt, headers}))
await expect(applePayments.verifyGemPurchase({ user, receipt, headers }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -85,12 +87,13 @@ describe('Apple Payments', () => {
it('errors if amount does not exist', async () => {
sinon.stub(user, 'canGetGems').resolves(true);
iapGetPurchaseDataStub.restore();
iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
.returns([{productId: 'badProduct',
transactionId: token,
iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
.returns([{
productId: 'badProduct',
transactionId: token,
}]);
await expect(applePayments.verifyGemPurchase({user, receipt, headers}))
await expect(applePayments.verifyGemPurchase({ user, receipt, headers }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -126,13 +129,14 @@ describe('Apple Payments', () => {
gemsCanPurchase.forEach(gemTest => {
it(`purchases ${gemTest.productId} gems`, async () => {
iapGetPurchaseDataStub.restore();
iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
.returns([{productId: gemTest.productId,
transactionId: token,
iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
.returns([{
productId: gemTest.productId,
transactionId: token,
}]);
sinon.stub(user, 'canGetGems').resolves(true);
await applePayments.verifyGemPurchase({user, receipt, headers});
await applePayments.verifyGemPurchase({ user, receipt, headers });
expect(iapSetupStub).to.be.calledOnce;
expect(iapValidateStub).to.be.calledOnce;
@@ -160,13 +164,16 @@ describe('Apple Payments', () => {
mockFindById(receivingUser);
iapGetPurchaseDataStub.restore();
iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
.returns([{productId: gemsCanPurchase[0].productId,
transactionId: token,
iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
.returns([{
productId: gemsCanPurchase[0].productId,
transactionId: token,
}]);
const gift = {uuid: receivingUser._id};
await applePayments.verifyGemPurchase({user, gift, receipt, headers});
const gift = { uuid: receivingUser._id };
await applePayments.verifyGemPurchase({
user, gift, receipt, headers,
});
expect(iapSetupStub).to.be.calledOnce;
expect(iapValidateStub).to.be.calledOnce;
@@ -187,8 +194,11 @@ describe('Apple Payments', () => {
});
describe('subscribe', () => {
let sub, sku, user, token, receipt, headers, nextPaymentProcessing;
let iapSetupStub, iapValidateStub, iapIsValidatedStub, paymentsCreateSubscritionStub, iapGetPurchaseDataStub;
let sub; let sku; let user; let token; let receipt; let headers; let
nextPaymentProcessing;
let iapSetupStub; let iapValidateStub; let iapIsValidatedStub;
let paymentsCreateSubscritionStub; let
iapGetPurchaseDataStub;
beforeEach(() => {
sub = common.content.subscriptionBlocks[subKey];
@@ -197,25 +207,25 @@ describe('Apple Payments', () => {
token = 'test-token';
headers = {};
receipt = `{"token": "${token}"}`;
nextPaymentProcessing = moment.utc().add({days: 2});
nextPaymentProcessing = moment.utc().add({ days: 2 });
iapSetupStub = sinon.stub(iapModule, 'setup')
iapSetupStub = sinon.stub(iap, 'setup')
.resolves();
iapValidateStub = sinon.stub(iapModule, 'validate')
iapValidateStub = sinon.stub(iap, 'validate')
.resolves({});
iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(true);
iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
.returns([{
expirationDate: moment.utc().subtract({day: 1}).toDate(),
expirationDate: moment.utc().subtract({ day: 1 }).toDate(),
productId: sku,
transactionId: token,
}, {
expirationDate: moment.utc().add({day: 1}).toDate(),
expirationDate: moment.utc().add({ day: 1 }).toDate(),
productId: 'wrongsku',
transactionId: token,
}, {
expirationDate: moment.utc().add({day: 1}).toDate(),
expirationDate: moment.utc().add({ day: 1 }).toDate(),
productId: sku,
transactionId: token,
}]);
@@ -223,10 +233,10 @@ describe('Apple Payments', () => {
});
afterEach(() => {
iapModule.setup.restore();
iapModule.validate.restore();
iapModule.isValidated.restore();
iapModule.getPurchaseData.restore();
iap.setup.restore();
iap.validate.restore();
iap.isValidated.restore();
iap.getPurchaseData.restore();
if (payments.createSubscription.restore) payments.createSubscription.restore();
});
@@ -240,8 +250,8 @@ describe('Apple Payments', () => {
});
it('should throw an error if receipt is invalid', async () => {
iapModule.isValidated.restore();
iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
iap.isValidated.restore();
iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(false);
await expect(applePayments.subscribe(sku, user, receipt, headers, nextPaymentProcessing))
@@ -272,10 +282,10 @@ describe('Apple Payments', () => {
];
subOptions.forEach(option => {
it(`creates a user subscription for ${option.sku}`, async () => {
iapModule.getPurchaseData.restore();
iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
iap.getPurchaseData.restore();
iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
.returns([{
expirationDate: moment.utc().add({day: 1}).toDate(),
expirationDate: moment.utc().add({ day: 1 }).toDate(),
productId: option.sku,
transactionId: token,
}]);
@@ -319,8 +329,10 @@ describe('Apple Payments', () => {
});
describe('cancelSubscribe ', () => {
let user, token, receipt, headers, customerId, expirationDate;
let iapSetupStub, iapValidateStub, iapIsValidatedStub, iapGetPurchaseDataStub, paymentCancelSubscriptionSpy;
let user; let token; let receipt; let headers; let customerId; let
expirationDate;
let iapSetupStub; let iapValidateStub; let iapIsValidatedStub; let iapGetPurchaseDataStub; let
paymentCancelSubscriptionSpy;
beforeEach(async () => {
token = 'test-token';
@@ -329,15 +341,15 @@ describe('Apple Payments', () => {
customerId = 'test-customerId';
expirationDate = moment.utc();
iapSetupStub = sinon.stub(iapModule, 'setup')
iapSetupStub = sinon.stub(iap, 'setup')
.resolves();
iapValidateStub = sinon.stub(iapModule, 'validate')
iapValidateStub = sinon.stub(iap, 'validate')
.resolves({
expirationDate,
});
iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
.returns([{expirationDate: expirationDate.toDate()}]);
iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
.returns([{ expirationDate: expirationDate.toDate() }]);
iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(true);
user = new User();
@@ -350,11 +362,11 @@ describe('Apple Payments', () => {
paymentCancelSubscriptionSpy = sinon.stub(payments, 'cancelSubscription').resolves({});
});
afterEach(function () {
iapModule.setup.restore();
iapModule.validate.restore();
iapModule.isValidated.restore();
iapModule.getPurchaseData.restore();
afterEach(() => {
iap.setup.restore();
iap.validate.restore();
iap.isValidated.restore();
iap.getPurchaseData.restore();
payments.cancelSubscription.restore();
});
@@ -370,9 +382,9 @@ describe('Apple Payments', () => {
});
it('should throw an error if subscription is still valid', async () => {
iapModule.getPurchaseData.restore();
iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
.returns([{expirationDate: expirationDate.add({day: 1}).toDate()}]);
iap.getPurchaseData.restore();
iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
.returns([{ expirationDate: expirationDate.add({ day: 1 }).toDate() }]);
await expect(applePayments.cancelSubscribe(user, headers))
.to.eventually.be.rejected.and.to.eql({
@@ -383,8 +395,8 @@ describe('Apple Payments', () => {
});
it('should throw an error if receipt is invalid', async () => {
iapModule.isValidated.restore();
iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
iap.isValidated.restore();
iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(false);
await expect(applePayments.cancelSubscribe(user, headers))

View File

@@ -1,21 +1,22 @@
/* eslint-disable camelcase */
import iapModule from '../../../../../website/server/libs/inAppPurchases';
import moment from 'moment';
import payments from '../../../../../website/server/libs/payments/payments';
import googlePayments from '../../../../../website/server/libs/payments/google';
import iap from '../../../../../website/server/libs/inAppPurchases';
import {model as User} from '../../../../../website/server/models/user';
import { model as User } from '../../../../../website/server/models/user';
import common from '../../../../../website/common';
import moment from 'moment';
import {mockFindById, restoreFindById} from '../../../../helpers/mongoose.helper';
import { mockFindById, restoreFindById } from '../../../../helpers/mongoose.helper';
const i18n = common.i18n;
const { i18n } = common;
describe('Google Payments', () => {
let subKey = 'basic_3mo';
describe('Google Payments', () => {
const subKey = 'basic_3mo';
describe('verifyGemPurchase', () => {
let sku, user, token, receipt, signature, headers;
let iapSetupStub, iapValidateStub, iapIsValidatedStub, paymentBuyGemsStub;
let sku; let user; let token; let receipt; let signature; let
headers;
let iapSetupStub; let iapValidateStub; let iapIsValidatedStub; let
paymentBuyGemsStub;
beforeEach(() => {
sku = 'com.habitrpg.android.habitica.iap.21gems';
@@ -24,28 +25,30 @@ describe('Google Payments', () => {
signature = '';
headers = {};
iapSetupStub = sinon.stub(iapModule, 'setup')
iapSetupStub = sinon.stub(iap, 'setup')
.resolves();
iapValidateStub = sinon.stub(iapModule, 'validate')
iapValidateStub = sinon.stub(iap, 'validate')
.resolves({});
iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(true);
paymentBuyGemsStub = sinon.stub(payments, 'buyGems').resolves({});
});
afterEach(() => {
iapModule.setup.restore();
iapModule.validate.restore();
iapModule.isValidated.restore();
iap.setup.restore();
iap.validate.restore();
iap.isValidated.restore();
payments.buyGems.restore();
});
it('should throw an error if receipt is invalid', async () => {
iapModule.isValidated.restore();
iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
iap.isValidated.restore();
iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(false);
await expect(googlePayments.verifyGemPurchase({user, receipt, signature, headers}))
await expect(googlePayments.verifyGemPurchase({
user, receipt, signature, headers,
}))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -56,7 +59,9 @@ describe('Google Payments', () => {
it('should throw an error if productId is invalid', async () => {
receipt = `{"token": "${token}", "productId": "invalid"}`;
await expect(googlePayments.verifyGemPurchase({user, receipt, signature, headers}))
await expect(googlePayments.verifyGemPurchase({
user, receipt, signature, headers,
}))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -67,7 +72,9 @@ describe('Google Payments', () => {
it('should throw an error if user cannot purchase gems', async () => {
sinon.stub(user, 'canGetGems').resolves(false);
await expect(googlePayments.verifyGemPurchase({user, receipt, signature, headers}))
await expect(googlePayments.verifyGemPurchase({
user, receipt, signature, headers,
}))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -79,7 +86,9 @@ describe('Google Payments', () => {
it('purchases gems', async () => {
sinon.stub(user, 'canGetGems').resolves(true);
await googlePayments.verifyGemPurchase({user, receipt, signature, headers});
await googlePayments.verifyGemPurchase({
user, receipt, signature, headers,
});
expect(iapSetupStub).to.be.calledOnce;
expect(iapValidateStub).to.be.calledOnce;
@@ -107,8 +116,10 @@ describe('Google Payments', () => {
mockFindById(receivingUser);
const gift = {uuid: receivingUser._id};
await googlePayments.verifyGemPurchase({user, gift, receipt, signature, headers});
const gift = { uuid: receivingUser._id };
await googlePayments.verifyGemPurchase({
user, gift, receipt, signature, headers,
});
expect(iapSetupStub).to.be.calledOnce;
expect(iapValidateStub).to.be.calledOnce;
@@ -131,8 +142,10 @@ describe('Google Payments', () => {
});
describe('subscribe', () => {
let sub, sku, user, token, receipt, signature, headers, nextPaymentProcessing;
let iapSetupStub, iapValidateStub, iapIsValidatedStub, paymentsCreateSubscritionStub;
let sub; let sku; let user; let token; let receipt; let signature; let headers; let
nextPaymentProcessing;
let iapSetupStub; let iapValidateStub; let iapIsValidatedStub; let
paymentsCreateSubscritionStub;
beforeEach(() => {
sub = common.content.subscriptionBlocks[subKey];
@@ -142,30 +155,31 @@ describe('Google Payments', () => {
headers = {};
receipt = `{"token": "${token}"}`;
signature = '';
nextPaymentProcessing = moment.utc().add({days: 2});
nextPaymentProcessing = moment.utc().add({ days: 2 });
iapSetupStub = sinon.stub(iapModule, 'setup')
iapSetupStub = sinon.stub(iap, 'setup')
.resolves();
iapValidateStub = sinon.stub(iapModule, 'validate')
iapValidateStub = sinon.stub(iap, 'validate')
.resolves({});
iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(true);
paymentsCreateSubscritionStub = sinon.stub(payments, 'createSubscription').resolves({});
});
afterEach(() => {
iapModule.setup.restore();
iapModule.validate.restore();
iapModule.isValidated.restore();
iap.setup.restore();
iap.validate.restore();
iap.isValidated.restore();
payments.createSubscription.restore();
});
it('should throw an error if receipt is invalid', async () => {
iapModule.isValidated.restore();
iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
iap.isValidated.restore();
iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(false);
await expect(googlePayments.subscribe(sku, user, receipt, signature, headers, nextPaymentProcessing))
await expect(googlePayments
.subscribe(sku, user, receipt, signature, headers, nextPaymentProcessing))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -176,7 +190,8 @@ describe('Google Payments', () => {
it('should throw an error if sku is invalid', async () => {
sku = 'invalid';
await expect(googlePayments.subscribe(sku, user, receipt, signature, headers, nextPaymentProcessing))
await expect(googlePayments
.subscribe(sku, user, receipt, signature, headers, nextPaymentProcessing))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -203,15 +218,17 @@ describe('Google Payments', () => {
paymentMethod: googlePayments.constants.PAYMENT_METHOD_GOOGLE,
sub,
headers,
additionalData: {data: receipt, signature},
additionalData: { data: receipt, signature },
nextPaymentProcessing,
});
});
});
describe('cancelSubscribe ', () => {
let user, token, receipt, signature, headers, customerId, expirationDate;
let iapSetupStub, iapValidateStub, iapIsValidatedStub, iapGetPurchaseDataStub, paymentCancelSubscriptionSpy;
let user; let token; let receipt; let signature; let headers; let customerId; let
expirationDate;
let iapSetupStub; let iapValidateStub; let iapIsValidatedStub; let iapGetPurchaseDataStub; let
paymentCancelSubscriptionSpy;
beforeEach(async () => {
token = 'test-token';
@@ -221,15 +238,15 @@ describe('Google Payments', () => {
customerId = 'test-customerId';
expirationDate = moment.utc();
iapSetupStub = sinon.stub(iapModule, 'setup')
iapSetupStub = sinon.stub(iap, 'setup')
.resolves();
iapValidateStub = sinon.stub(iapModule, 'validate')
iapValidateStub = sinon.stub(iap, 'validate')
.resolves({
expirationDate,
});
iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
.returns([{expirationDate: expirationDate.toDate()}]);
iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
.returns([{ expirationDate: expirationDate.toDate() }]);
iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(true);
user = new User();
@@ -237,16 +254,16 @@ describe('Google Payments', () => {
user.purchased.plan.customerId = customerId;
user.purchased.plan.paymentMethod = googlePayments.constants.PAYMENT_METHOD_GOOGLE;
user.purchased.plan.planId = subKey;
user.purchased.plan.additionalData = {data: receipt, signature};
user.purchased.plan.additionalData = { data: receipt, signature };
paymentCancelSubscriptionSpy = sinon.stub(payments, 'cancelSubscription').resolves({});
});
afterEach(function () {
iapModule.setup.restore();
iapModule.validate.restore();
iapModule.isValidated.restore();
iapModule.getPurchaseData.restore();
afterEach(() => {
iap.setup.restore();
iap.validate.restore();
iap.isValidated.restore();
iap.getPurchaseData.restore();
payments.cancelSubscription.restore();
});
@@ -262,9 +279,9 @@ describe('Google Payments', () => {
});
it('should throw an error if subscription is still valid', async () => {
iapModule.getPurchaseData.restore();
iapGetPurchaseDataStub = sinon.stub(iapModule, 'getPurchaseData')
.returns([{expirationDate: expirationDate.add({day: 1}).toDate()}]);
iap.getPurchaseData.restore();
iapGetPurchaseDataStub = sinon.stub(iap, 'getPurchaseData')
.returns([{ expirationDate: expirationDate.add({ day: 1 }).toDate() }]);
await expect(googlePayments.cancelSubscribe(user, headers))
.to.eventually.be.rejected.and.to.eql({
@@ -275,8 +292,8 @@ describe('Google Payments', () => {
});
it('should throw an error if receipt is invalid', async () => {
iapModule.isValidated.restore();
iapIsValidatedStub = sinon.stub(iapModule, 'isValidated')
iap.isValidated.restore();
iapIsValidatedStub = sinon.stub(iap, 'isValidated')
.returns(false);
await expect(googlePayments.cancelSubscribe(user, headers))

View File

@@ -6,11 +6,12 @@ import { model as User } from '../../../../../../website/server/models/user';
import { model as Group } from '../../../../../../website/server/models/group';
import {
generateGroup,
} from '../../../../../helpers/api-unit.helper.js';
} from '../../../../../helpers/api-unit.helper';
import i18n from '../../../../../../website/common/script/i18n';
describe('Canceling a subscription for group', () => {
let plan, group, user, data;
let plan; let group; let user; let
data;
beforeEach(async () => {
user = new User();
@@ -67,9 +68,9 @@ describe('Canceling a subscription for group', () => {
data.groupId = group._id;
await api.cancelSubscription(data);
let now = new Date();
let updatedGroup = await Group.findById(group._id).exec();
let daysTillTermination = moment(updatedGroup.purchased.plan.dateTerminated).diff(now, 'days');
const now = new Date();
const updatedGroup = await Group.findById(group._id).exec();
const daysTillTermination = moment(updatedGroup.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(29, 30); // 1 month +/- 1 days
});
@@ -81,9 +82,9 @@ describe('Canceling a subscription for group', () => {
await api.cancelSubscription(data);
let now = new Date();
let updatedGroup = await Group.findById(group._id).exec();
let daysTillTermination = moment(updatedGroup.purchased.plan.dateTerminated).diff(now, 'days');
const now = new Date();
const updatedGroup = await Group.findById(group._id).exec();
const daysTillTermination = moment(updatedGroup.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(89, 90); // 3 months +/- 1 days
});
@@ -95,9 +96,9 @@ describe('Canceling a subscription for group', () => {
await api.cancelSubscription(data);
let now = new Date();
let updatedGroup = await Group.findById(group._id).exec();
let daysTillTermination = moment(updatedGroup.purchased.plan.dateTerminated).diff(now, 'days');
const now = new Date();
const updatedGroup = await Group.findById(group._id).exec();
const daysTillTermination = moment(updatedGroup.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(38, 39); // should be about 1 month + 1/3 month
});
@@ -108,9 +109,9 @@ describe('Canceling a subscription for group', () => {
await api.cancelSubscription(data);
let now = new Date();
let updatedGroup = await Group.findById(group._id).exec();
let daysTillTermination = moment(updatedGroup.purchased.plan.dateTerminated).diff(now, 'days');
const now = new Date();
const updatedGroup = await Group.findById(group._id).exec();
const daysTillTermination = moment(updatedGroup.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(13, 15);
});
@@ -122,7 +123,7 @@ describe('Canceling a subscription for group', () => {
await api.cancelSubscription(data);
let updatedGroup = await Group.findById(group._id).exec();
const updatedGroup = await Group.findById(group._id).exec();
expect(updatedGroup.purchased.plan.extraMonths).to.eql(0);
});
@@ -134,12 +135,12 @@ describe('Canceling a subscription for group', () => {
expect(sender.sendTxn.firstCall.args[0]._id).to.equal(user._id);
expect(sender.sendTxn.firstCall.args[1]).to.equal('group-cancel-subscription');
expect(sender.sendTxn.firstCall.args[2]).to.eql([
{name: 'GROUP_NAME', content: group.name},
{ name: 'GROUP_NAME', content: group.name },
]);
});
it('prevents non group leader from managing subscription', async () => {
let groupMember = new User();
const groupMember = new User();
data.user = groupMember;
data.groupId = group._id;
@@ -160,7 +161,7 @@ describe('Canceling a subscription for group', () => {
await api.createSubscription(data);
let updatedGroup = await Group.findById(group._id).exec();
let newLeader = new User();
const newLeader = new User();
updatedGroup.leader = newLeader._id;
await updatedGroup.save();
@@ -192,15 +193,15 @@ describe('Canceling a subscription for group', () => {
await api.cancelSubscription(data);
let now = new Date();
const now = new Date();
now.setHours(0, 0, 0, 0);
let updatedLeader = await User.findById(user._id).exec();
let daysTillTermination = moment(updatedLeader.purchased.plan.dateTerminated).diff(now, 'days');
const updatedLeader = await User.findById(user._id).exec();
const daysTillTermination = moment(updatedLeader.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(2, 3); // only a few days
});
it('sends an email to members of group', async () => {
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
recipient.guilds.push(group._id);
await recipient.save();
@@ -214,8 +215,8 @@ describe('Canceling a subscription for group', () => {
expect(sender.sendTxn.thirdCall.args[0]._id).to.equal(recipient._id);
expect(sender.sendTxn.thirdCall.args[1]).to.equal('group-member-cancel');
expect(sender.sendTxn.thirdCall.args[2]).to.eql([
{name: 'LEADER', content: user.profile.name},
{name: 'GROUP_NAME', content: group.name},
{ name: 'LEADER', content: user.profile.name },
{ name: 'GROUP_NAME', content: group.name },
]);
});
@@ -223,7 +224,7 @@ describe('Canceling a subscription for group', () => {
plan.key = 'basic_earned';
plan.customerId = api.constants.UNLIMITED_CUSTOMER_ID;
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -233,12 +234,12 @@ describe('Canceling a subscription for group', () => {
await api.cancelSubscription(data);
let updatedLeader = await User.findById(user._id).exec();
const updatedLeader = await User.findById(user._id).exec();
expect(updatedLeader.purchased.plan.dateTerminated).to.not.exist;
});
it('does not cancel a user subscription if they are still in another active group plan', async () => {
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
recipient.purchased.plan = plan;
@@ -252,10 +253,10 @@ describe('Canceling a subscription for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
let firstDateCreated = updatedUser.purchased.plan.dateCreated;
let extraMonthsBeforeSecond = updatedUser.purchased.plan.extraMonths;
const firstDateCreated = updatedUser.purchased.plan.dateCreated;
const extraMonthsBeforeSecond = updatedUser.purchased.plan.extraMonths;
let group2 = generateGroup({
const group2 = generateGroup({
name: 'test group2',
type: 'guild',
privacy: 'public',
@@ -291,10 +292,10 @@ describe('Canceling a subscription for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(user._id).exec();
let firstDateCreated = updatedUser.purchased.plan.dateCreated;
let extraMonthsBeforeSecond = updatedUser.purchased.plan.extraMonths;
const firstDateCreated = updatedUser.purchased.plan.dateCreated;
const extraMonthsBeforeSecond = updatedUser.purchased.plan.extraMonths;
let group2 = generateGroup({
const group2 = generateGroup({
name: 'test group2',
type: 'guild',
privacy: 'public',

View File

@@ -11,7 +11,7 @@ import { model as User } from '../../../../../../website/server/models/user';
import { model as Group } from '../../../../../../website/server/models/group';
import {
generateGroup,
} from '../../../../../helpers/api-unit.helper.js';
} from '../../../../../helpers/api-unit.helper';
describe('Purchasing a group plan for group', () => {
const EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_GOOGLE = 'Google_subscription';
@@ -19,10 +19,11 @@ describe('Purchasing a group plan for group', () => {
const EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NORMAL = 'normal_subscription';
const EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NONE = 'no_subscription';
let plan, group, user, data;
let stripe = stripeModule('test');
let groupLeaderName = 'sender';
let groupName = 'test group';
let plan; let group; let user; let
data;
const stripe = stripeModule('test');
const groupLeaderName = 'sender';
const groupName = 'test group';
beforeEach(async () => {
user = new User();
@@ -68,14 +69,17 @@ describe('Purchasing a group plan for group', () => {
},
};
let subscriptionId = 'subId';
const subscriptionId = 'subId';
sinon.stub(stripe.customers, 'del').resolves({});
let currentPeriodEndTimeStamp = moment().add(3, 'months').unix();
const currentPeriodEndTimeStamp = moment().add(3, 'months').unix();
sinon.stub(stripe.customers, 'retrieve')
.resolves({
subscriptions: {
data: [{id: subscriptionId, current_period_end: currentPeriodEndTimeStamp}], // eslint-disable-line camelcase
data: [{
id: subscriptionId,
current_period_end: currentPeriodEndTimeStamp,
}], // eslint-disable-line camelcase
},
});
@@ -95,7 +99,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedGroup = await Group.findById(group._id).exec();
const updatedGroup = await Group.findById(group._id).exec();
expect(updatedGroup.purchased.plan.planId).to.eql('basic_3mo');
expect(updatedGroup.purchased.plan.customerId).to.eql('customer-id');
@@ -126,7 +130,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedGroup = await Group.findById(group._id).exec();
const updatedGroup = await Group.findById(group._id).exec();
expect(updatedGroup.purchased.plan.extraMonths).to.within(1.9, 2);
});
@@ -139,7 +143,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedGroup = await Group.findById(group._id).exec();
const updatedGroup = await Group.findById(group._id).exec();
expect(updatedGroup.purchased.plan.extraMonths).to.eql(0);
});
@@ -150,7 +154,7 @@ describe('Purchasing a group plan for group', () => {
data.groupId = group._id;
await api.createSubscription(data);
let updatedLeader = await User.findById(user._id).exec();
const updatedLeader = await User.findById(user._id).exec();
expect(updatedLeader.purchased.plan.planId).to.eql('group_plan_auto');
expect(updatedLeader.purchased.plan.customerId).to.eql('group-plan');
@@ -166,7 +170,7 @@ describe('Purchasing a group plan for group', () => {
});
it('sends an email to member of group who was not a subscriber', async () => {
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
recipient.guilds.push(group._id);
await recipient.save();
@@ -179,9 +183,9 @@ describe('Purchasing a group plan for group', () => {
expect(sender.sendTxn.firstCall.args[0]._id).to.equal(recipient._id);
expect(sender.sendTxn.firstCall.args[1]).to.equal('group-member-join');
expect(sender.sendTxn.firstCall.args[2]).to.eql([
{name: 'LEADER', content: user.profile.name},
{name: 'GROUP_NAME', content: group.name},
{name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NONE},
{ name: 'LEADER', content: user.profile.name },
{ name: 'GROUP_NAME', content: group.name },
{ name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NONE },
]);
// confirm that the other email sent is appropriate:
expect(sender.sendTxn.secondCall.args[0]._id).to.equal(group.leader);
@@ -189,7 +193,7 @@ describe('Purchasing a group plan for group', () => {
});
it('sends one email to subscribed member of group, stating subscription is cancelled (Stripe)', async () => {
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
plan.paymentMethod = stripePayments.constants.PAYMENT_METHOD;
@@ -205,9 +209,9 @@ describe('Purchasing a group plan for group', () => {
expect(sender.sendTxn.firstCall.args[0]._id).to.equal(recipient._id);
expect(sender.sendTxn.firstCall.args[1]).to.equal('group-member-join');
expect(sender.sendTxn.firstCall.args[2]).to.eql([
{name: 'LEADER', content: user.profile.name},
{name: 'GROUP_NAME', content: group.name},
{name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NORMAL},
{ name: 'LEADER', content: user.profile.name },
{ name: 'GROUP_NAME', content: group.name },
{ name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NORMAL },
]);
// confirm that the other email sent is not a cancel-subscription email:
expect(sender.sendTxn.secondCall.args[0]._id).to.equal(group.leader);
@@ -218,11 +222,11 @@ describe('Purchasing a group plan for group', () => {
sinon.stub(amzLib, 'getBillingAgreementDetails')
.resolves({
BillingAgreementDetails: {
BillingAgreementStatus: {State: 'Closed'},
BillingAgreementStatus: { State: 'Closed' },
},
});
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
plan.planId = 'basic_earned';
plan.paymentMethod = amzLib.constants.PAYMENT_METHOD;
@@ -238,9 +242,9 @@ describe('Purchasing a group plan for group', () => {
expect(sender.sendTxn.firstCall.args[0]._id).to.equal(recipient._id);
expect(sender.sendTxn.firstCall.args[1]).to.equal('group-member-join');
expect(sender.sendTxn.firstCall.args[2]).to.eql([
{name: 'LEADER', content: user.profile.name},
{name: 'GROUP_NAME', content: group.name},
{name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NORMAL},
{ name: 'LEADER', content: user.profile.name },
{ name: 'GROUP_NAME', content: group.name },
{ name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NORMAL },
]);
// confirm that the other email sent is not a cancel-subscription email:
expect(sender.sendTxn.secondCall.args[0]._id).to.equal(group.leader);
@@ -259,7 +263,7 @@ describe('Purchasing a group plan for group', () => {
},
});
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
plan.planId = 'basic_earned';
plan.paymentMethod = paypalPayments.constants.PAYMENT_METHOD;
@@ -275,9 +279,9 @@ describe('Purchasing a group plan for group', () => {
expect(sender.sendTxn.firstCall.args[0]._id).to.equal(recipient._id);
expect(sender.sendTxn.firstCall.args[1]).to.equal('group-member-join');
expect(sender.sendTxn.firstCall.args[2]).to.eql([
{name: 'LEADER', content: user.profile.name},
{name: 'GROUP_NAME', content: group.name},
{name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NORMAL},
{ name: 'LEADER', content: user.profile.name },
{ name: 'GROUP_NAME', content: group.name },
{ name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_NORMAL },
]);
// confirm that the other email sent is not a cancel-subscription email:
expect(sender.sendTxn.secondCall.args[0]._id).to.equal(group.leader);
@@ -292,7 +296,7 @@ describe('Purchasing a group plan for group', () => {
plan.customerId = 'random';
plan.paymentMethod = api.constants.GOOGLE_PAYMENT_METHOD;
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -310,9 +314,9 @@ describe('Purchasing a group plan for group', () => {
expect(sender.sendTxn.args[1][0]._id).to.equal(recipient._id);
expect(sender.sendTxn.args[1][1]).to.equal('group-member-join');
expect(sender.sendTxn.args[1][2]).to.eql([
{name: 'LEADER', content: groupLeaderName},
{name: 'GROUP_NAME', content: groupName},
{name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_GOOGLE},
{ name: 'LEADER', content: groupLeaderName },
{ name: 'GROUP_NAME', content: groupName },
{ name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_GOOGLE },
]);
expect(sender.sendTxn.args[2][0]._id).to.equal(group.leader);
expect(sender.sendTxn.args[2][1]).to.equal('group-member-join');
@@ -325,7 +329,7 @@ describe('Purchasing a group plan for group', () => {
plan.customerId = 'random';
plan.paymentMethod = api.constants.IOS_PAYMENT_METHOD;
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -343,9 +347,9 @@ describe('Purchasing a group plan for group', () => {
expect(sender.sendTxn.args[1][0]._id).to.equal(recipient._id);
expect(sender.sendTxn.args[1][1]).to.equal('group-member-join');
expect(sender.sendTxn.args[1][2]).to.eql([
{name: 'LEADER', content: groupLeaderName},
{name: 'GROUP_NAME', content: groupName},
{name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_IOS},
{ name: 'LEADER', content: groupLeaderName },
{ name: 'GROUP_NAME', content: groupName },
{ name: 'PREVIOUS_SUBSCRIPTION_TYPE', content: EMAIL_TEMPLATE_SUBSCRIPTION_TYPE_IOS },
]);
expect(sender.sendTxn.args[2][0]._id).to.equal(group.leader);
expect(sender.sendTxn.args[2][1]).to.equal('group-member-join');
@@ -354,7 +358,7 @@ describe('Purchasing a group plan for group', () => {
});
it('adds months to members with existing gift subscription', async () => {
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -378,7 +382,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.planId).to.eql('group_plan_auto');
expect(updatedUser.purchased.plan.customerId).to.eql('group-plan');
@@ -392,7 +396,7 @@ describe('Purchasing a group plan for group', () => {
});
it('adds months to members with existing multi-month gift subscription', async () => {
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -414,7 +418,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.planId).to.eql('group_plan_auto');
expect(updatedUser.purchased.plan.customerId).to.eql('group-plan');
@@ -428,7 +432,7 @@ describe('Purchasing a group plan for group', () => {
});
it('adds months to members with existing recurring subscription (Stripe)', async () => {
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
plan.paymentMethod = stripePayments.constants.PAYMENT_METHOD;
@@ -450,11 +454,11 @@ describe('Purchasing a group plan for group', () => {
sinon.stub(amzLib, 'getBillingAgreementDetails')
.resolves({
BillingAgreementDetails: {
BillingAgreementStatus: {State: 'Closed'},
BillingAgreementStatus: { State: 'Closed' },
},
});
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
plan.planId = 'basic_earned';
plan.paymentMethod = amzLib.constants.PAYMENT_METHOD;
@@ -470,7 +474,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.extraMonths).to.within(3, 5);
});
@@ -485,7 +489,7 @@ describe('Purchasing a group plan for group', () => {
},
});
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
plan.planId = 'basic_earned';
plan.paymentMethod = paypalPayments.constants.PAYMENT_METHOD;
@@ -500,7 +504,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.extraMonths).to.within(2, 3);
paypalPayments.paypalBillingAgreementGet.restore();
@@ -511,7 +515,7 @@ describe('Purchasing a group plan for group', () => {
it('adds months to members with existing recurring subscription (iOS)');
it('adds months to members who already cancelled but not yet terminated recurring subscription', async () => {
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
plan.paymentMethod = stripePayments.constants.PAYMENT_METHOD;
@@ -527,13 +531,13 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.extraMonths).to.within(2, 3);
});
it('adds months to members who already cancelled but not yet terminated group plan subscription', async () => {
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
plan.paymentMethod = api.constants.GROUP_PLAN_PAYMENT_METHOD;
@@ -550,12 +554,12 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.extraMonths).to.within(3, 4);
});
it('resets date terminated if user has old subscription', async () => {
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
plan.paymentMethod = stripePayments.constants.PAYMENT_METHOD;
@@ -570,13 +574,13 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.dateTerminated).to.not.exist;
});
it('adds months to members with existing recurring subscription and includes existing extraMonths', async () => {
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
plan.paymentMethod = stripePayments.constants.PAYMENT_METHOD;
@@ -591,13 +595,13 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.extraMonths).to.within(7, 9);
});
it('adds months to members with existing recurring subscription and ignores existing negative extraMonths', async () => {
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
plan.paymentMethod = stripePayments.constants.PAYMENT_METHOD;
@@ -612,23 +616,23 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.extraMonths).to.within(2, 3);
});
it('does not override gemsBought, mysteryItems, dateCreated, and consective fields', async () => {
let planCreatedDate = moment().toDate();
let mysteryItem = {title: 'item'};
let mysteryItems = [mysteryItem];
let consecutive = {
const planCreatedDate = moment().toDate();
const mysteryItem = { title: 'item' };
const mysteryItems = [mysteryItem];
const consecutive = {
trinkets: 3,
gemCapExtra: 20,
offset: 1,
count: 13,
};
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
@@ -647,7 +651,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.gemsBought).to.equal(3);
expect(updatedUser.purchased.plan.mysteryItems[0]).to.eql(mysteryItem);
@@ -659,7 +663,7 @@ describe('Purchasing a group plan for group', () => {
});
it('does not modify a user with a group subscription when they join another group', async () => {
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
recipient.purchased.plan = plan;
@@ -673,10 +677,10 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
let firstDateCreated = updatedUser.purchased.plan.dateCreated;
let extraMonthsBeforeSecond = updatedUser.purchased.plan.extraMonths;
const firstDateCreated = updatedUser.purchased.plan.dateCreated;
const extraMonthsBeforeSecond = updatedUser.purchased.plan.extraMonths;
let group2 = generateGroup({
const group2 = generateGroup({
name: 'test group2',
type: 'guild',
privacy: 'public',
@@ -703,7 +707,7 @@ describe('Purchasing a group plan for group', () => {
});
it('does not remove a user who is in two groups plans and leaves one', async () => {
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
plan.key = 'basic_earned';
recipient.purchased.plan = plan;
@@ -717,10 +721,10 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
let firstDateCreated = updatedUser.purchased.plan.dateCreated;
let extraMonthsBeforeSecond = updatedUser.purchased.plan.extraMonths;
const firstDateCreated = updatedUser.purchased.plan.dateCreated;
const extraMonthsBeforeSecond = updatedUser.purchased.plan.extraMonths;
let group2 = generateGroup({
const group2 = generateGroup({
name: 'test group2',
type: 'guild',
privacy: 'public',
@@ -733,7 +737,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedGroup = await Group.findById(group._id).exec();
const updatedGroup = await Group.findById(group._id).exec();
await updatedGroup.leave(recipient);
updatedUser = await User.findById(recipient._id).exec();
@@ -753,7 +757,7 @@ describe('Purchasing a group plan for group', () => {
plan.key = 'basic_earned';
plan.customerId = api.constants.UNLIMITED_CUSTOMER_ID;
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -765,7 +769,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.planId).to.eql('basic_3mo');
expect(updatedUser.purchased.plan.customerId).to.eql(api.constants.UNLIMITED_CUSTOMER_ID);
@@ -782,7 +786,7 @@ describe('Purchasing a group plan for group', () => {
plan.customerId = 'random';
plan.paymentMethod = api.constants.GOOGLE_PAYMENT_METHOD;
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -794,7 +798,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.planId).to.eql('basic_3mo');
expect(updatedUser.purchased.plan.customerId).to.eql('random');
@@ -811,7 +815,7 @@ describe('Purchasing a group plan for group', () => {
plan.customerId = 'random';
plan.paymentMethod = api.constants.IOS_PAYMENT_METHOD;
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -823,7 +827,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.planId).to.eql('basic_3mo');
expect(updatedUser.purchased.plan.customerId).to.eql('random');
@@ -841,7 +845,7 @@ describe('Purchasing a group plan for group', () => {
plan.customerId = api.constants.GROUP_PLAN_CUSTOMER_ID;
plan.dateTerminated = moment().add(1, 'months');
let recipient = new User();
const recipient = new User();
recipient.profile.name = 'recipient';
recipient.purchased.plan = plan;
recipient.guilds.push(group._id);
@@ -853,7 +857,7 @@ describe('Purchasing a group plan for group', () => {
await api.createSubscription(data);
let updatedUser = await User.findById(recipient._id).exec();
const updatedUser = await User.findById(recipient._id).exec();
expect(updatedUser.purchased.plan.planId).to.eql('group_plan_auto');
expect(updatedUser.purchased.plan.customerId).to.eql(api.constants.GROUP_PLAN_CUSTOMER_ID);

View File

@@ -1,7 +1,7 @@
import { model as User } from '../../../../../website/server/models/user';
export async function createNonLeaderGroupMember (group) {
let nonLeader = new User();
export async function createNonLeaderGroupMember (group) { // eslint-disable-line import/prefer-default-export, max-len
const nonLeader = new User();
nonLeader.guilds.push(group._id);
return await nonLeader.save();
return nonLeader.save();
}

View File

@@ -8,10 +8,11 @@ import { model as User } from '../../../../../website/server/models/user';
import { translate as t } from '../../../../helpers/api-integration/v3';
import {
generateGroup,
} from '../../../../helpers/api-unit.helper.js';
} from '../../../../helpers/api-unit.helper';
describe('payments/index', () => {
let user, group, data, plan;
let user; let group; let data; let
plan;
beforeEach(async () => {
user = new User();
@@ -102,7 +103,7 @@ describe('payments/index', () => {
});
it('does not set negative extraMonths if plan has past dateTerminated date', async () => {
let dateTerminated = moment().subtract(2, 'months').toDate();
const dateTerminated = moment().subtract(2, 'months').toDate();
recipient.purchased.plan.dateTerminated = dateTerminated;
await api.createSubscription(data);
@@ -120,7 +121,7 @@ describe('payments/index', () => {
});
it('adds to date terminated for an existing plan with a future terminated date', async () => {
let dateTerminated = moment().add(1, 'months').toDate();
const dateTerminated = moment().add(1, 'months').toDate();
recipient.purchased.plan = plan;
recipient.purchased.plan.dateTerminated = dateTerminated;
@@ -130,7 +131,7 @@ describe('payments/index', () => {
});
it('replaces date terminated for an account with a past terminated date', async () => {
let dateTerminated = moment().subtract(1, 'months').toDate();
const dateTerminated = moment().subtract(1, 'months').toDate();
recipient.purchased.plan.dateTerminated = dateTerminated;
await api.createSubscription(data);
@@ -208,18 +209,21 @@ describe('payments/index', () => {
it('sends a private message about the gift', async () => {
await api.createSubscription(data);
let msg = '\`Hello recipient, sender has sent you 3 months of subscription!\`';
const msg = '`Hello recipient, sender has sent you 3 months of subscription!`';
expect(user.sendMessage).to.be.calledOnce;
expect(user.sendMessage).to.be.calledWith(recipient, { receiverMsg: msg, senderMsg: msg, save: false });
expect(user.sendMessage).to.be.calledWith(
recipient,
{ receiverMsg: msg, senderMsg: msg, save: false },
);
});
it('sends an email about the gift', async () => {
await api.createSubscription(data);
expect(sender.sendTxn).to.be.calledWith(recipient, 'gifted-subscription', [
{name: 'GIFTER', content: 'sender'},
{name: 'X_MONTHS_SUBSCRIPTION', content: 3},
{ name: 'GIFTER', content: 'sender' },
{ name: 'X_MONTHS_SUBSCRIPTION', content: 3 },
]);
});
@@ -416,8 +420,8 @@ describe('payments/index', () => {
context('Mystery Items', () => {
it('awards mystery items when within the timeframe for a mystery item', async () => {
let mayMysteryItemTimeframe = 1464725113000; // May 31st 2016
let fakeClock = sinon.useFakeTimers(mayMysteryItemTimeframe);
const mayMysteryItemTimeframe = 1464725113000; // May 31st 2016
const fakeClock = sinon.useFakeTimers(mayMysteryItemTimeframe);
data = { paymentMethod: 'PaymentMethod', user, sub: { key: 'basic_3mo' } };
@@ -437,7 +441,7 @@ describe('payments/index', () => {
it('does not awards mystery items when not within the timeframe for a mystery item', async () => {
const noMysteryItemTimeframe = 1462183920000; // May 2nd 2016
let fakeClock = sinon.useFakeTimers(noMysteryItemTimeframe);
const fakeClock = sinon.useFakeTimers(noMysteryItemTimeframe);
data = { paymentMethod: 'PaymentMethod', user, sub: { key: 'basic_3mo' } };
await api.createSubscription(data);
@@ -449,7 +453,7 @@ describe('payments/index', () => {
it('does not add a notification for mystery items if none was awarded', async () => {
const noMysteryItemTimeframe = 1462183920000; // May 2nd 2016
let fakeClock = sinon.useFakeTimers(noMysteryItemTimeframe);
const fakeClock = sinon.useFakeTimers(noMysteryItemTimeframe);
data = { paymentMethod: 'PaymentMethod', user, sub: { key: 'basic_3mo' } };
await api.createSubscription(data);
@@ -461,9 +465,9 @@ describe('payments/index', () => {
});
it('does not award mystery item when user already owns the item', async () => {
let mayMysteryItemTimeframe = 1464725113000; // May 31st 2016
let fakeClock = sinon.useFakeTimers(mayMysteryItemTimeframe);
let mayMysteryItem = 'armor_mystery_201605';
const mayMysteryItemTimeframe = 1464725113000; // May 31st 2016
const fakeClock = sinon.useFakeTimers(mayMysteryItemTimeframe);
const mayMysteryItem = 'armor_mystery_201605';
user.items.gear.owned[mayMysteryItem] = true;
data = { paymentMethod: 'PaymentMethod', user, sub: { key: 'basic_3mo' } };
@@ -477,9 +481,9 @@ describe('payments/index', () => {
});
it('does not award mystery item when user already has the item in the mystery box', async () => {
let mayMysteryItemTimeframe = 1464725113000; // May 31st 2016
let fakeClock = sinon.useFakeTimers(mayMysteryItemTimeframe);
let mayMysteryItem = 'armor_mystery_201605';
const mayMysteryItemTimeframe = 1464725113000; // May 31st 2016
const fakeClock = sinon.useFakeTimers(mayMysteryItemTimeframe);
const mayMysteryItem = 'armor_mystery_201605';
user.purchased.plan.mysteryItems = [mayMysteryItem];
sandbox.spy(user.purchased.plan.mysteryItems, 'push');
@@ -504,8 +508,8 @@ describe('payments/index', () => {
it('adds a month termination date by default', async () => {
await api.cancelSubscription(data);
let now = new Date();
let daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
const now = new Date();
const daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(29, 30); // 1 month +/- 1 days
});
@@ -515,8 +519,8 @@ describe('payments/index', () => {
await api.cancelSubscription(data);
let now = new Date();
let daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
const now = new Date();
const daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(89, 90); // 3 months +/- 1 days
});
@@ -526,8 +530,8 @@ describe('payments/index', () => {
await api.cancelSubscription(data);
let now = new Date();
let daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
const now = new Date();
const daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(38, 39); // should be about 1 month + 1/3 month
});
@@ -537,8 +541,8 @@ describe('payments/index', () => {
await api.cancelSubscription(data);
let now = new Date();
let daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
const now = new Date();
const daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(13, 15);
});
@@ -549,8 +553,8 @@ describe('payments/index', () => {
await api.cancelSubscription(data);
let now = new Date();
let daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
const now = new Date();
const daysTillTermination = moment(user.purchased.plan.dateTerminated).diff(now, 'days');
expect(daysTillTermination).to.be.within(13, 15);
});
@@ -641,9 +645,10 @@ describe('payments/index', () => {
it('sends a message from purchaser to recipient', async () => {
await api.buyGems(data);
let msg = '\`Hello recipient, sender has sent you 4 gems!\`';
const msg = '`Hello recipient, sender has sent you 4 gems!`';
expect(user.sendMessage).to.be.calledWith(recipient, { receiverMsg: msg, senderMsg: msg, save: false });
expect(user.sendMessage).to.be
.calledWith(recipient, { receiverMsg: msg, senderMsg: msg, save: false });
});
it('sends a message from purchaser to recipient wtih custom message', async () => {
@@ -652,7 +657,8 @@ describe('payments/index', () => {
await api.buyGems(data);
const msg = `\`Hello recipient, sender has sent you 4 gems!\` ${data.gift.message}`;
expect(user.sendMessage).to.be.calledWith(recipient, { receiverMsg: msg, senderMsg: msg, save: false });
expect(user.sendMessage).to.be
.calledWith(recipient, { receiverMsg: msg, senderMsg: msg, save: false });
});
it('sends a push notification if user did not gift to self', async () => {
@@ -671,8 +677,8 @@ describe('payments/index', () => {
});
await api.buyGems(data);
let [recipientsMessageContent, sendersMessageContent] = ['en', 'en'].map((lang) => {
let messageContent = t('giftedGemsFull', {
const [recipientsMessageContent, sendersMessageContent] = ['en', 'en'].map(lang => {
const messageContent = t('giftedGemsFull', {
username: recipient.profile.name,
sender: user.profile.name,
gemAmount: data.gift.gems.amount,
@@ -681,7 +687,10 @@ describe('payments/index', () => {
return `\`${messageContent}\``;
});
expect(user.sendMessage).to.be.calledWith(recipient, { receiverMsg: recipientsMessageContent, senderMsg: sendersMessageContent, save: false });
expect(user.sendMessage).to.be.calledWith(
recipient,
{ receiverMsg: recipientsMessageContent, senderMsg: sendersMessageContent, save: false },
);
});
});
});
@@ -693,7 +702,7 @@ describe('payments/index', () => {
await api.addSubToGroupUser(user, group);
let updatedUser = await User.findById(user._id).exec();
const updatedUser = await User.findById(user._id).exec();
expect(updatedUser.purchased.plan.planId).to.eql('group_plan_auto');
expect(updatedUser.purchased.plan.customerId).to.eql('group-plan');
@@ -709,17 +718,17 @@ describe('payments/index', () => {
it('awards the Royal Purple Jackalope pet', async () => {
await api.addSubToGroupUser(user, group);
let updatedUser = await User.findById(user._id).exec();
const updatedUser = await User.findById(user._id).exec();
expect(updatedUser.items.pets['Jackalope-RoyalPurple']).to.eql(5);
});
it('saves previously unused Mystery Items and Hourglasses for an expired subscription', async () => {
let planExpirationDate = new Date();
const planExpirationDate = new Date();
planExpirationDate.setDate(planExpirationDate.getDate() - 2);
let mysteryItem = 'item';
let mysteryItems = [mysteryItem];
let consecutive = {
const mysteryItem = 'item';
const mysteryItems = [mysteryItem];
const consecutive = {
trinkets: 3,
};
@@ -735,7 +744,7 @@ describe('payments/index', () => {
await user.save();
await api.addSubToGroupUser(user, group);
let updatedUser = await User.findById(user._id).exec();
const updatedUser = await User.findById(user._id).exec();
expect(updatedUser.purchased.plan.mysteryItems[0]).to.eql(mysteryItem);
expect(updatedUser.purchased.plan.consecutive.trinkets).to.equal(consecutive.trinkets);

View File

@@ -5,8 +5,10 @@ import { model as User } from '../../../../../../website/server/models/user';
describe('checkout success', () => {
const subKey = 'basic_3mo';
let user, gift, customerId, paymentId;
let paypalPaymentExecuteStub, paymentBuyGemsStub, paymentsCreateSubscritionStub;
let user; let gift; let customerId; let
paymentId;
let paypalPaymentExecuteStub; let paymentBuyGemsStub; let
paymentsCreateSubscritionStub;
beforeEach(() => {
user = new User();
@@ -25,7 +27,9 @@ describe('checkout success', () => {
});
it('purchases gems', async () => {
await paypalPayments.checkoutSuccess({user, gift, paymentId, customerId});
await paypalPayments.checkoutSuccess({
user, gift, paymentId, customerId,
});
expect(paypalPaymentExecuteStub).to.be.calledOnce;
expect(paypalPaymentExecuteStub).to.be.calledWith(paymentId, { payer_id: customerId });
@@ -38,7 +42,7 @@ describe('checkout success', () => {
});
it('gifts gems', async () => {
let receivingUser = new User();
const receivingUser = new User();
await receivingUser.save();
gift = {
type: 'gems',
@@ -48,7 +52,9 @@ describe('checkout success', () => {
},
};
await paypalPayments.checkoutSuccess({user, gift, paymentId, customerId});
await paypalPayments.checkoutSuccess({
user, gift, paymentId, customerId,
});
expect(paypalPaymentExecuteStub).to.be.calledOnce;
expect(paypalPaymentExecuteStub).to.be.calledWith(paymentId, { payer_id: customerId });
@@ -62,7 +68,7 @@ describe('checkout success', () => {
});
it('gifts subscription', async () => {
let receivingUser = new User();
const receivingUser = new User();
await receivingUser.save();
gift = {
type: 'subscription',
@@ -72,7 +78,9 @@ describe('checkout success', () => {
},
};
await paypalPayments.checkoutSuccess({user, gift, paymentId, customerId});
await paypalPayments.checkoutSuccess({
user, gift, paymentId, customerId,
});
expect(paypalPaymentExecuteStub).to.be.calledOnce;
expect(paypalPaymentExecuteStub).to.be.calledWith(paymentId, { payer_id: customerId });

View File

@@ -6,7 +6,7 @@ import { model as User } from '../../../../../../website/server/models/user';
import common from '../../../../../../website/common';
const BASE_URL = nconf.get('BASE_URL');
const i18n = common.i18n;
const { i18n } = common;
describe('checkout', () => {
const subKey = 'basic_3mo';
@@ -53,7 +53,7 @@ describe('checkout', () => {
});
it('creates a link for gem purchases', async () => {
let link = await paypalPayments.checkout({user: new User()});
const link = await paypalPayments.checkout({ user: new User() });
expect(paypalPaymentCreateStub).to.be.calledOnce;
expect(paypalPaymentCreateStub).to.be.calledWith(getPaypalCreateOptions('Habitica Gems', 5.00));
@@ -61,9 +61,9 @@ describe('checkout', () => {
});
it('should error if gem amount is too low', async () => {
let receivingUser = new User();
const receivingUser = new User();
receivingUser.save();
let gift = {
const gift = {
type: 'gems',
gems: {
amount: 0,
@@ -71,7 +71,7 @@ describe('checkout', () => {
},
};
await expect(paypalPayments.checkout({gift}))
await expect(paypalPayments.checkout({ gift }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 400,
message: 'Amount must be at least 1.',
@@ -80,10 +80,10 @@ describe('checkout', () => {
});
it('should error if the user cannot get gems', async () => {
let user = new User();
const user = new User();
sinon.stub(user, 'canGetGems').resolves(false);
await expect(paypalPayments.checkout({user})).to.eventually.be.rejected.and.to.eql({
await expect(paypalPayments.checkout({ user })).to.eventually.be.rejected.and.to.eql({
httpCode: 401,
message: i18n.t('groupPolicyCannotGetGems'),
name: 'NotAuthorized',
@@ -91,9 +91,9 @@ describe('checkout', () => {
});
it('creates a link for gifting gems', async () => {
let receivingUser = new User();
const receivingUser = new User();
await receivingUser.save();
let gift = {
const gift = {
type: 'gems',
uuid: receivingUser._id,
gems: {
@@ -101,7 +101,7 @@ describe('checkout', () => {
},
};
let link = await paypalPayments.checkout({gift});
const link = await paypalPayments.checkout({ gift });
expect(paypalPaymentCreateStub).to.be.calledOnce;
expect(paypalPaymentCreateStub).to.be.calledWith(getPaypalCreateOptions('Habitica Gems (Gift)', '4.00'));
@@ -109,9 +109,9 @@ describe('checkout', () => {
});
it('creates a link for gifting a subscription', async () => {
let receivingUser = new User();
const receivingUser = new User();
receivingUser.save();
let gift = {
const gift = {
type: 'subscription',
subscription: {
key: subKey,
@@ -119,7 +119,7 @@ describe('checkout', () => {
},
};
let link = await paypalPayments.checkout({gift});
const link = await paypalPayments.checkout({ gift });
expect(paypalPaymentCreateStub).to.be.calledOnce;
expect(paypalPaymentCreateStub).to.be.calledWith(getPaypalCreateOptions('mo. Habitica Subscription (Gift)', '15.00'));

View File

@@ -3,13 +3,15 @@ import paypalPayments from '../../../../../../website/server/libs/payments/paypa
import payments from '../../../../../../website/server/libs/payments/payments';
import {
generateGroup,
} from '../../../../../helpers/api-unit.helper.js';
} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
describe('ipn', () => {
const subKey = 'basic_3mo';
let user, group, txn_type, userPaymentId, groupPaymentId;
let ipnVerifyAsyncStub, paymentCancelSubscriptionSpy;
let user; let group; let txn_type; let userPaymentId; let
groupPaymentId;
let ipnVerifyAsyncStub; let
paymentCancelSubscriptionSpy;
beforeEach(async () => {
txn_type = 'recurring_payment_profile_cancel';
@@ -38,16 +40,16 @@ describe('ipn', () => {
paymentCancelSubscriptionSpy = sinon.stub(payments, 'cancelSubscription').resolves({});
});
afterEach(function () {
afterEach(() => {
paypalPayments.ipnVerifyAsync.restore();
payments.cancelSubscription.restore();
});
it('should cancel a user subscription', async () => {
await paypalPayments.ipn({txn_type, recurring_payment_id: userPaymentId});
await paypalPayments.ipn({ txn_type, recurring_payment_id: userPaymentId });
expect(ipnVerifyAsyncStub).to.be.calledOnce;
expect(ipnVerifyAsyncStub).to.be.calledWith({txn_type, recurring_payment_id: userPaymentId});
expect(ipnVerifyAsyncStub).to.be.calledWith({ txn_type, recurring_payment_id: userPaymentId });
expect(paymentCancelSubscriptionSpy).to.be.calledOnce;
expect(paymentCancelSubscriptionSpy.args[0][0].user._id).to.eql(user._id);
@@ -55,10 +57,10 @@ describe('ipn', () => {
});
it('should cancel a group subscription', async () => {
await paypalPayments.ipn({txn_type, recurring_payment_id: groupPaymentId});
await paypalPayments.ipn({ txn_type, recurring_payment_id: groupPaymentId });
expect(ipnVerifyAsyncStub).to.be.calledOnce;
expect(ipnVerifyAsyncStub).to.be.calledWith({txn_type, recurring_payment_id: groupPaymentId});
expect(ipnVerifyAsyncStub).to.be.calledWith({ txn_type, recurring_payment_id: groupPaymentId });
expect(paymentCancelSubscriptionSpy).to.be.calledOnce;
expect(paymentCancelSubscriptionSpy).to.be.calledWith({ groupId: group._id, paymentMethod: 'Paypal' });

View File

@@ -3,17 +3,19 @@ import paypalPayments from '../../../../../../website/server/libs/payments/paypa
import payments from '../../../../../../website/server/libs/payments/payments';
import {
generateGroup,
} from '../../../../../helpers/api-unit.helper.js';
} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import common from '../../../../../../website/common';
import { createNonLeaderGroupMember } from '../paymentHelpers';
const i18n = common.i18n;
const { i18n } = common;
describe('subscribeCancel', () => {
const subKey = 'basic_3mo';
let user, group, groupId, customerId, groupCustomerId, nextBillingDate;
let paymentCancelSubscriptionSpy, paypalBillingAgreementCancelStub, paypalBillingAgreementGetStub;
let user; let group; let groupId; let customerId; let groupCustomerId; let
nextBillingDate;
let paymentCancelSubscriptionSpy; let paypalBillingAgreementCancelStub; let
paypalBillingAgreementGetStub;
beforeEach(async () => {
customerId = 'customer-id';
@@ -49,7 +51,7 @@ describe('subscribeCancel', () => {
paymentCancelSubscriptionSpy = sinon.stub(payments, 'cancelSubscription').resolves({});
});
afterEach(function () {
afterEach(() => {
paypalPayments.paypalBillingAgreementGet.restore();
paypalPayments.paypalBillingAgreementCancel.restore();
payments.cancelSubscription.restore();
@@ -58,7 +60,7 @@ describe('subscribeCancel', () => {
it('should throw an error if we are missing a subscription', async () => {
user.purchased.plan.customerId = undefined;
await expect(paypalPayments.subscribeCancel({user}))
await expect(paypalPayments.subscribeCancel({ user }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -67,7 +69,7 @@ describe('subscribeCancel', () => {
});
it('should throw an error if group is not found', async () => {
await expect(paypalPayments.subscribeCancel({user, groupId: 'fake-id'}))
await expect(paypalPayments.subscribeCancel({ user, groupId: 'fake-id' }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 404,
name: 'NotFound',
@@ -76,9 +78,9 @@ describe('subscribeCancel', () => {
});
it('should throw an error if user is not group leader', async () => {
let nonLeader = await createNonLeaderGroupMember(group);
const nonLeader = await createNonLeaderGroupMember(group);
await expect(paypalPayments.subscribeCancel({user: nonLeader, groupId: group._id}))
await expect(paypalPayments.subscribeCancel({ user: nonLeader, groupId: group._id }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -87,7 +89,7 @@ describe('subscribeCancel', () => {
});
it('should cancel a user subscription', async () => {
await paypalPayments.subscribeCancel({user});
await paypalPayments.subscribeCancel({ user });
expect(paypalBillingAgreementGetStub).to.be.calledOnce;
expect(paypalBillingAgreementGetStub).to.be.calledWith(customerId);
@@ -105,7 +107,7 @@ describe('subscribeCancel', () => {
});
it('should cancel a group subscription', async () => {
await paypalPayments.subscribeCancel({user, groupId: group._id});
await paypalPayments.subscribeCancel({ user, groupId: group._id });
expect(paypalBillingAgreementGetStub).to.be.calledOnce;
expect(paypalBillingAgreementGetStub).to.be.calledWith(groupCustomerId);

View File

@@ -3,14 +3,16 @@ import paypalPayments from '../../../../../../website/server/libs/payments/paypa
import payments from '../../../../../../website/server/libs/payments/payments';
import {
generateGroup,
} from '../../../../../helpers/api-unit.helper.js';
} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import common from '../../../../../../website/common';
describe('subscribeSuccess', () => {
const subKey = 'basic_3mo';
let user, group, block, groupId, token, headers, customerId;
let paypalBillingAgreementExecuteStub, paymentsCreateSubscritionStub;
let user; let group; let block; let groupId; let token; let headers; let
customerId;
let paypalBillingAgreementExecuteStub; let
paymentsCreateSubscritionStub;
beforeEach(async () => {
user = new User();
@@ -40,7 +42,9 @@ describe('subscribeSuccess', () => {
});
it('creates a user subscription', async () => {
await paypalPayments.subscribeSuccess({user, block, groupId, token, headers});
await paypalPayments.subscribeSuccess({
user, block, groupId, token, headers,
});
expect(paypalBillingAgreementExecuteStub).to.be.calledOnce;
expect(paypalBillingAgreementExecuteStub).to.be.calledWith(token, {});
@@ -59,7 +63,9 @@ describe('subscribeSuccess', () => {
it('create a group subscription', async () => {
groupId = group._id;
await paypalPayments.subscribeSuccess({user, block, groupId, token, headers});
await paypalPayments.subscribeSuccess({
user, block, groupId, token, headers,
});
expect(paypalBillingAgreementExecuteStub).to.be.calledOnce;
expect(paypalBillingAgreementExecuteStub).to.be.calledWith(token, {});

View File

@@ -6,16 +6,17 @@ import paypalPayments from '../../../../../../website/server/libs/payments/paypa
import { model as Coupon } from '../../../../../../website/server/models/coupon';
import common from '../../../../../../website/common';
const i18n = common.i18n;
const { i18n } = common;
describe('subscribe', () => {
const subKey = 'basic_3mo';
let coupon, sub, approvalHerf;
let coupon; let sub; let
approvalHerf;
let paypalBillingAgreementCreateStub;
beforeEach(() => {
approvalHerf = 'approvalHerf-test';
sub = Object.assign({}, common.content.subscriptionBlocks[subKey]);
sub = { ...common.content.subscriptionBlocks[subKey] };
paypalBillingAgreementCreateStub = sinon.stub(paypalPayments, 'paypalBillingAgreementCreate')
.resolves({
@@ -30,7 +31,7 @@ describe('subscribe', () => {
it('should throw an error when coupon code is missing', async () => {
sub.discount = 40;
await expect(paypalPayments.subscribe({sub, coupon}))
await expect(paypalPayments.subscribe({ sub, coupon }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 400,
name: 'BadRequest',
@@ -43,13 +44,13 @@ describe('subscribe', () => {
sub.key = 'google_6mo';
coupon = 'example-coupon';
let couponModel = new Coupon();
const couponModel = new Coupon();
couponModel.event = 'google_6mo';
await couponModel.save();
sinon.stub(cc, 'validate').returns('invalid');
await expect(paypalPayments.subscribe({sub, coupon}))
await expect(paypalPayments.subscribe({ sub, coupon }))
.to.eventually.be.rejected.and.to.eql({
httpCode: 401,
name: 'NotAuthorized',
@@ -63,17 +64,17 @@ describe('subscribe', () => {
sub.key = 'google_6mo';
coupon = 'example-coupon';
let couponModel = new Coupon();
const couponModel = new Coupon();
couponModel.event = 'google_6mo';
let updatedCouponModel = await couponModel.save();
const updatedCouponModel = await couponModel.save();
sinon.stub(cc, 'validate').returns(updatedCouponModel._id);
let link = await paypalPayments.subscribe({sub, coupon});
const link = await paypalPayments.subscribe({ sub, coupon });
expect(link).to.eql(approvalHerf);
expect(paypalBillingAgreementCreateStub).to.be.calledOnce;
let billingPlanTitle = `Habitica Subscription ($${sub.price} every ${sub.months} months, recurring)`;
const billingPlanTitle = `Habitica Subscription ($${sub.price} every ${sub.months} months, recurring)`;
expect(paypalBillingAgreementCreateStub).to.be.calledWith({
name: billingPlanTitle,
description: billingPlanTitle,
@@ -92,11 +93,11 @@ describe('subscribe', () => {
it('creates a link for a subscription', async () => {
delete sub.discount;
let link = await paypalPayments.subscribe({sub, coupon});
const link = await paypalPayments.subscribe({ sub, coupon });
expect(link).to.eql(approvalHerf);
expect(paypalBillingAgreementCreateStub).to.be.calledOnce;
let billingPlanTitle = `Habitica Subscription ($${sub.price} every ${sub.months} months, recurring)`;
const billingPlanTitle = `Habitica Subscription ($${sub.price} every ${sub.months} months, recurring)`;
expect(paypalBillingAgreementCreateStub).to.be.calledWith({
name: billingPlanTitle,
description: billingPlanTitle,

View File

@@ -2,18 +2,19 @@ import stripeModule from 'stripe';
import {
generateGroup,
} from '../../../../../helpers/api-unit.helper.js';
} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import stripePayments from '../../../../../../website/server/libs/payments/stripe';
import payments from '../../../../../../website/server/libs/payments/payments';
import common from '../../../../../../website/common';
const i18n = common.i18n;
const { i18n } = common;
describe('cancel subscription', () => {
const subKey = 'basic_3mo';
const stripe = stripeModule('test');
let user, groupId, group;
let user; let groupId; let
group;
beforeEach(async () => {
user = new User();
@@ -62,7 +63,7 @@ describe('cancel subscription', () => {
});
it('throws an error if user is not the group leader', async () => {
let nonLeader = new User();
const nonLeader = new User();
nonLeader.guilds.push(groupId);
await nonLeader.save();
@@ -78,7 +79,9 @@ describe('cancel subscription', () => {
});
describe('success', () => {
let stripeDeleteCustomerStub, paymentsCancelSubStub, stripeRetrieveStub, subscriptionId, currentPeriodEndTimeStamp;
let stripeDeleteCustomerStub; let paymentsCancelSubStub;
let stripeRetrieveStub; let subscriptionId; let
currentPeriodEndTimeStamp;
beforeEach(() => {
subscriptionId = 'subId';
@@ -89,7 +92,10 @@ describe('cancel subscription', () => {
stripeRetrieveStub = sinon.stub(stripe.customers, 'retrieve')
.resolves({
subscriptions: {
data: [{id: subscriptionId, current_period_end: currentPeriodEndTimeStamp}], // eslint-disable-line camelcase
data: [{
id: subscriptionId,
current_period_end: currentPeriodEndTimeStamp,
}], // eslint-disable-line camelcase
},
});
});

View File

@@ -3,19 +3,22 @@ import cc from 'coupon-code';
import {
generateGroup,
} from '../../../../../helpers/api-unit.helper.js';
} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import { model as Coupon } from '../../../../../../website/server/models/coupon';
import stripePayments from '../../../../../../website/server/libs/payments/stripe';
import payments from '../../../../../../website/server/libs/payments/payments';
import common from '../../../../../../website/common';
const i18n = common.i18n;
const { i18n } = common;
describe('checkout with subscription', () => {
const subKey = 'basic_3mo';
const stripe = stripeModule('test');
let user, group, data, gift, sub, groupId, email, headers, coupon, customerIdResponse, subscriptionId, token;
let user; let group; let data; let gift; let sub;
let groupId; let email; let headers; let coupon;
let customerIdResponse; let subscriptionId; let
token;
let spy;
let stripeCreateCustomerSpy;
let stripePaymentsCreateSubSpy;
@@ -57,10 +60,10 @@ describe('checkout with subscription', () => {
spy.resolves;
stripeCreateCustomerSpy = sinon.stub(stripe.customers, 'create');
let stripCustomerResponse = {
const stripCustomerResponse = {
id: customerIdResponse,
subscriptions: {
data: [{id: subscriptionId}],
data: [{ id: subscriptionId }],
},
};
stripeCreateCustomerSpy.resolves(stripCustomerResponse);
@@ -72,7 +75,7 @@ describe('checkout with subscription', () => {
data.sub.quantity = 3;
});
afterEach(function () {
afterEach(() => {
stripe.subscriptions.update.restore();
stripe.customers.create.restore();
payments.createSubscription.restore();
@@ -120,7 +123,7 @@ describe('checkout with subscription', () => {
sub.key = 'google_6mo';
coupon = 'example-coupon';
let couponModel = new Coupon();
const couponModel = new Coupon();
couponModel.event = 'google_6mo';
await couponModel.save();
@@ -149,9 +152,9 @@ describe('checkout with subscription', () => {
sub.key = 'google_6mo';
coupon = 'example-coupon';
let couponModel = new Coupon();
const couponModel = new Coupon();
couponModel.event = 'google_6mo';
let updatedCouponModel = await couponModel.save();
const updatedCouponModel = await couponModel.save();
sinon.stub(cc, 'validate').returns(updatedCouponModel._id);

View File

@@ -5,13 +5,15 @@ import stripePayments from '../../../../../../website/server/libs/payments/strip
import payments from '../../../../../../website/server/libs/payments/payments';
import common from '../../../../../../website/common';
const i18n = common.i18n;
const { i18n } = common;
describe('checkout', () => {
const subKey = 'basic_3mo';
const stripe = stripeModule('test');
let stripeChargeStub, paymentBuyGemsStub, paymentCreateSubscritionStub;
let user, gift, groupId, email, headers, coupon, customerIdResponse, token;
let stripeChargeStub; let paymentBuyGemsStub; let
paymentCreateSubscritionStub;
let user; let gift; let groupId; let email; let headers; let coupon; let customerIdResponse; let
token;
beforeEach(() => {
user = new User();
@@ -23,7 +25,7 @@ describe('checkout', () => {
token = 'test-token';
customerIdResponse = 'example-customerIdResponse';
let stripCustomerResponse = {
const stripCustomerResponse = {
id: customerIdResponse,
};
stripeChargeStub = sinon.stub(stripe.charges, 'create').resolves(stripCustomerResponse);
@@ -54,7 +56,7 @@ describe('checkout', () => {
});
it('should error if gem amount is too low', async () => {
let receivingUser = new User();
const receivingUser = new User();
receivingUser.save();
gift = {
type: 'gems',
@@ -132,7 +134,7 @@ describe('checkout', () => {
});
it('should gift gems', async () => {
let receivingUser = new User();
const receivingUser = new User();
await receivingUser.save();
gift = {
type: 'gems',
@@ -169,7 +171,7 @@ describe('checkout', () => {
});
it('should gift a subscription', async () => {
let receivingUser = new User();
const receivingUser = new User();
receivingUser.save();
gift = {
type: 'subscription',

View File

@@ -2,17 +2,18 @@ import stripeModule from 'stripe';
import {
generateGroup,
} from '../../../../../helpers/api-unit.helper.js';
} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import stripePayments from '../../../../../../website/server/libs/payments/stripe';
import common from '../../../../../../website/common';
const i18n = common.i18n;
const { i18n } = common;
describe('edit subscription', () => {
const subKey = 'basic_3mo';
const stripe = stripeModule('test');
let user, groupId, group, token;
let user; let groupId; let group; let
token;
beforeEach(async () => {
user = new User();
@@ -76,7 +77,7 @@ describe('edit subscription', () => {
});
it('throws an error if user is not the group leader', async () => {
let nonLeader = new User();
const nonLeader = new User();
nonLeader.guilds.push(groupId);
await nonLeader.save();
@@ -93,13 +94,14 @@ describe('edit subscription', () => {
});
describe('success', () => {
let stripeListSubscriptionStub, stripeUpdateSubscriptionStub, subscriptionId;
let stripeListSubscriptionStub; let stripeUpdateSubscriptionStub; let
subscriptionId;
beforeEach(() => {
subscriptionId = 'subId';
stripeListSubscriptionStub = sinon.stub(stripe.subscriptions, 'list')
.resolves({
data: [{id: subscriptionId}],
data: [{ id: subscriptionId }],
});
stripeUpdateSubscriptionStub = sinon.stub(stripe.subscriptions, 'update').resolves({});
@@ -118,11 +120,13 @@ describe('edit subscription', () => {
}, stripe);
expect(stripeListSubscriptionStub).to.be.calledOnce;
expect(stripeListSubscriptionStub).to.be.calledWith({customer: user.purchased.plan.customerId});
expect(stripeListSubscriptionStub).to.be.calledWith({
customer: user.purchased.plan.customerId,
});
expect(stripeUpdateSubscriptionStub).to.be.calledOnce;
expect(stripeUpdateSubscriptionStub).to.be.calledWith(
subscriptionId,
{ card: token }
{ card: token },
);
});
@@ -134,11 +138,13 @@ describe('edit subscription', () => {
}, stripe);
expect(stripeListSubscriptionStub).to.be.calledOnce;
expect(stripeListSubscriptionStub).to.be.calledWith({customer: group.purchased.plan.customerId});
expect(stripeListSubscriptionStub).to.be.calledWith({
customer: group.purchased.plan.customerId,
});
expect(stripeUpdateSubscriptionStub).to.be.calledOnce;
expect(stripeUpdateSubscriptionStub).to.be.calledWith(
subscriptionId,
{ card: token }
{ card: token },
);
});
});

View File

@@ -1,25 +1,25 @@
import stripeModule from 'stripe';
import { v4 as uuid } from 'uuid';
import moment from 'moment';
import {
generateGroup,
} from '../../../../../helpers/api-unit.helper.js';
} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import stripePayments from '../../../../../../website/server/libs/payments/stripe';
import payments from '../../../../../../website/server/libs/payments/payments';
import common from '../../../../../../website/common';
import logger from '../../../../../../website/server/libs/logger';
import { v4 as uuid } from 'uuid';
import moment from 'moment';
const i18n = common.i18n;
const { i18n } = common;
describe('Stripe - Webhooks', () => {
const stripe = stripeModule('test');
describe('all events', () => {
const eventType = 'account.updated';
const event = {id: 123};
const eventRetrieved = {type: eventType};
const event = { id: 123 };
const eventRetrieved = { type: eventType };
beforeEach(() => {
sinon.stub(stripe.events, 'retrieve').resolves(eventRetrieved);
@@ -33,7 +33,7 @@ describe('Stripe - Webhooks', () => {
it('logs an error if an unsupported webhook event is passed', async () => {
const error = new Error(`Missing handler for Stripe webhook ${eventType}`);
await stripePayments.handleWebhooks({requestBody: event}, stripe);
await stripePayments.handleWebhooks({ requestBody: event }, stripe);
expect(logger.error).to.have.been.calledOnce;
const calledWith = logger.error.getCall(0).args;
@@ -42,7 +42,7 @@ describe('Stripe - Webhooks', () => {
});
it('retrieves and validates the event from Stripe', async () => {
await stripePayments.handleWebhooks({requestBody: event}, stripe);
await stripePayments.handleWebhooks({ requestBody: event }, stripe);
expect(stripe.events.retrieve).to.have.been.calledOnce;
expect(stripe.events.retrieve).to.have.been.calledWith(event.id);
});
@@ -68,7 +68,7 @@ describe('Stripe - Webhooks', () => {
request: 123,
});
await stripePayments.handleWebhooks({requestBody: {}}, stripe);
await stripePayments.handleWebhooks({ requestBody: {} }, stripe);
expect(stripe.events.retrieve).to.have.been.calledOnce;
expect(stripe.customers.del).to.not.have.been.called;
@@ -93,11 +93,12 @@ describe('Stripe - Webhooks', () => {
request: null,
});
await expect(stripePayments.handleWebhooks({requestBody: {}}, stripe)).to.eventually.be.rejectedWith({
message: i18n.t('userNotFound'),
httpCode: 404,
name: 'NotFound',
});
await expect(stripePayments.handleWebhooks({ requestBody: {} }, stripe))
.to.eventually.be.rejectedWith({
message: i18n.t('userNotFound'),
httpCode: 404,
name: 'NotFound',
});
expect(stripe.customers.del).to.not.have.been.called;
expect(payments.cancelSubscription).to.not.have.been.called;
@@ -108,7 +109,7 @@ describe('Stripe - Webhooks', () => {
it('deletes the customer on Stripe and calls payments.cancelSubscription', async () => {
const customerId = '456';
let subscriber = new User();
const subscriber = new User();
subscriber.purchased.plan.customerId = customerId;
subscriber.purchased.plan.paymentMethod = 'Stripe';
await subscriber.save();
@@ -127,13 +128,13 @@ describe('Stripe - Webhooks', () => {
request: null,
});
await stripePayments.handleWebhooks({requestBody: {}}, stripe);
await stripePayments.handleWebhooks({ requestBody: {} }, stripe);
expect(stripe.customers.del).to.have.been.calledOnce;
expect(stripe.customers.del).to.have.been.calledWith(customerId);
expect(payments.cancelSubscription).to.have.been.calledOnce;
let cancelSubscriptionOpts = payments.cancelSubscription.lastCall.args[0];
const cancelSubscriptionOpts = payments.cancelSubscription.lastCall.args[0];
expect(cancelSubscriptionOpts.user._id).to.equal(subscriber._id);
expect(cancelSubscriptionOpts.paymentMethod).to.equal('Stripe');
expect(Math.round(moment(cancelSubscriptionOpts.nextBill).diff(new Date(), 'days', true))).to.equal(3);
@@ -160,11 +161,12 @@ describe('Stripe - Webhooks', () => {
request: null,
});
await expect(stripePayments.handleWebhooks({requestBody: {}}, stripe)).to.eventually.be.rejectedWith({
message: i18n.t('groupNotFound'),
httpCode: 404,
name: 'NotFound',
});
await expect(stripePayments.handleWebhooks({ requestBody: {} }, stripe))
.to.eventually.be.rejectedWith({
message: i18n.t('groupNotFound'),
httpCode: 404,
name: 'NotFound',
});
expect(stripe.customers.del).to.not.have.been.called;
expect(payments.cancelSubscription).to.not.have.been.called;
@@ -175,7 +177,7 @@ describe('Stripe - Webhooks', () => {
it('throws an error if the group leader is not found', async () => {
const customerId = 456;
let subscriber = generateGroup({
const subscriber = generateGroup({
name: 'test group',
type: 'guild',
privacy: 'public',
@@ -199,11 +201,12 @@ describe('Stripe - Webhooks', () => {
request: null,
});
await expect(stripePayments.handleWebhooks({requestBody: {}}, stripe)).to.eventually.be.rejectedWith({
message: i18n.t('userNotFound'),
httpCode: 404,
name: 'NotFound',
});
await expect(stripePayments.handleWebhooks({ requestBody: {} }, stripe))
.to.eventually.be.rejectedWith({
message: i18n.t('userNotFound'),
httpCode: 404,
name: 'NotFound',
});
expect(stripe.customers.del).to.not.have.been.called;
expect(payments.cancelSubscription).to.not.have.been.called;
@@ -214,10 +217,10 @@ describe('Stripe - Webhooks', () => {
it('deletes the customer on Stripe and calls payments.cancelSubscription', async () => {
const customerId = '456';
let leader = new User();
const leader = new User();
await leader.save();
let subscriber = generateGroup({
const subscriber = generateGroup({
name: 'test group',
type: 'guild',
privacy: 'public',
@@ -241,13 +244,13 @@ describe('Stripe - Webhooks', () => {
request: null,
});
await stripePayments.handleWebhooks({requestBody: {}}, stripe);
await stripePayments.handleWebhooks({ requestBody: {} }, stripe);
expect(stripe.customers.del).to.have.been.calledOnce;
expect(stripe.customers.del).to.have.been.calledWith(customerId);
expect(payments.cancelSubscription).to.have.been.calledOnce;
let cancelSubscriptionOpts = payments.cancelSubscription.lastCall.args[0];
const cancelSubscriptionOpts = payments.cancelSubscription.lastCall.args[0];
expect(cancelSubscriptionOpts.user._id).to.equal(leader._id);
expect(cancelSubscriptionOpts.paymentMethod).to.equal('Stripe');
expect(Math.round(moment(cancelSubscriptionOpts.nextBill).diff(new Date(), 'days', true))).to.equal(3);

View File

@@ -2,7 +2,7 @@ import stripeModule from 'stripe';
import {
generateGroup,
} from '../../../../../helpers/api-unit.helper.js';
} from '../../../../../helpers/api-unit.helper';
import { model as User } from '../../../../../../website/server/models/user';
import { model as Group } from '../../../../../../website/server/models/group';
import stripePayments from '../../../../../../website/server/libs/payments/stripe';
@@ -10,9 +10,10 @@ import payments from '../../../../../../website/server/libs/payments/payments';
describe('Stripe - Upgrade Group Plan', () => {
const stripe = stripeModule('test');
let spy, data, user, group;
let spy; let data; let user; let
group;
beforeEach(async function () {
beforeEach(async () => {
user = new User();
user.profile.name = 'sender';
@@ -44,7 +45,7 @@ describe('Stripe - Upgrade Group Plan', () => {
stripePayments.setStripeApi(stripe);
});
afterEach(function () {
afterEach(() => {
stripe.subscriptions.update.restore();
});
@@ -52,7 +53,7 @@ describe('Stripe - Upgrade Group Plan', () => {
data.paymentMethod = 'Stripe';
await payments.createSubscription(data);
let updatedGroup = await Group.findById(group._id).exec();
const updatedGroup = await Group.findById(group._id).exec();
expect(updatedGroup.purchased.plan.quantity).to.eql(3);
updatedGroup.memberCount += 1;