How to use sandbox.fake.resolves method in sinon

Best JavaScript code snippet using sinon

paypal-processor.js

Source:paypal-processor.js Github

copy

Full Screen

...88 });89 });90 describe('cancelInvoiceSubscription', () => {91 it('marks invoice and cancels subscription', async () => {92 mockStripeHelper.markUncollectible = sandbox.fake.resolves({});93 mockStripeHelper.cancelSubscription = sandbox.fake.resolves({});94 const result = await processor.cancelInvoiceSubscription(paidInvoice);95 assert.deepEqual(result, [{}, {}]);96 sinon.assert.calledOnceWithExactly(97 mockStripeHelper.markUncollectible,98 paidInvoice99 );100 sinon.assert.calledOnceWithExactly(101 mockStripeHelper.cancelSubscription,102 paidInvoice.subscription.id103 );104 });105 });106 describe('ensureAccurateAttemptCount', () => {107 it('does nothing if the attempts match', async () => {108 mockStripeHelper.getPaymentAttempts = sandbox.fake.returns(1);109 mockStripeHelper.updatePaymentAttempts = sandbox.fake.resolves({});110 await processor.ensureAccurateAttemptCount(unpaidInvoice, [{}]);111 sinon.assert.notCalled(mockStripeHelper.updatePaymentAttempts);112 });113 it('updates the attempts if they do not match', async () => {114 const invoice = deepCopy(unpaidInvoice);115 mockStripeHelper.getPaymentAttempts = sandbox.fake.returns(2);116 mockStripeHelper.updatePaymentAttempts = sandbox.fake.resolves({});117 await processor.ensureAccurateAttemptCount(invoice, [{}]);118 sinon.assert.calledOnceWithExactly(119 mockStripeHelper.updatePaymentAttempts,120 invoice,121 1122 );123 sandbox.reset();124 await processor.ensureAccurateAttemptCount(invoice, [{}, {}, {}]);125 sinon.assert.calledOnceWithExactly(126 mockStripeHelper.updatePaymentAttempts,127 invoice,128 3129 );130 });131 });132 describe('handlePaidTransaction', () => {133 it('returns false if no success', async () => {134 let result = await processor.handlePaidTransaction(unpaidInvoice, []);135 assert.isFalse(result);136 result = await processor.handlePaidTransaction(unpaidInvoice, [137 { status: 'Pending' },138 ]);139 assert.isFalse(result);140 });141 it('returns true if success', async () => {142 mockStripeHelper.updateInvoiceWithPaypalTransactionId =143 sandbox.fake.resolves({});144 mockStripeHelper.payInvoiceOutOfBand = sandbox.fake.resolves({});145 const result = await processor.handlePaidTransaction(unpaidInvoice, [146 { status: 'Completed', transactionId: 'test1234' },147 ]);148 assert.isTrue(result);149 sinon.assert.calledOnceWithExactly(150 mockStripeHelper.updateInvoiceWithPaypalTransactionId,151 unpaidInvoice,152 'test1234'153 );154 });155 it('returns true and logs if > 1 success', async () => {156 mockStripeHelper.updateInvoiceWithPaypalTransactionId =157 sandbox.fake.resolves({});158 mockStripeHelper.payInvoiceOutOfBand = sandbox.fake.resolves({});159 mockLog.error = sandbox.fake.returns({});160 const result = await processor.handlePaidTransaction(unpaidInvoice, [161 { status: 'Completed', transactionId: 'test1234' },162 { status: 'Completed', transactionId: 'test12345' },163 ]);164 assert.isTrue(result);165 sinon.assert.calledOnceWithExactly(166 mockStripeHelper.updateInvoiceWithPaypalTransactionId,167 unpaidInvoice,168 'test1234'169 );170 sinon.assert.calledOnceWithExactly(171 mockLog.error,172 'multipleCompletedTransactions',173 {174 customer: unpaidInvoice.customer,175 invoiceId: unpaidInvoice.id,176 transactionCount: 2,177 excessTransactions: ['test12345'],178 }179 );180 });181 });182 describe('handlePendingTransaction', () => {183 it('returns true if a pending within grace period exists', async () => {184 processor.inGracePeriod = sandbox.fake.returns(true);185 const result = await processor.handlePendingTransaction(unpaidInvoice, [186 { status: 'Pending' },187 ]);188 assert.isTrue(result);189 sinon.assert.calledOnceWithExactly(190 processor.inGracePeriod,191 unpaidInvoice192 );193 });194 it('returns true and logs if multiple pending within grace exist', async () => {195 processor.inGracePeriod = sandbox.fake.returns(true);196 mockLog.error = sandbox.fake.returns({});197 const result = await processor.handlePendingTransaction(unpaidInvoice, [198 { status: 'Pending' },199 { status: 'Pending' },200 ]);201 assert.isTrue(result);202 sinon.assert.calledOnceWithExactly(203 processor.inGracePeriod,204 unpaidInvoice205 );206 sinon.assert.calledOnceWithExactly(207 mockLog.error,208 'multiplePendingTransactions',209 { customer: unpaidInvoice.customer, invoiceId: unpaidInvoice.id }210 );211 });212 it('returns false if no pending exist', async () => {213 processor.inGracePeriod = sandbox.fake.returns(true);214 const result = await processor.handlePendingTransaction(unpaidInvoice, [215 { status: 'Completed' },216 ]);217 assert.isFalse(result);218 sinon.assert.calledOnceWithExactly(219 processor.inGracePeriod,220 unpaidInvoice221 );222 });223 it('returns false if no pending within grace period exist', async () => {224 processor.inGracePeriod = sandbox.fake.returns(false);225 const result = await processor.handlePendingTransaction(unpaidInvoice, [226 { status: 'Pending' },227 ]);228 assert.isFalse(result);229 sinon.assert.calledOnceWithExactly(230 processor.inGracePeriod,231 unpaidInvoice232 );233 });234 });235 describe('makePaymentAttempt', () => {236 it('processes zero invoice if its 0', async () => {237 const invoice = deepCopy(unpaidInvoice);238 invoice.amount_due = 0;239 mockPaypalHelper.processZeroInvoice = sandbox.fake.resolves({});240 const result = await processor.makePaymentAttempt(invoice);241 assert.isTrue(result);242 sinon.assert.calledOnceWithExactly(243 mockPaypalHelper.processZeroInvoice,244 invoice245 );246 });247 it('processes an invoice successfully', async () => {248 const invoice = deepCopy(unpaidInvoice);249 mockPaypalHelper.processInvoice = sandbox.fake.resolves({});250 mockStripeHelper.getCustomerPaypalAgreement = sandbox.fake.resolves({});251 const result = await processor.makePaymentAttempt(invoice);252 assert.isTrue(result);253 sinon.assert.notCalled(mockStripeHelper.getCustomerPaypalAgreement);254 });255 it('handles a paypal source error', async () => {256 const paypalHelper = new PayPalHelper({ mockLog });257 const invoice = deepCopy(unpaidInvoice);258 const testCustomer = { metadata: { userid: 'testuser' } };259 invoice.customer = testCustomer;260 const failedResponse = deepCopy(failedDoReferenceTransactionResponse);261 failedResponse.L_ERRORCODE0 = PAYPAL_SOURCE_ERRORS[0];262 const rawString = paypalHelper.client.objectToNVP(failedResponse);263 const parsedNvpObject = paypalHelper.client.nvpToObject(rawString);264 const throwErr = new PayPalClientError(rawString, parsedNvpObject);265 mockPaypalHelper.processInvoice = sandbox.fake.rejects(throwErr);266 mockStripeHelper.removeCustomerPaypalAgreement = sandbox.fake.resolves(267 {}268 );269 mockStripeHelper.getCustomerPaypalAgreement =270 sandbox.fake.returns('testba');271 mockStripeHelper.getEmailTypes = sandbox.fake.returns([]);272 mockHandler.sendSubscriptionPaymentFailedEmail = sandbox.fake.resolves(273 {}274 );275 const result = await processor.makePaymentAttempt(invoice);276 assert.isFalse(result);277 sinon.assert.calledOnceWithExactly(278 mockHandler.sendSubscriptionPaymentFailedEmail,279 invoice280 );281 sinon.assert.notCalled(mockStripeHelper.getCustomerPaypalAgreement);282 sinon.assert.notCalled(mockStripeHelper.removeCustomerPaypalAgreement);283 });284 it('handles an invalid billing agreement', async () => {285 const paypalHelper = new PayPalHelper({ mockLog });286 const invoice = deepCopy(unpaidInvoice);287 const testCustomer = { metadata: { userid: 'testuser' } };288 invoice.customer = testCustomer;289 const failedResponse = deepCopy(failedDoReferenceTransactionResponse);290 failedResponse.L_ERRORCODE0 = PAYPAL_BILLING_AGREEMENT_INVALID;291 const rawString = paypalHelper.client.objectToNVP(failedResponse);292 const parsedNvpObject = paypalHelper.client.nvpToObject(rawString);293 const throwErr = new PayPalClientError(rawString, parsedNvpObject);294 mockPaypalHelper.processInvoice = sandbox.fake.rejects(throwErr);295 mockStripeHelper.removeCustomerPaypalAgreement = sandbox.fake.resolves(296 {}297 );298 mockStripeHelper.getCustomerPaypalAgreement =299 sandbox.fake.returns('testba');300 mockStripeHelper.getEmailTypes = sandbox.fake.returns([]);301 mockHandler.sendSubscriptionPaymentFailedEmail = sandbox.fake.resolves(302 {}303 );304 const result = await processor.makePaymentAttempt(invoice);305 assert.isFalse(result);306 sinon.assert.calledOnceWithExactly(307 mockStripeHelper.getCustomerPaypalAgreement,308 testCustomer309 );310 sinon.assert.calledOnceWithExactly(311 mockStripeHelper.removeCustomerPaypalAgreement,312 'testuser',313 testCustomer.id,314 'testba'315 );316 sinon.assert.calledOnceWithExactly(317 mockHandler.sendSubscriptionPaymentFailedEmail,318 invoice319 );320 });321 it('handles an unexpected error', async () => {322 const invoice = deepCopy(unpaidInvoice);323 const testCustomer = { metadata: { userid: 'testuser' } };324 invoice.customer = testCustomer;325 const throwErr = new Error('test');326 mockLog.error = sandbox.fake.returns({});327 mockPaypalHelper.processInvoice = sandbox.fake.rejects(throwErr);328 mockStripeHelper.removeCustomerPaypalAgreement = sandbox.fake.resolves(329 {}330 );331 mockStripeHelper.getCustomerPaypalAgreement =332 sandbox.fake.returns('testba');333 const result = await processor.makePaymentAttempt(invoice);334 assert.isFalse(result);335 sinon.assert.calledOnceWithExactly(mockLog.error, 'processInvoice', {336 err: throwErr,337 invoiceId: invoice.id,338 });339 sinon.assert.notCalled(mockStripeHelper.getCustomerPaypalAgreement);340 sinon.assert.notCalled(mockStripeHelper.removeCustomerPaypalAgreement);341 });342 });343 describe('attemptsToday', () => {344 it('locates the transactions for today', () => {345 let yesterdayTransaction = new Date();346 yesterdayTransaction.setDate(yesterdayTransaction.getDate() - 1);347 yesterdayTransaction = yesterdayTransaction.toUTCString();348 const todayTransaction = new Date().toUTCString();349 const result = processor.attemptsToday([350 { timestamp: yesterdayTransaction },351 { timestamp: todayTransaction },352 ]);353 assert.equal(result, 1);354 });355 });356 describe('attemptInvoiceProcessing', () => {357 let invoice;358 let customer;359 beforeEach(() => {360 invoice = deepCopy(unpaidInvoice);361 invoice.customer = customer = deepCopy(customer1);362 });363 it('makes an attempt', async () => {364 mockPaypalHelper.searchTransactions = sandbox.fake.resolves([]);365 processor.ensureAccurateAttemptCount = sandbox.fake.resolves({});366 processor.handlePaidTransaction = sandbox.fake.resolves(false);367 processor.handlePendingTransaction = sandbox.fake.resolves(false);368 processor.inGracePeriod = sandbox.fake.returns(true);369 mockStripeHelper.getCustomerPaypalAgreement =370 sandbox.fake.returns('b-1234');371 processor.attemptsToday = sandbox.fake.returns(0);372 processor.makePaymentAttempt = sandbox.fake.resolves({});373 const result = await processor.attemptInvoiceProcessing(invoice);374 assert.isUndefined(result);375 sinon.assert.callCount(mockPaypalHelper.searchTransactions, 1);376 for (const spy of [377 processor.ensureAccurateAttemptCount,378 processor.handlePaidTransaction,379 processor.handlePendingTransaction,380 ]) {381 sinon.assert.calledOnceWithExactly(spy, invoice, []);382 }383 sinon.assert.calledOnceWithExactly(processor.inGracePeriod, invoice);384 sinon.assert.calledOnceWithExactly(385 mockStripeHelper.getCustomerPaypalAgreement,386 invoice.customer387 );388 sinon.assert.calledOnceWithExactly(processor.attemptsToday, []);389 sinon.assert.calledOnceWithExactly(processor.makePaymentAttempt, invoice);390 });391 it('errors with no customer loaded', async () => {392 invoice.customer = 'cust_1232142';393 mockLog.error = sandbox.fake.returns({});394 try {395 await processor.attemptInvoiceProcessing(invoice);396 assert.fail('Expected to throw an error without a customer loaded.');397 } catch (err) {398 assert.deepEqual(399 err,400 error.internalValidationError('customerNotLoad', {401 customer: 'cust_1232142',402 invoiceId: invoice.id,403 })404 );405 sinon.assert.calledOnceWithExactly(mockLog.error, 'customerNotLoaded', {406 customer: 'cust_1232142',407 });408 }409 });410 it('stops with a pending transaction', async () => {411 mockPaypalHelper.searchTransactions = sandbox.fake.resolves([]);412 processor.ensureAccurateAttemptCount = sandbox.fake.resolves({});413 processor.handlePaidTransaction = sandbox.fake.resolves(false);414 processor.handlePendingTransaction = sandbox.fake.resolves(true);415 processor.inGracePeriod = sandbox.fake.returns(true);416 const result = await processor.attemptInvoiceProcessing(invoice);417 assert.isUndefined(result);418 sinon.assert.callCount(mockPaypalHelper.searchTransactions, 1);419 for (const spy of [420 processor.ensureAccurateAttemptCount,421 processor.handlePaidTransaction,422 processor.handlePendingTransaction,423 ]) {424 sinon.assert.calledOnceWithExactly(spy, invoice, []);425 }426 sinon.assert.notCalled(processor.inGracePeriod);427 });428 it('stops with a completed transaction', async () => {429 mockPaypalHelper.searchTransactions = sandbox.fake.resolves([]);430 processor.ensureAccurateAttemptCount = sandbox.fake.resolves({});431 processor.handlePaidTransaction = sandbox.fake.resolves(true);432 processor.handlePendingTransaction = sandbox.fake.resolves(false);433 const result = await processor.attemptInvoiceProcessing(invoice);434 assert.isUndefined(result);435 sinon.assert.callCount(mockPaypalHelper.searchTransactions, 1);436 for (const spy of [437 processor.ensureAccurateAttemptCount,438 processor.handlePaidTransaction,439 ]) {440 sinon.assert.calledOnceWithExactly(spy, invoice, []);441 }442 sinon.assert.notCalled(processor.handlePendingTransaction);443 });444 it('stops if no billing agreement', async () => {445 mockPaypalHelper.searchTransactions = sandbox.fake.resolves([]);446 processor.ensureAccurateAttemptCount = sandbox.fake.resolves({});447 processor.handlePaidTransaction = sandbox.fake.resolves(false);448 processor.handlePendingTransaction = sandbox.fake.resolves(false);449 processor.inGracePeriod = sandbox.fake.returns(true);450 mockStripeHelper.getCustomerPaypalAgreement =451 sandbox.fake.returns(undefined);452 processor.attemptsToday = sandbox.fake.returns(0);453 mockStripeHelper.getEmailTypes = sandbox.fake.returns(['paymentFailed']);454 mockHandler.sendSubscriptionPaymentFailedEmail = sandbox.fake.resolves(455 {}456 );457 const result = await processor.attemptInvoiceProcessing(invoice);458 assert.isUndefined(result);459 sinon.assert.callCount(mockPaypalHelper.searchTransactions, 1);460 for (const spy of [461 processor.ensureAccurateAttemptCount,462 processor.handlePaidTransaction,463 processor.handlePendingTransaction,464 ]) {465 sinon.assert.calledOnceWithExactly(spy, invoice, []);466 }467 sinon.assert.calledOnceWithExactly(processor.inGracePeriod, invoice);468 sinon.assert.calledOnceWithExactly(469 mockStripeHelper.getCustomerPaypalAgreement,470 invoice.customer471 );472 // We do not send an email since `getEmailTypes` is returning a list with473 // 'paymentFailed'.474 sinon.assert.notCalled(mockHandler.sendSubscriptionPaymentFailedEmail);475 sinon.assert.notCalled(processor.attemptsToday);476 });477 it('voids invoices for deleted customers', async () => {478 mockStripeHelper.markUncollectible = sandbox.fake.resolves({});479 mockLog.info = sandbox.fake.returns({});480 customer.deleted = true;481 const result = await processor.attemptInvoiceProcessing(invoice);482 assert.isUndefined(result);483 sinon.assert.calledOnceWithExactly(mockLog.info, 'customerDeletedVoid', {484 customerId: customer.id,485 });486 });487 it('cancels if outside the grace period', async () => {488 mockPaypalHelper.searchTransactions = sandbox.fake.resolves([]);489 processor.ensureAccurateAttemptCount = sandbox.fake.resolves({});490 processor.handlePaidTransaction = sandbox.fake.resolves(false);491 processor.handlePendingTransaction = sandbox.fake.resolves(false);492 processor.inGracePeriod = sandbox.fake.returns(false);493 mockStripeHelper.getCustomerPaypalAgreement =494 sandbox.fake.returns('b-1234');495 processor.cancelInvoiceSubscription = sandbox.fake.resolves({});496 const result = await processor.attemptInvoiceProcessing(invoice);497 assert.deepEqual(result, {});498 sinon.assert.callCount(mockPaypalHelper.searchTransactions, 1);499 for (const spy of [500 processor.ensureAccurateAttemptCount,501 processor.handlePaidTransaction,502 processor.handlePendingTransaction,503 ]) {504 sinon.assert.calledOnceWithExactly(spy, invoice, []);505 }506 sinon.assert.calledOnceWithExactly(processor.inGracePeriod, invoice);507 sinon.assert.notCalled(mockStripeHelper.getCustomerPaypalAgreement);508 sinon.assert.calledOnceWithExactly(509 processor.cancelInvoiceSubscription,510 invoice511 );512 });513 it('does not attempt payment after too many attempts', async () => {514 mockPaypalHelper.searchTransactions = sandbox.fake.resolves([]);515 processor.ensureAccurateAttemptCount = sandbox.fake.resolves({});516 processor.handlePaidTransaction = sandbox.fake.resolves(false);517 processor.handlePendingTransaction = sandbox.fake.resolves(false);518 processor.inGracePeriod = sandbox.fake.returns(true);519 mockStripeHelper.getCustomerPaypalAgreement =520 sandbox.fake.returns('b-1234');521 processor.attemptsToday = sandbox.fake.returns(20);522 processor.makePaymentAttempt = sandbox.fake.resolves({});523 const result = await processor.attemptInvoiceProcessing(invoice);524 assert.isUndefined(result);525 sinon.assert.callCount(mockPaypalHelper.searchTransactions, 1);526 for (const spy of [527 processor.ensureAccurateAttemptCount,528 processor.handlePaidTransaction,529 processor.handlePendingTransaction,530 ]) {531 sinon.assert.calledOnceWithExactly(spy, invoice, []);532 }533 sinon.assert.calledOnceWithExactly(processor.inGracePeriod, invoice);534 sinon.assert.calledOnceWithExactly(535 mockStripeHelper.getCustomerPaypalAgreement,536 invoice.customer537 );538 sinon.assert.calledOnceWithExactly(processor.attemptsToday, []);539 sinon.assert.notCalled(processor.makePaymentAttempt);540 });541 });542 describe('processInvoices', () => {543 it('processes an invoice', async () => {544 const invoice = deepCopy(unpaidInvoice);545 mockLog.error = sandbox.fake.returns({});546 mockLog.info = sandbox.fake.returns({});547 processor.attemptInvoiceProcessing = sandbox.fake.resolves({});548 mockStripeHelper.fetchOpenInvoices = sandbox.fake.returns({549 *[Symbol.asyncIterator]() {550 yield invoice;551 },552 });553 // eslint-disable-next-line554 for await (const _ of processor.processInvoices()) {555 // No value yield'd; yielding control for potential distributed lock556 // extension in actual use case557 }558 sinon.assert.calledOnceWithExactly(559 mockLog.info,560 'processInvoice.processing',561 {562 invoiceId: invoice.id,563 }564 );565 sinon.assert.notCalled(mockLog.error);566 });567 it('logs an error on invoice exception', async () => {568 const invoice = deepCopy(unpaidInvoice);569 mockLog.error = sandbox.fake.returns({});570 mockLog.info = sandbox.fake.returns({});571 const throwErr = new Error('Test');572 processor.attemptInvoiceProcessing = sandbox.fake.rejects(throwErr);573 mockStripeHelper.fetchOpenInvoices = sandbox.fake.returns({574 *[Symbol.asyncIterator]() {575 yield invoice;576 },577 });578 try {579 // eslint-disable-next-line580 for await (const _ of processor.processInvoices()) {581 // No value yield'd; yielding control for potential distributed lock582 // extension in actual use case583 }584 assert.fail('Process invoicce should fail');585 } catch (err) {586 sinon.assert.calledOnceWithExactly(587 mockLog.info,588 'processInvoice.processing',589 {590 invoiceId: invoice.id,591 }592 );593 sinon.assert.calledOnceWithExactly(mockLog.error, 'processInvoice', {594 err: throwErr,595 nvpData: undefined,596 invoiceId: invoice.id,597 });598 }599 });600 });601 describe('sendFailedPaymentEmail', () => {602 it('sends an email when paymentFailed is not in the list of sent emails', async () => {603 mockStripeHelper.getEmailTypes = sandbox.fake.returns([]);604 mockHandler.sendSubscriptionPaymentFailedEmail = sandbox.fake.resolves(605 {}606 );607 await processor.sendFailedPaymentEmail(unpaidInvoice);608 sinon.assert.calledOnce(mockHandler.sendSubscriptionPaymentFailedEmail);609 });610 it('does not send an email when paymentFailed is in the list of sent emails', async () => {611 mockStripeHelper.getEmailTypes = sandbox.fake.returns([612 'a',613 'b',614 'paymentFailed',615 ]);616 mockHandler.sendSubscriptionPaymentFailedEmail = sandbox.fake.resolves(617 {}618 );619 await processor.sendFailedPaymentEmail(unpaidInvoice);620 sinon.assert.notCalled(mockHandler.sendSubscriptionPaymentFailedEmail);621 });622 });...

Full Screen

Full Screen

subscription-reminders.js

Source:subscription-reminders.js Github

copy

Full Screen

...91 describe('getEligiblePlans', () => {92 it('returns [] when no plans are eligible', async () => {93 const shortPlan2 = deepCopy(shortPlan1);94 shortPlan2.interval = 'week';95 mockStripeHelper.allAbbrevPlans = sandbox.fake.resolves([96 shortPlan1,97 shortPlan2,98 ]);99 const result = await reminder.getEligiblePlans();100 assert.isEmpty(result);101 });102 it('returns a partial list when some plans are eligible', async () => {103 mockStripeHelper.allAbbrevPlans = sandbox.fake.resolves([104 shortPlan1,105 longPlan1,106 longPlan2,107 ]);108 const expected = [longPlan1, longPlan2];109 const actual = await reminder.getEligiblePlans();110 assert.deepEqual(actual, expected);111 });112 it('returns all when all plans are eligible', async () => {113 mockStripeHelper.allAbbrevPlans = sandbox.fake.resolves([114 longPlan1,115 longPlan2,116 ]);117 const expected = [longPlan1, longPlan2];118 const actual = await reminder.getEligiblePlans();119 assert.deepEqual(actual, expected);120 });121 });122 describe('getStartAndEndTimes', () => {123 it('returns a time period of 1 day reminderLength days from "now" in UTC', () => {124 const realDateTimeUtc = DateTime.utc.bind(DateTime);125 DateTime.utc = sinon.fake(() =>126 DateTime.fromMillis(MOCK_DATETIME_MS, { zone: 'utc' })127 );128 const expected = MOCK_INTERVAL;129 const actual = reminder.getStartAndEndTimes();130 const actualStartS = actual.start.toSeconds();131 const actualEndS = actual.end.toSeconds();132 assert.equal(actualStartS, expected.start.toSeconds());133 assert.equal(actualEndS, expected.end.toSeconds());134 assert.equal(actualEndS - actualStartS, S_IN_A_DAY);135 DateTime.utc = realDateTimeUtc;136 });137 });138 describe('alreadySentEmail', () => {139 const args = ['uid', 12345, { subscriptionId: 'sub_123' }];140 const sentEmailArgs = ['uid', EMAIL_TYPE, { subscriptionId: 'sub_123' }];141 it('returns true for email already sent for this cycle', async () => {142 SentEmail.findLatestSentEmailByType = sandbox.fake.resolves({143 sentAt: 12346,144 });145 const result = await reminder.alreadySentEmail(...args);146 assert.isTrue(result);147 sinon.assert.calledOnceWithExactly(148 SentEmail.findLatestSentEmailByType,149 ...sentEmailArgs150 );151 });152 it('returns false for email that has not been sent during this billing cycle', async () => {153 SentEmail.findLatestSentEmailByType = sandbox.fake.resolves({154 sentAt: 12344,155 });156 const result = await reminder.alreadySentEmail(...args);157 assert.isFalse(result);158 sinon.assert.calledOnceWithExactly(159 SentEmail.findLatestSentEmailByType,160 ...sentEmailArgs161 );162 });163 it('returns false for email that has never been sent', async () => {164 SentEmail.findLatestSentEmailByType = sandbox.fake.resolves(undefined);165 const result = await reminder.alreadySentEmail(...args);166 assert.isFalse(result);167 sinon.assert.calledOnceWithExactly(168 SentEmail.findLatestSentEmailByType,169 ...sentEmailArgs170 );171 });172 });173 describe('updateSentEmail', () => {174 it('creates a record in the SentEmails table', async () => {175 const sentEmailArgs = ['uid', EMAIL_TYPE, { subscriptionId: 'sub_123' }];176 SentEmail.createSentEmail = sandbox.fake.resolves({});177 await reminder.updateSentEmail('uid', { subscriptionId: 'sub_123' });178 sinon.assert.calledOnceWithExactly(179 SentEmail.createSentEmail,180 ...sentEmailArgs181 );182 });183 });184 describe('sendSubscriptionRenewalReminderEmail', () => {185 it('logs an error and returns false if customer uid is not provided', async () => {186 const subscription = deepCopy(longSubscription1);187 subscription.customer = {188 metadata: {189 userid: null,190 },191 };192 mockLog.error = sandbox.fake.returns({});193 const result = await reminder.sendSubscriptionRenewalReminderEmail(194 subscription195 );196 assert.isFalse(result);197 sinon.assert.calledOnceWithExactly(198 mockLog.error,199 'sendSubscriptionRenewalReminderEmail',200 {201 customer: subscription.customer,202 subscriptionId: subscription.id,203 }204 );205 });206 it('returns false if email already sent', async () => {207 const subscription = deepCopy(longSubscription1);208 subscription.customer = {209 email: 'abc@123.com',210 metadata: {211 userid: 'uid',212 },213 };214 reminder.alreadySentEmail = sandbox.fake.resolves(true);215 const result = await reminder.sendSubscriptionRenewalReminderEmail(216 subscription,217 longPlan1.id218 );219 assert.isFalse(result);220 sinon.assert.calledOnceWithExactly(221 reminder.alreadySentEmail,222 subscription.customer.metadata.userid,223 Math.floor(subscription.current_period_start * 1000),224 {225 subscriptionId: subscription.id,226 }227 );228 });229 it('returns true if it sends a reminder email', async () => {230 const subscription = deepCopy(longSubscription1);231 subscription.customer = {232 email: 'abc@123.com',233 metadata: {234 userid: 'uid',235 },236 };237 reminder.alreadySentEmail = sandbox.fake.resolves(false);238 const account = {239 emails: [],240 email: 'testo@test.test',241 locale: 'NZ',242 };243 reminder.db.account = sandbox.fake.resolves(account);244 mockLog.info = sandbox.fake.returns({});245 const formattedSubscription = {246 id: 'subscriptionId',247 productMetadata: {248 privacyUrl: 'http://privacy',249 termsOfServiceUrl: 'http://tos',250 },251 };252 mockStripeHelper.formatSubscriptionForEmail = sandbox.fake.resolves(formattedSubscription);253 mockStripeHelper.findPlanById = sandbox.fake.resolves({254 amount: longPlan1.amount,255 currency: longPlan1.currency,256 interval_count: longPlan1.interval_count,257 interval: longPlan1.interval,258 });259 reminder.mailer.sendSubscriptionRenewalReminderEmail =260 sandbox.fake.resolves(true);261 reminder.updateSentEmail = sandbox.fake.resolves({});262 const realDateNow = Date.now.bind(global.Date);263 Date.now = sinon.fake(() => MOCK_DATETIME_MS);264 const result = await reminder.sendSubscriptionRenewalReminderEmail(265 subscription,266 longPlan1.id267 );268 assert.isTrue(result);269 sinon.assert.calledOnceWithExactly(270 reminder.db.account,271 subscription.customer.metadata.userid272 );273 sinon.assert.calledOnceWithExactly(274 mockStripeHelper.formatSubscriptionForEmail,275 subscription276 );277 sinon.assert.calledOnceWithExactly(278 mockStripeHelper.findPlanById,279 longPlan1.id280 );281 sinon.assert.calledOnceWithExactly(282 mockLog.info,283 'sendSubscriptionRenewalReminderEmail',284 {285 message: 'Sending a renewal reminder email.',286 subscriptionId: subscription.id,287 currentPeriodStart: subscription.current_period_start,288 currentPeriodEnd: subscription.current_period_end,289 currentDateMs: Date.now(),290 }291 );292 sinon.assert.calledOnceWithExactly(293 reminder.mailer.sendSubscriptionRenewalReminderEmail,294 account.emails,295 account,296 {297 acceptLanguage: account.locale,298 uid: 'uid',299 email: 'testo@test.test',300 subscription: formattedSubscription,301 reminderLength: 14,302 planIntervalCount: 1,303 planInterval: 'month',304 invoiceTotalInCents: 499,305 invoiceTotalCurrency: 'usd',306 productMetadata: formattedSubscription.productMetadata,307 }308 );309 sinon.assert.calledOnceWithExactly(310 reminder.updateSentEmail,311 subscription.customer.metadata.userid,312 { subscriptionId: subscription.id }313 );314 Date.now = realDateNow;315 });316 it('returns false if an error is caught when trying to send a reminder email', async () => {317 const subscription = deepCopy(longSubscription1);318 subscription.customer = {319 email: 'abc@123.com',320 metadata: {321 userid: 'uid',322 },323 };324 reminder.alreadySentEmail = sandbox.fake.resolves(false);325 reminder.db.account = sandbox.fake.resolves({});326 reminder.updateSentEmail = sandbox.fake.resolves({});327 mockStripeHelper.formatSubscriptionForEmail = sandbox.fake.resolves({});328 mockStripeHelper.findPlanById = sandbox.fake.resolves({329 amount: longPlan1.amount,330 currency: longPlan1.currency,331 interval_count: longPlan1.interval_count,332 interval: longPlan1.interval,333 });334 mockLog.info = sandbox.fake.returns({});335 mockLog.error = sandbox.fake.returns({});336 const errMessage = 'Something went wrong.';337 const throwErr = new Error(errMessage);338 reminder.mailer.sendSubscriptionRenewalReminderEmail =339 sandbox.fake.rejects(throwErr);340 const result = await reminder.sendSubscriptionRenewalReminderEmail(341 subscription,342 longPlan1.id343 );344 assert.isFalse(result);345 sinon.assert.calledOnceWithExactly(346 reminder.db.account,347 subscription.customer.metadata.userid348 );349 sinon.assert.calledOnceWithExactly(350 mockStripeHelper.formatSubscriptionForEmail,351 subscription352 );353 sinon.assert.calledOnceWithExactly(354 mockStripeHelper.findPlanById,355 longPlan1.id356 );357 sinon.assert.calledOnceWithExactly(358 mockLog.error,359 'sendSubscriptionRenewalReminderEmail',360 {361 err: throwErr,362 subscriptionId: subscription.id,363 }364 );365 sinon.assert.notCalled(reminder.updateSentEmail);366 });367 });368 describe('sendReminders', () => {369 beforeEach(() => {370 reminder.getEligiblePlans = sandbox.fake.resolves([longPlan1, longPlan2]);371 reminder.getStartAndEndTimes = sandbox.fake.returns(MOCK_INTERVAL);372 async function* genSubscriptionForPlan1() {373 yield longSubscription1;374 }375 async function* genSubscriptionForPlan2() {376 yield longSubscription2;377 }378 const stub = sandbox.stub(379 mockStripeHelper,380 'findActiveSubscriptionsByPlanId'381 );382 stub.onFirstCall().callsFake(genSubscriptionForPlan1);383 stub.onSecondCall().callsFake(genSubscriptionForPlan2);384 });385 it('returns true if it can process all eligible subscriptions', async () => {386 reminder.sendSubscriptionRenewalReminderEmail = sandbox.fake.resolves({});387 const result = await reminder.sendReminders();388 assert.isTrue(result);389 sinon.assert.calledOnce(reminder.getEligiblePlans);390 sinon.assert.calledOnceWithExactly(reminder.getStartAndEndTimes);391 // We iterate through each plan, longPlan1 and longPlan2, and there is one392 // subscription, longSubscription1 and longSubscription2 respectively,393 // returned for each plan.394 sinon.assert.calledTwice(395 mockStripeHelper.findActiveSubscriptionsByPlanId396 );397 sinon.assert.calledTwice(reminder.sendSubscriptionRenewalReminderEmail);398 });399 it('returns false and logs an error for any eligible subscription that it fails to process', async () => {400 mockLog.error = sandbox.fake.returns({});...

Full Screen

Full Screen

stopMessaging.test.js

Source:stopMessaging.test.js Github

copy

Full Screen

...25 store.clearActions();26 });27 it('updateStopMessage should call api once', async () => {28 // given29 const fakeApi = sandbox.fake.resolves();30 const fakeMethod = sandbox.stub(stopMessagingApi, 'updateStopMessage').callsFake(fakeApi);31 const payload = {32 startTime: moment(),33 endTime: moment(),34 };35 // when36 await store.dispatch(updateStopMessage(payload, '123', null));37 // then38 sandbox.assert.calledOnce(fakeMethod);39 });40 it('when recurrence updateStopMessage should call api once per day', async () => {41 // given42 const fakeApi = sandbox.fake.resolves();43 const fakeMethod = sandbox.stub(stopMessagingApi, 'updateStopMessage').callsFake(fakeApi);44 const startTime = moment().add(2, 'w').weekday(0);45 const payload = {46 startTime,47 endTime: startTime.clone(),48 };49 const days = [WEEK_DAYS.Wednesday, WEEK_DAYS.Friday];50 const recurrence = {51 weeks: 1,52 days,53 };54 // when55 await store.dispatch(updateStopMessage(payload, '123', recurrence));56 // then57 sandbox.assert.callCount(fakeMethod, days.length);58 });59 it('when recurrence updateStopMessage should send different dates for each day', async () => {60 // given61 const fakeApi = sandbox.fake.resolves();62 const fakeMethod = sandbox.stub(stopMessagingApi, 'updateStopMessage').callsFake(fakeApi);63 const date = moment().add(2, 'w').weekday(0);64 const payload = {65 startTime: date,66 endTime: date.clone(),67 };68 const days = [WEEK_DAYS.Monday, WEEK_DAYS.Wednesday, WEEK_DAYS.Thursday, WEEK_DAYS.Saturday];69 const recurrence = {70 weeks: 1,71 days,72 };73 // when74 await store.dispatch(updateStopMessage(payload, '123', recurrence));75 // then76 days.forEach((day, index) => {77 const expectedDate = date.clone().weekday(day);78 const callArguments = fakeMethod.getCall(index).args[0];79 expect(callArguments.startTime.toJSON()).to.eql(expectedDate.toJSON());80 expect(callArguments.endTime.toJSON()).to.eql(expectedDate.toJSON());81 });82 });83 it('when recurrence updateStopMessage should call api once per day per week', async () => {84 // given85 const fakeApi = sandbox.fake.resolves();86 const fakeMethod = sandbox.stub(stopMessagingApi, 'updateStopMessage').callsFake(fakeApi);87 const date = moment().add(2, 'w').weekday(0);88 const payload = {89 startTime: date,90 endTime: date.clone(),91 };92 const weeks = 3;93 const days = [WEEK_DAYS.Tuesday, WEEK_DAYS.Thursday];94 const recurrence = {95 weeks,96 days,97 };98 // when99 await store.dispatch(updateStopMessage(payload, '123', recurrence));100 // then101 sandbox.assert.callCount(fakeMethod, weeks * days.length);102 });103 it('when recurrence updateStopMessage should send different dates for each day of each week', async () => {104 // given105 const fakeApi = sandbox.fake.resolves();106 const fakeMethod = sandbox.stub(stopMessagingApi, 'updateStopMessage').callsFake(fakeApi);107 const date = moment().add(2, 'w').weekday(0);108 const payload = {109 startTime: date,110 endTime: date,111 };112 const weeks = 3;113 const days = [WEEK_DAYS.Monday, WEEK_DAYS.Wednesday, WEEK_DAYS.Thursday, WEEK_DAYS.Saturday];114 const recurrence = {115 weeks,116 days,117 };118 // when119 await store.dispatch(updateStopMessage(payload, '123', recurrence));120 // then121 for (let i = 1; i < weeks; i++) {122 const week = i - 1;123 const expectedDate = date.clone().add(week, 'w');124 days.forEach((day, index) => {125 expectedDate.weekday(day);126 const callArguments = fakeMethod.getCall(index + (week * days.length)).args[0];127 expect(callArguments.startTime.toJSON()).to.eql(expectedDate.toJSON());128 expect(callArguments.endTime.toJSON()).to.eql(expectedDate.toJSON());129 });130 }131 });132 it('when recurrence updateStopMessage should skip dates that are before the event start date', async () => {133 // given134 const fakeApi = sandbox.fake.resolves();135 const fakeMethod = sandbox.stub(stopMessagingApi, 'updateStopMessage').callsFake(fakeApi);136 const date = moment().add(2, 'w').weekday(4);137 const payload = {138 startTime: date,139 endTime: date,140 };141 const weeks = 1;142 const days = [WEEK_DAYS.Monday, WEEK_DAYS.Wednesday, WEEK_DAYS.Thursday, WEEK_DAYS.Saturday];143 const recurrence = {144 weeks,145 days,146 };147 // when148 await store.dispatch(updateStopMessage(payload, '123', recurrence));...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const sinon = require('sinon');2const sandbox = sinon.createSandbox();3const chai = require('chai');4const expect = chai.expect;5describe('test', function() {6 it('test', function() {7 const stub = sandbox.fake.resolves('test');8 expect(stub()).to.eventually.equal('test');9 });10});11const sinon = require('sinon');12const sandbox = sinon.createSandbox();13const chai = require('chai');14const expect = chai.expect;15describe('test', function() {16 it('test', function() {17 const stub = sandbox.stub().resolves('test');18 expect(stub()).to.eventually.equal('test');19 });20});

Full Screen

Using AI Code Generation

copy

Full Screen

1import {expect} from 'chai';2import sinon from 'sinon';3import {foo} from './foo';4describe('foo', () => {5 it('should call the callback', () => {6 const callback = sinon.fake.resolves();7 foo(callback);8 expect(callback.called).to.be.true;9 });10});11export function foo(callback) {12 callback();13}14{15 "scripts": {16 },17 "devDependencies": {18 }19}

Full Screen

Using AI Code Generation

copy

Full Screen

1const sandbox = sinon.createSandbox();2const fake = sandbox.fake.resolves('hello');3fake().then((result) => {4 console.log(result);5});6sandbox.restore();7const sandbox = sinon.createSandbox();8const fake = sandbox.fake.rejects('hello');9fake().catch((result) => {10 console.log(result);11});12sandbox.restore();13const sandbox = sinon.createSandbox();14const fake = sandbox.fake.throws('hello');15fake().catch((result) => {16 console.log(result);17});18sandbox.restore();19const sandbox = sinon.createSandbox();20const fake = sandbox.fake.yields('hello');21fake((result) => {22 console.log(result);23});24sandbox.restore();25const sandbox = sinon.createSandbox();26const fake = sandbox.fake.yieldsTo('hello');27fake((result) => {28 console.log(result);29});30sandbox.restore();31const sandbox = sinon.createSandbox();32const fake = sandbox.fake.yieldsOn('hello');33fake((result) => {34 console.log(result);35});36sandbox.restore();37const sandbox = sinon.createSandbox();38const fake = sandbox.fake.yieldsRight('hello');39fake((result) => {40 console.log(result);41});42sandbox.restore();43const sandbox = sinon.createSandbox();44const fake = sandbox.fake.yieldsToOn('hello');45fake((result) => {46 console.log(result);47});48sandbox.restore();49const sandbox = sinon.createSandbox();50const fake = sandbox.fake.yieldsToRight('hello');51fake((result) => {52 console.log(result);53});54sandbox.restore();55const sandbox = sinon.createSandbox();56const fake = sandbox.fake.yieldsToAsync('

Full Screen

Using AI Code Generation

copy

Full Screen

1var sinon = require('sinon');2var sandbox = sinon.sandbox.create();3var test = sandbox.fake.resolves("Hello World");4test.then(function(data){5 console.log(data);6});7var sinon = require('sinon');8var sandbox = sinon.sandbox.create();9var test = sandbox.fake.rejects("Hello World");10test.catch(function(data){11 console.log(data);12});13Recommended Posts: Sinon.js | sinon.fake()14Sinon.js | sinon.fake.returns()15Sinon.js | sinon.fake.yields()16Sinon.js | sinon.fake.yieldsTo()17Sinon.js | sinon.fakeServer()18Sinon.js | sinon.fakeServerWithClock()19Sinon.js | sinon.fakeServer.xhr()20Sinon.js | sinon.stub()21Sinon.js | sinon.spy()22Sinon.js | sinon.match()23Sinon.js | sinon.match.any()24Sinon.js | sinon.match.defined()25Sinon.js | sinon.match.truthy()26Sinon.js | sinon.match.falsy()27Sinon.js | sinon.match.bool()28Sinon.js | sinon.match.number()29Sinon.js | sinon.match.string()30Sinon.js | sinon.match.object()31Sinon.js | sinon.match.same()

Full Screen

Using AI Code Generation

copy

Full Screen

1const sandbox = sinon.sandbox.create();2const fake = sandbox.fake.resolves("fake result");3const fake2 = sandbox.fake.rejects("fake error");4const fake3 = sandbox.fake.throws("fake exception");5const fake4 = sandbox.fake.yields("fake yield");6const fake5 = sandbox.fake.yieldsTo("fake yield to");7const fake6 = sandbox.fake.callsFake(() => "fake call");8const fake7 = sandbox.fake.returns("fake return");9const fake8 = sandbox.fake.returnsArg(0);10const fake9 = sandbox.fake.returnsThis();11const fake10 = sandbox.fake.returnsThis();12const fake11 = sandbox.fake.returnsThis();13const fake12 = sandbox.fake.returnsThis();14const fake13 = sandbox.fake.returnsThis();15const fake14 = sandbox.fake.returnsThis();16const fake15 = sandbox.fake.returnsThis();17const fake16 = sandbox.fake.returnsThis();18const fake17 = sandbox.fake.returnsThis();19const fake18 = sandbox.fake.returnsThis();20const fake19 = sandbox.fake.returnsThis();21const fake20 = sandbox.fake.returnsThis();22const fake21 = sandbox.fake.returnsThis();23const fake22 = sandbox.fake.returnsThis();24const fake23 = sandbox.fake.returnsThis();25const fake24 = sandbox.fake.returnsThis();26const fake25 = sandbox.fake.returnsThis();27const fake26 = sandbox.fake.returnsThis();28const fake27 = sandbox.fake.returnsThis();29const fake28 = sandbox.fake.returnsThis();30const fake29 = sandbox.fake.returnsThis();31const fake30 = sandbox.fake.returnsThis();32const fake31 = sandbox.fake.returnsThis();33const fake32 = sandbox.fake.returnsThis();34const fake33 = sandbox.fake.returnsThis();35const fake34 = sandbox.fake.returnsThis();36const fake35 = sandbox.fake.returnsThis();37const fake36 = sandbox.fake.returnsThis();38const fake37 = sandbox.fake.returnsThis();39const fake38 = sandbox.fake.returnsThis();40const fake39 = sandbox.fake.returnsThis();41const fake40 = sandbox.fake.returnsThis();42const fake41 = sandbox.fake.returnsThis();43const fake42 = sandbox.fake.returnsThis();44const fake43 = sandbox.fake.returnsThis();45const fake44 = sandbox.fake.returnsThis();46const fake45 = sandbox.fake.returnsThis();47const fake46 = sandbox.fake.returnsThis();48const fake47 = sandbox.fake.returnsThis();

Full Screen

Using AI Code Generation

copy

Full Screen

1const sandbox = sinon.sandbox.create();2const fake = sandbox.fake.resolves('success');3fake().then(console.log);4const sandbox = sinon.sandbox.create();5const fake = sandbox.fake.rejects('error');6fake().catch(console.log);7const sandbox = sinon.sandbox.create();8const fake = sandbox.fake.throws('error');9fake().catch(console.log);10const sandbox = sinon.sandbox.create();11const fake = sandbox.fake.yields('error');12fake().catch(console.log);13const sandbox = sinon.sandbox.create();14const fake = sandbox.fake.yieldsOn('error');15fake().catch(console.log);16const sandbox = sinon.sandbox.create();17const fake = sandbox.fake.yieldsTo('error');18fake().catch(console.log);19const sandbox = sinon.sandbox.create();20const fake = sandbox.fake.yieldsToOn('error');21fake().catch(console.log);22const sandbox = sinon.sandbox.create();23const fake = sandbox.fake.returnsArg('error');24fake().catch(console.log);25const sandbox = sinon.sandbox.create();26const fake = sandbox.fake.returnsThis('error');27fake().catch(console.log);28const sandbox = sinon.sandbox.create();29const fake = sandbox.fake.throwsArg('error');30fake().catch(console.log);31const sandbox = sinon.sandbox.create();32const fake = sandbox.fake.returns('error');33fake().catch(console.log);

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run sinon automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful