【问题标题】:Mock stripe with Jest用 Jest 模拟条纹
【发布时间】:2019-08-26 13:01:31
【问题描述】:

我想在 Jest 中模拟节点 Stripe SDK,因为我不想从 Stripe 运行模拟 API 服务器,但我不知道该怎么做。我正在创建一个__mocks__ 目录并添加stripe.js,但我无法获得任何可用于导出的内容。

我通常在拨打strypegw.charges.create() 时收到TypeError: Cannot read property 'create' of undefined。我使用的是 ES6 模块语法,所以我 import stripe from 'stripe'.

【问题讨论】:

标签: node.js jestjs stripe-payments


【解决方案1】:

这是一个简单的解决方案:

jest.mock("stripe", () => {
  return jest.fn().mockImplementation(function {
    return {
      charges: {
        create: () => "fake stripe response",
      },
    };
  });
});

我在关于 ES6 Class Mocks 的笑话文档中找到了它

【讨论】:

  • 这在我测试时实际上不起作用。像const stripe = new Stripe(); 这样调用构造函数时,我一直收到错误消息。 @Sergey 的另一个答案似乎有效。有什么理由会这样吗?
  • 是的,我也一样——谢尔盖的工作。很想回答这个问题
【解决方案2】:
// 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,
};

【讨论】:

  • 谢谢 Sergey。在探​​索了很多之后,这个解决方案对我有用。我试图模拟条带模块但没有运气。这对我来说很好。
  • 对于那些尝试这个但没有运气的人,请确保按照docs,__mocks__ 目录与您的文件相邻
  • 如果我想使用一些嵌套方法,如 stripe.checkout.sessions.create,我应该如何修改 mock?
  • @AleisterCrowley 我想像Stripe.prototype.checkout = { sessions: { create: createSessionMock, } };
【解决方案3】:

将此添加到辅助函数中,并在需要时在 jest 设置文件或测试顶部调用它。

// Mocking Stripe object
  const elementMock = {
    mount: jest.fn(),
    destroy: jest.fn(),
    on: jest.fn(),
    update: jest.fn(),
  };

  const elementsMock = {
    create: jest.fn().mockReturnValue(elementMock),
  };

  const stripeMock = {
    elements: jest.fn().mockReturnValue(elementsMock),
    createToken: jest.fn(() => Promise.resolve()),
    createSource: jest.fn(() => Promise.resolve()),
  };

  // Set the global Stripe
  window.Stripe = jest.fn().mockReturnValue(stripeMock);

使用这种方法,您也可以轻松测试与条带相关的代码

// Ex. of a token successfully created mock
  stripeMock.createToken.mockResolvedValue({
    token: {
      id: 'test_id',
    },
  });

  // Ex. of a failure mock
  stripeMock.createToken.mockResolvedValue({
    error: {
      code: 'incomplete_number',
      message: 'Your card number is incomplete.',
      type: 'validation_error',
    },
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-14
    • 2020-04-21
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多