簡體   English   中英

如何在 Jest 中模擬嵌套的 object 方法?

[英]How to mock nested object methods in Jest?

我不是 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:無法設置未定義的屬性“會話”

為什么我不能設置這樣的嵌套方法模擬,我應該如何處理這樣的嵌套模擬? 我應該修改手動模擬來完成這個嗎?

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.

順便說一句,您可能還對stripe-mock感興趣,它是一個模擬 HTTP 服務器,其響應類似於真正的 Stripe API。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM