Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock stripe with Jest

I'd like to mock the node Stripe SDK in Jest because I don't want to run the mock API server from Stripe but I can't figure how how to do it. I'm creating a __mocks__ directory and adding stripe.js but I can't get anything usable to export.

I typically get TypeError: Cannot read property 'create' of undefined when calling strypegw.charges.create(). I'm using ES6 module syntax so I import stripe from 'stripe'.

like image 827
Jason Leach Avatar asked Apr 04 '19 17:04

Jason Leach


2 Answers

// your-code.js
const stripe = require('stripe')('key');
const customer = await stripe.customers.create({
    ...
});

// __mocks__/stripe.js
class Stripe {}
const stripe = jest.fn(() => new Stripe());

module.exports = stripe;
module.exports.Stripe = Stripe;

// stripe.tests.js
const { Stripe } = require('stripe');
const createCustomerMock = jest.fn(() => ({
    id: 1,
    ...
}));
Stripe.prototype.customers = {
    create: createCustomerMock,
};
like image 71
Sergey Nakhankov Avatar answered Nov 14 '22 03:11

Sergey Nakhankov


Here is a simple solution :

jest.mock("stripe", () => {
  return jest.fn().mockImplementation(function {
    return {
      charges: {
        create: () => "fake stripe response",
      },
    };
  });
});

I found it in jest documentation about ES6 Class Mocks

like image 42
JeromeBu Avatar answered Nov 14 '22 04:11

JeromeBu