我有一个Textfield组件,它的右侧包含一个单位(p).我在useEffect内动态更改了这个单元和文本值之间的填充,但是当我想使用Cypress的组件测试来确保它正确工作时,我阻止了它.


import classNames from "classnames";
import { IProps } from "./type";
import styles from "./style.module.css";
import { useEffect, useRef } from "react";

const TextField = ({
  ID,
  value,
  placeholder,
  type,
  rounded,
  outline,
  disabled,
  icon,
  unit,
  onChange,
  onFocus,
  onBlur,
}: IProps) => {
  const unitRef = useRef<HTMLParagraphElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // How to test this hook
  useEffect(() => {
    if (unitRef.current && inputRef.current) {
      const unitWidth = unitRef.current.getBoundingClientRect().width;
      inputRef.current.style.paddingRight = `${unitWidth + 20}px`;
    }
  }, [unit]);
  return (
    <div
      className={styles.wrapper}
      data-cy="textfield-wrapper"
    >
      {icon && (
        <div
          className={classNames(styles.icon, {
            [styles.iconPrimary]: type === "primary",
            [styles.iconSecondary]: type === "secondary",
            [styles.iconTernary]: type === "ternary",
          })}
          data-cy="textfield-icon"
        >
          {icon}
        </div>
      )}
      <input
        ref={inputRef}
        id={ID}
        type="text"
        value={value}
        placeholder={placeholder}
        className={classNames(styles.textfield, {
          [styles.primary]: type === "primary",
          [styles.secondary]: type === "secondary",
          [styles.ternary]: type === "ternary",
          [styles.rounded]: rounded,
          [styles.outline]: outline,
          [styles.paddingLeft]: icon,
          [styles.paddingRight]: unit,
        })}
        disabled={disabled}
        onChange={onChange}
        onFocus={onFocus}
        onBlur={onBlur}
      />
      {unit && (
        <p
          ref={inputRef}
          className={classNames(styles.unit, {
            [styles.unitPrimary]: type === "primary",
            [styles.unitSecondary]: type === "secondary",
            [styles.unitTernary]: type === "ternary",
          })}
          data-cy="textfield-unit"
        >
          {unit}
        </p>
      )}
    </div>
  );
};

export default TextField;

``

button.cy.tsx


  it("should adjusts input padding based on unit width", () => {
    const onChange = () => {
      console.log("TextField");
    };
    cy.mount(
      <TextField
        ID="textfield"
        value="credium Textfield"
        onChange={onChange}
        type="primary"
        icon={<IoMdHome />}
        unit="kWh"
        rounded
        outline
      />
    );
    cy.get('[data-cy="textfield-wrapper"]').within(() => {
      // blocked here
      cy.get("input").should("have.css", "padding-right", "???");
    });
  });

推荐答案

应用程序将paddingRight设置为${unitWidth + 20}px,你可以在.should()中重复这一计算.

cy.get("input").should($el => {
  const unitWidth = $el[0].getBoundingClientRect().width
  const expected = `${unitWidth + 20}px`
  const actual = window.getComputedStyle($el[0]).getPropertyValue('padding-right')
  expect(actual).to.eq(expected)
})

即使元素宽度因窗口宽度、灵活布局、媒体查询(移动/平板电脑/桌面)而改变,这也应该会成功.

如果我理解正确的话,您只想知道填充总是宽度+20.


If unitRef is pointing to 100

如果我对unitRef的假设是正确的,我认为测试代码需要调整,即它应该绑定到<p>元素.

如果是这样的话,.should()回调同时需要<input><p>.

cy.get('p').then($p => {
  cy.get('input').should($input => {

    const unitWidth = $p[0].getBoundingClientRect().width
    const expected = `${unitWidth + 20}px`

    const actual = window.getComputedStyle($input[0])
      .getPropertyValue('padding-right')

    expect(actual).to.eq(expected)
  })
})

Reactjs相关问答推荐

react 派生状态未正确更新

通过单击具有此值的按钮将值添加到数组对象键

如何在重新图表中更改悬停时的条形填充 colored颜色 ?

在Reaction常量函数中未更新状态变量

React Router:在没有手动页面刷新的情况下,路由不会更新内容

这两个子元素在Reaction Native中使用的有什么不同?

如何使用 React 获取表单中的所有值?

如何在不同的路由中渲染相同的页面组件(包括 getServerSideProps)

我无法通过 useContext 显示值

验证 Yup 中的对象项

强制 useEffect 仅运行一次

React useEffect 依赖项

是否可以直接在 jsx 标签上使用 CSS 定义的 colored颜色 ?

React - 如何重定向页面以显示数据修改?

try 从 React JS 构建此教程游戏但无法继续前进

在react 中从外部 api 渲染列表

类型错误:类型typeof import(js-cookie)上不存在属性get

带有 webpack 错误多个文件匹配路由名称的 Expo-router.无法Bundle 或部署应用程序

.filter() 函数在删除函数中创建循环 - React

如果两个组件在 React 中导入相同的 CSS 文件会发生什么?