How to Mock the Stripe API in Node.js with Jest
How to Mock the Stripe API in Node.js with Jest

How to Mock the Stripe API in Node.js with Jest

Spread the love
Mock stripe with Jest
Testing with Jest

Jest is one of the most popular test frameworks used in JavaScript. It is used by developers to automate the CRUD from breaking. The use of third-party services and libraries is a common part of modern projects. It’s easy to test the code written in your project because you have full control over it. But it’s difficult to control the behavior of third-party services and to solve this problem, we mock the third-party service.

Also, as a best practice in testing, you should only be testing your code, not code imported from other places. Ideally, test cases written by the vendor should cover that part. Mocking simply allows you to replace the actual implementation with a fake/fixed set of the desired output. Stripe is one of the popular international payment gateway used by the developer for online payment.

So let’s see how we can mock the Stripe API to test our APIs using Jest.

Below is the code, which shows the actual implementation of the Stripe API in index.js. To know more about the Stripe integration with Node.js, read here.

const stripe = require('stripe')('sk_test_...');
router.post('/create_account', async (req, res) => {
 try {
  const customer = await stripe.customers.create({
   email: req.body.email,
   name: `${req.body.firstName} ${req.body.lastName}`,
   phone: `${req.body.countryCode} ${req.body.phoneNo}`,
   description: 'User Account Created'
  })
  res.send(customer)
 } catch (err) {
  res.status(501).send(err.message)
 }
})

Now let’s mock the Stripe module completely by returning the fixed set of output on each Stripe API implementation.

jest.doMock('stripe', () => {
 return jest.fn(() => ({
  customers: {
   retrieve: jest.fn(() => Promise.resolve({
    id: 'cust_123'
   })),
   create: jest.fn(() => Promise.resolve({
    id: 'cust_123',
    name: "Jest_User",
    currency: "sgd",
    description: "Jest User Account created",
   })),
  },
  coupons: {
   create: jest.fn(() => Promise.resolve({
    id: '7JS8SH'
   })),
  },
  subscriptions: {
   retrieve: jest.fn(() => Promise.resolve({
    id: 'sub_123',
    object: 'subscription',
   })),
   del: jest.fn(() => Promise.resolve({
    id: 'sub_123'
   })),
  },
  checkout: {
   sessions: {
    create: jest.fn(() => Promise.resolve({
     id: '123'
    })),
   },
  },
 }));
});

After mocking the stripe, let’s write the test case into the index.test.js file and check the create account API.

const request = require('supertest');
const app = require('../../app');
const client = request(app);
const urlPrefix = '/';
let token
describe('Create user profile', () => {
 it('should create user profile', async () => {
  const res = await client.post(`${urlPrefix}/create_account`)
   .send({
     email: "testuser@example.com",
     phoneNo: "787840255",
     firstName: "Test",
     lastName: "User",
    })
   expect(res.status).toEqual(200)
 })
})

When you run the above test file you will receive the name of the customer as “Jest_User” instead of “Test User” because you have mocked the Stripe API.

Thanks for reading. If you liked the post, feel free to hit the clap button or leave a comment.

2 Comments

  1. Pingback: Save time by Automated Testing: Jest in Node.js | Noob2Geek

  2. Pingback: Stripe integration With Node.js | Noob2Geek

Leave a Reply

Your email address will not be published.