【问题标题】:Testing character count in textarea测试文本区域中的字符数
【发布时间】:2023-01-12 23:19:44
【问题描述】:

我有一个组件,它有 2 个基于 pageIndex 具有不同背景颜色的 div。我想在 pageIndex = 0pageIndex = 1 时测试这个组件。测试在两种情况下都成功,但在第二种情况下也必须失败。我在这里错过了什么?

export function FormSteps(props: FormStepsProps) {
  return (
    <div>
      <div
        style={{
          backgroundColor:
            props.pageIndex === 0
              ? "green"
              : "red",
        }}
      >
        <span>Step 1</span>
      </div>
      <div
        style={{
          backgroundColor:
            props.pageIndex === 1
              ? "red"
              : "green",
        }}
      >
        <span>Step 2</span>
      </div>
    </div>
  );
}
test("Page Index is 0", () => {
  render(<FormSteps pageIndex={0} />);

  const fieldStep1 = screen.getByText(/step 1/i);
  const fieldStep2 = screen.getByText(/step 2/i);

  expect(fieldStep1).toHaveStyle(`backgroundColor: "green"`);
  expect(fieldStep2).toHaveStyle(`backgroundColor: "red"`);
});

test("Page Index is 1", () => {
  render(<FormSteps pageIndex={1} />);

  const fieldStep1 = screen.getByText(/step 1/i);
  const fieldStep2 = screen.getByText(/step 2/i);

  expect(fieldStep1).toHaveStyle(`backgroundColor: "green"`);
  expect(fieldStep2).toHaveStyle(`backgroundColor: "red"`);
});

【问题讨论】:

  • 您在三元组中进行了两项更改:pageIndex 相等和反转结果

标签: reactjs react-testing-library


【解决方案1】:

根据您的代码,如果 page index === 0,那么第一个 div 将是您测试的 green,第二个 div 应该是 backgroundColor: "red",而对于 page index === 1 则不然。这是通过测试的正确代码:

test("Page Index is 0", () => {
  render(<FormSteps pageIndex={0} />);

  const fieldStep1 = screen.getByText(/step 1/i);
  const fieldStep2 = screen.getByText(/step 2/i);

  expect(fieldStep1).toHaveStyle(`backgroundColor: "green"`);
  expect(fieldStep2).toHaveStyle(`backgroundColor: "green"`);
});

test("Page Index is 1", () => {
  render(<FormSteps pageIndex={1} />);

  const fieldStep1 = screen.getByText(/step 1/i);
  const fieldStep2 = screen.getByText(/step 2/i);

  expect(fieldStep1).toHaveStyle(`backgroundColor: "red"`);
  expect(fieldStep2).toHaveStyle(`backgroundColor: "red"`);
});

但是如果你想让你的第二个测试失败,应该是这样的(这是我从你的问题中理解的,第二个测试应该失败):

test("Page Index is 1", () => {
  render(<FormSteps pageIndex={1} />);

  const fieldStep1 = screen.getByText(/step 1/i);
  const fieldStep2 = screen.getByText(/step 2/i);

  expect(fieldStep1).toHaveStyle(`backgroundColor: "green"`);
  expect(fieldStep2).toHaveStyle(`backgroundColor: "green"`);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 2021-12-21
    • 2013-07-13
    • 2011-07-28
    • 2012-12-14
    相关资源
    最近更新 更多