带有 Jest 的模拟条纹

Jas*_*ach 8 node.js stripe-payments jestjs

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

我通常TypeError: Cannot read property 'create' of undefined在调用strypegw.charges.create(). 我正在使用 ES6 模块语法,所以我import stripe from 'stripe'.

小智 6

// 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,
};
Run Code Online (Sandbox Code Playgroud)


Jer*_*eBu 2

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

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

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