使用React测试库测试输入事件

时间:2020-08-06 09:08:52

标签: react-testing-library

我已经在react中创建了一个小型键盘应用程序,并且试图在该应用程序上测试输入事件,由于某种原因,我没有得到预期的结果。我正在尝试测试它是否成功。我正在运行的测试如下,我想输入1995(正确的组合),单击“解锁”按钮并最终收到一条消息,返回“ Unlocked!”,但它仅返回Incorrect Code!仅当代码不正确或输入字段为空时才会发生。但这不应该是空的,因为我已经在测试中填写了它。

这是一个代码框:https://codesandbox.io/s/quirky-cloud-gywu6?file=/src/App.test.js:0-26

有什么想法吗?

测试:

const setup = () => {
  const utils = render(<App />);
  const input = utils.getByLabelText("input-code");
  return {
    input,
    ...utils
  };
};

test("It should return a successful try", async () => {
  const { input, getByTestId } = setup();
  await act(async () => {
    fireEvent.change(input, { target: { value: "1995" } });
  });
  expect(input.value).toBe("1995");

  await act(async () => {
    fireEvent.click(getByTestId("unlockbutton"));
  });
  expect(getByTestId("status")).toHaveTextContent("Unlocked!");
});

我要测试的组件

import React, { useState, useEffect } from "react";

import Keypad from "./components/Keypad";

import "./App.css";
import "./css/Result.css";

function App() {
  //correctCombination: 1995

  const [result, setResult] = useState("");
  const [locked, setLocked] = useState("Locked");
  const [tries, setTries] = useState(0);
  const [hide, setHide] = useState(true);

  //Along with the maxLength property on the input,
  // this is also needed for the keypad
  useEffect(() => {
    (function() {
      if (result >= 4) {
        setResult(result.slice(0, 4));
      }
    })();
  }, [result]);

  const onClick = button => {
    switch (button) {
      case "unlock":
        checkCode();
        break;
      case "clear":
        clear();
        break;
      case "backspace":
        backspace();
        break;
      default:
        setResult(result + button);
        break;
    }
  };

  const checkCode = () => {
    if (result === "1995") {
      setLocked("Unlocked!");
      setTries(0);
    } else if (tries === 3) {
      setHide(false);
      setLocked("Too many incorrect attempts!");
      setTimeout(() => {
        setHide(true);
      }, 3000);
    } else {
      setLocked("Incorrect code!");
      setTries(tries + 1);
    }
  };

  const clear = () => {
    setResult("");
  };

  const backspace = () => {
    setResult(result.slice(0, -1));
  };

  const handleChange = event => {
    setResult(event.target.value);
  };

  return (
    <div className="App">
      <div className="pin-body">
        <h1>Pin Pad</h1>
        <div className="status">
          <h2 data-testid="status">{locked}</h2>
        </div>
        <div className="result">
          <input
            maxLength={4}
            type="phone"
            aria-label="input-code"
            data-testid="inputcode"
            placeholder="Enter code"
            onChange={handleChange}
            value={result}
          />
        </div>
        {hide ? <Keypad onClick={onClick} /> : false}
      </div>
    </div>
  );
}

export default App;

0 个答案:

没有答案