Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

reactjs - Making the window to different data type in React testing library

I am trying to test a reusable hook for checking the window resize has been triggered or not.

I was using Enzyme for my unit testing, since I was not able to find docs and support for hooks I am using

  1. @testing-library/react
  2. @testing-library/react-hooks

hooks.js

import { useState, useEffect } from "react";

function useWindowSize() {
    const isClient = typeof window === "object";

    function getSize() {
        return {
            width: isClient ? window.innerWidth : undefined,
            height: isClient ? window.innerHeight : undefined,
        };
    }

    const [windowSize, setWindowSize] = useState(getSize);

    useEffect(() => {
        if (!isClient) {
            return false;
        }

        function handleResize() {
            setWindowSize(getSize());
        }

        window.addEventListener("resize", handleResize);
        return () => window.removeEventListener("resize", handleResize);
    }, []); // Empty array ensures that effect is only run on mount and unmount

    return windowSize;
}

export default {useWindowSize}

I was able to test the normal flow, but how can make the window to different data type so i can make the code coverage of 100%

hooks.test.js

import { renderHook, act } from "@testing-library/react-hooks";
import { fireEvent } from "@testing-library/react";
import hooks from "..";

const { useWindowSize } = hooks;

describe("hooks", () => {
    it("should return a new size of window", () => {
        const { result } = renderHook(() => useWindowSize());
        expect(result.current.width).toBe(1024);
        expect(result.current.height).toBe(768);

        act(() => {
            // change the viewport to 500px.
            window.innerWidth = 500;
            window.innerHeight = 500;
            // trigger the window resize event
            fireEvent(window, new Event("resize"));
        });

        expect(result.current.width).toBe(500);
        expect(result.current.height).toBe(500);
    });
    
    // how can i test if window is not an typeof object
    it("should exit if its not window", () => {
        const { result } = renderHook(() => useWindowSize());
        act(() => {
            // change the window from object 
            window = "";
            fireEvent(window, new Event("resize"));
        });
    });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...