如何测试根据 prop 更改 CSS 属性的 useEffect 钩子?

Men*_*ine 3 reactjs cypress react-testing-library

p我有一个 TextField 组件,右侧包含一个单元 ( )。我动态地更改了该单元和文本值之间的填充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;

``

Run Code Online (Sandbox Code Playgroud)

按钮.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", "???");
    });
  });
Run Code Online (Sandbox Code Playgroud)

Lol*_*ola 6

应用程序将 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)
})
Run Code Online (Sandbox Code Playgroud)

即使元素宽度由于窗口宽度、弹性布局、媒体查询(移动设备/平板电脑/桌面设备)而发生变化,这也应该成功。

如果我理解正确的话,你只想知道填充始终是宽度+20。


如果unitRef指向<p>

我认为如果我的假设是正确的,测试代码需要调整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)
  })
})
Run Code Online (Sandbox Code Playgroud)