shi*_*k01 0 javascript node.js stripe-payments jestjs
我想模拟 stripe api 但不知道该怎么做。我正在使用下面的代码创建会话-
const stripe = require('stripe')('key');
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: 'abs',
images: ['url'],
},
unit_amount: 100,
},
quantity: 1,
},
],
mode: 'payment',
success_url: `${YOUR_DOMAIN}?success=true&session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${YOUR_DOMAIN}?back=true&order_id=${req.clientReferenceId}`,
metadata: req.metadata,
client_reference_id: req.clientReferenceId,
customer_email: req.customerEmail,
billing_address_collection: 'required',
});
Run Code Online (Sandbox Code Playgroud)
我无法在测试文件中导入 stripe,因为它需要 API 密钥。这个怎么做?PS-我尝试按照这个 - Jest 来嘲笑 Stripe,但它对我不起作用。
stripe导出为函数,当你想模拟它时,你可以使用jest.doMockhelper。
想象一下你有一个像这样的index.js:
\nconst stripe = require('stripe')('key'); // You use require('stripe') as a function\n\nexports.CreateSession = async (req) => {\n const session = await stripe.checkout.sessions.create({\n // information to create session\n });\n return session;\n}\n\nRun Code Online (Sandbox Code Playgroud)\n然后,测试文件将是这样的:
\ndescribe('Create session', () => {\n beforeEach(() => {\n jest.resetModules(); // importance line\n });\n\n it('creates the session', async () => {\n const req = {\n unitAmount: 100,\n imageUrl: '',\n metadata: {\n userId: '1'\n }\n };\n\n jest.doMock('stripe', () => {\n // instead of mocking return an object, let\xe2\x80\x99s return a function\n return jest.fn(() => ({ // when the function be called, it return an object like this\n checkout: {\n sessions: {\n create: jest.fn(() => Promise.resolve({\n sessionId: '123' // sessionId instead of id , right?\n })),\n },\n },\n }));\n });\n\n const { CreateSession } = require('./index'); // import function what you need to test\n const resp = await CreateSession(req); // execute with a parameter\n expect(resp.sessionId).toBe('123');\n });\n});\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
2776 次 |
| 最近记录: |