Pārlūkot izejas kodu

Refactor out hook from RoundTimer and improve tests

Kirk Trombley 4 gadi atpakaļ
vecāks
revīzija
b081f4e094

+ 2 - 20
client/src/components/screens/GamePanel/GuessPane/RoundTimer.jsx

@@ -1,27 +1,9 @@
 import ms from "pretty-ms";
-import { useEffect, useState } from "react";
-import { dispatch, useRoundSeconds } from "../../../../domain/gameStore";
 import styles from "./GuessPane.module.css";
+import useRoundTimer from "./useRoundTimer";
 
 const RoundTimer = ({ onTimeout }) => {
-  const remaining = useRoundSeconds();
-  // eslint-disable-next-line consistent-return
-  useEffect(() => {
-    if (remaining > 0) {
-      const timeout = setTimeout(() => {
-        dispatch.updateRoundSeconds(r => r - 1);
-      }, 1000);
-      return () => clearTimeout(timeout);
-    }
-  }, [remaining]);
-  const [called, setCalled] = useState(false);
-  useEffect(() => {
-    if (!called && remaining <= 0) {
-      onTimeout();
-      setCalled(true);
-    }
-  }, [onTimeout, remaining, called]);
-
+  const remaining = useRoundTimer(onTimeout);
   return remaining > 0 ? (
     <span className={styles.timer}>Time: {ms(remaining * 1000)}</span>
   ) : (

+ 24 - 0
client/src/components/screens/GamePanel/GuessPane/useRoundTimer.jsx

@@ -0,0 +1,24 @@
+import { useEffect, useState } from "react";
+import { dispatch, useRoundSeconds } from "../../../../domain/gameStore";
+
+const useRoundTimer = onTimeout => {
+  const remaining = useRoundSeconds();
+  // eslint-disable-next-line consistent-return
+  useEffect(() => {
+    if (remaining > 0) {
+      const timeout = setTimeout(() => {
+        dispatch.updateRoundSeconds(r => r - 1);
+      }, 1000);
+      return () => clearTimeout(timeout);
+    }
+  }, [remaining]);
+  const [called, setCalled] = useState(false);
+  useEffect(() => {
+    if (!called && remaining <= 0) {
+      onTimeout();
+      setCalled(true);
+    }
+  }, [onTimeout, remaining, called]);
+};
+
+export default useRoundTimer;

+ 4 - 4
client/src/tests/RoundTimer.test.js

@@ -2,18 +2,18 @@ import React from "react";
 import { shallow } from "enzyme";
 import RoundTimer from "../components/screens/GamePanel/GuessPane/RoundTimer";
 
-jest.mock("../domain/gameStore");
+jest.mock("../components/screens/GamePanel/GuessPane/useRoundTimer");
 
-import { useRoundSeconds } from "../domain/gameStore";
+import useRoundTimer from "../components/screens/GamePanel/GuessPane/useRoundTimer";
 
 describe("RoundTimer", () => {
   it("renders with time left", () => {
-    useRoundSeconds.mockReturnValue(100);
+    useRoundTimer.mockReturnValue(100);
     const rendered = shallow(<RoundTimer />);
     expect(rendered).toMatchSnapshot();
   });
   it("renders with no time left", () => {
-    useRoundSeconds.mockReturnValue(0);
+    useRoundTimer.mockReturnValue(0);
     const rendered = shallow(<RoundTimer />);
     expect(rendered).toMatchSnapshot();
   });