Search code examples
unit-testingjestjsmockingstripe-paymentsts-jest

failed mock stripe on lambda function : TypeError: stripe_1.default is not a constructor


i want to mock stripe sdk on lambda function, this is how i create instance of stripe on config

export const stripe = new Stripe(STRIPE_SECRET_KEY, {
  apiVersion: '2020-08-27',
  typescript: true,
  maxNetworkRetries: 2,
});

and this is how i use the stripe instance on my lambda function

import { stripe, STRIPE_TEST_USERS } from '../config';

await stripe.invoices.retrieve(id)

and this is what i got

  TypeError: stripe_1.default is not a constructor

  36 | });
  37 |
> 38 | export const stripe = new Stripe(STRIPE_SECRET_KEY, {
     |                       ^
  39 |   apiVersion: '2020-08-27',
  40 |   typescript: true,
  41 |   maxNetworkRetries: 2,

dont get me wrong , i have tried all thing i can do, i have tried this method

1st

 jest.mock("stripe", () => {
      return jest.fn().mockImplementation(()=> {
        return {
          invoices: {
            retrieve: () =>jest.fn(),
          },
        };
      });
    });

2nd

jest.mock('stripe', () =>
   jest.fn().mockImplementation(() => ({
    invoices: {
      retrieve: () => jest.fn()
   },
  }))
 );

3rd

jest.mock('stripe', () => ({
  ...jest.mock('stripe'),
  Stripe: jest.fn().mockImplementation(() => {
    return {
      invoices: jest.fn().mockImplementation(() => {
        return {
          retrieve: jest.fn(),
        };
      }),
    };
  }),
}));

but none of those work, any solution?


Solution

  • i think you can use this, u need to import module first

    jest.mock("stripe", () => {
     return {
        __esModule: true,
        default: jest.fn().mockImplementation(() => {
          return {
            subscriptions: {
              update: () => updateMock(),
            },
          };
        }),
      };
    });
    

    update is what you want to mock