Mock stripe with Jest

蹲街弑〆低调 提交于 2020-07-08 21:44:31

问题


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'.


回答1:


// 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,
};



回答2:


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



来源:https://stackoverflow.com/questions/55521585/mock-stripe-with-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!