【问题标题】:How to mock nested object methods in Jest?如何在 Jest 中模拟嵌套对象方法?
【发布时间】:2022-01-21 14:29:33
【问题描述】:

我不是 100% 确定我的术语就在这里,但我想做的是如下。 我通过创建这样的手动模拟成功地模拟了 stripe.customers.create:

__mocks__/stripe.js 

class Stripe {}
const stripe = jest.fn(() => new Stripe()); 
module.exports = stripe;
module.exports.Stripe = Stripe;

然后在我的 unit.test.js 中我像这样导入模拟

const { Stripe } = require("stripe");
Stripe.prototype.customers = {
  create: jest.fn(() => {
    return {
      id: "cus_testid",
    };
  }),
};

stripe.customers.create() 方法被模拟得很好。然而,当我开始(因为没有更好的词)“嵌套”或“链接”这些方法时,问题就开始了。例如,这个模拟将不起作用:

Stripe.prototype.checkout.sessions = {
  create: jest.fn(() => {
    return {
      session: {
        url: 'someurl'
      }
    }
  })
}

TypeError:无法设置未定义的属性“会话”

为什么我不能设置这样的嵌套方法模拟,我应该如何处理这样的嵌套模拟?我应该修改手动模拟来完成这个吗?

【问题讨论】:

  • 你是如何使用 mocked stripe api 的?
  • 如果你的意思是原始实现,其中 Stripe API 被模拟,然后像这样(我使用 billingPortal 而不是 checkout,因为语法更短): const portalSession = await stripe.billingPortal.sessions .create({ customer: stripeCustomerId, return_url: returnUrl, });

标签: javascript node.js unit-testing jestjs stripe-payments


【解决方案1】:

根据docurl 是 Session 对象的直接属性,因此您应该只返回 {url: 'someUrl' } 而不是将其包装在另一个 session 属性中。

顺便说一句,您可能还对stripe-mock 感兴趣,它是一个模拟 HTTP 服务器,响应类似于真正的 Stripe API。

【讨论】:

  • 但是这里的断点是这样的:“TypeError: Cannot set property 'sessions' of undefined”,即 JS 说“Stripe.prototype.checkout”是未定义的。
猜你喜欢
  • 2021-02-27
  • 1970-01-01
  • 2023-02-15
  • 2020-03-31
  • 1970-01-01
  • 1970-01-01
  • 2017-05-23
  • 1970-01-01
  • 2017-12-20
相关资源
最近更新 更多