Making the window to different data type in react testing library

蹲街弑〆低调 提交于 2019-12-18 09:39:29

问题


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"));
        });
    });
});

any help is appreciated

来源:https://stackoverflow.com/questions/59173156/making-the-window-to-different-data-type-in-react-testing-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!