Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

280
Views
How to mock nested object methods in Jest?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!