I am not 100% sure my terminology is right here, but what I want to do is as follows. I managed to successfully mock stripe.customers.create by creating a manual mock like this:
__mocks__/stripe.js
class Stripe {}
const stripe = jest.fn(() => new Stripe());
module.exports = stripe;
module.exports.Stripe = Stripe;
then in my unit.test.js I import the mock like this
const { Stripe } = require("stripe");
Stripe.prototype.customers = {
create: jest.fn(() => {
return {
id: "cus_testid",
};
}),
};
And the stripe.customers.create() method is mocked just fine. However, the problem starts when I start to (for the lack of better word) "nest" or "chain" the methods further down the stripe object. For example this mock will not work:
Stripe.prototype.checkout.sessions = {
create: jest.fn(() => {
return {
session: {
url: 'someurl'
}
}
})
}
TypeError: Cannot set property 'sessions' of undefined
Why can't I set up such a nested method mock and how should I approach doing such a nested mock? Should I modify the manual mock to accomplish this?
According to the doc, the url is an immediate property to the Session object, so you should just return {url: 'someUrl' } instead of wrapping it inside another session property.
By the way, you might also be interested in stripe-mock, It's a mock HTTP server that responds like the real Stripe API.