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'
.
// 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,
};
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With