首页 > 解决方案 > 如何测试 Stripe 与 React 测试库的集成。无法渲染卡片元素

问题描述

我正在使用 React 构建一个预订应用程序,以同时学习前端开发和单元测试。我正在努力使用 Jest 和反应测试库为卡注册表编写测试。

我使用 rect-stripe.js 在表单中插入信用卡输入并且它可以工作,(手动测试)但我无法弄清楚如何使用 Jest 和 RTL 对其进行测试。我已经从 Stripe 模拟了 Elements 上下文提供程序并消除了许多错误,但我可以在渲染的 DOM 中看到元素根本不存在。(材质 UI 包装器是而不是条纹元素本身)。我不知道该怎么做——我需要自己模拟元素吗?在这一点上,我真正要测试的是什么?:) 或者,我是否需要使用测试密钥真正连接到 Stripe 并从中获取真实元素以在我的测试中使用?

我也不清楚这里应该采用什么测试策略。我想测试表单验证、错误消息和文本框颜色突出显示,如果没有所有必需的详细信息等,表单将不会提交。我猜与 Stripe 服务器的交互会超出单元/集成测试的范围?

对于新手问题,抱歉,但要尝试理解的内容很多,而且我能找到的信息很少。这是测试的设置和失败的基本测试:

    import React from "react";
import { render } from "@testing-library/react";
import "@testing-library/jest-dom";
import userEvent from "@testing-library/user-event";
import AddCardForm from "./AddCardForm";
import { Elements } from "@stripe/react-stripe-js";
import * as mocks from "../../../testing_assets/Stripe_mocks";

describe("AddCardForm ", () => {
  //TODO this should change as we will try and populate address info from the users profile
  it("should render all fields with correct default values", () => {
    let mockStripe = mocks.mockStripe();
    const { getByLabelText } = render(
      <Elements stripe={mockStripe}>
        <AddCardForm />
      </Elements>
    );
    expect(getByLabelText("Country").value).toBeUndefined();
    expect(getByLabelText("State/Province").value).toBeUndefined();
    expect(getByLabelText("Street").value).toBe("");
    expect(getByLabelText("City").value).toBe("");
    expect(getByLabelText("ZIP/Postal Code").value).toBe("");
    expect(getByLabelText("Email").value).toBe("");
    expect(getByLabelText("Name on card").value).toBe("");
    expect(getByLabelText("Credit Card Number")).toBeInTheDocument();
    expect(getByLabelText("Expiration Date")).toBeInTheDocument();
    expect(getByLabelText("CVC")).toBeInTheDocument();
    expect(getByTestId("submit-addcard")).toBeDisabled();
  });

标签: reactjsunit-testingstripe-payments

解决方案


推荐阅读