reactjs - 如何测试 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();
});
解决方案
推荐阅读
- vue.js - 使用 vue.js 的单一 spa 共享组件
- javascript - $load tab content from another page to my page仅显示前4张图片
- python - 如果值在使用 Python 的 dialogflow_v2 的数据库中,则将值从数据库传递到对话框流以避免提出必需的问题
- sorting - 有没有办法在 Google Data Studio 表中自定义排序记录?
- r - R data.table:如何正确读取
- javascript - 我的 Discord.js 正在运行,但不会响应命令
- javascript - 尽管代码运行,但箭头功能组件内的挂钩调用无效
- git - 'git add' 基于文件的最后修改日期?
- reactjs - 我如何访问由应用程序在 reactjs 中创建的路由
- python - 将图片嵌入Jupiter notebook,无法获取本地图片/文件的正确路径