在反应测试库中将窗口设置为不同的数据类型

时间:2019-12-04 09:52:26

标签: reactjs react-testing-library

我正在尝试测试可重复使用的挂钩,以检查是否已触发窗口调整大小。

我正在使用酶进行单元测试,因为我无法找到文档和对我正在使用的钩子的支持

  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}

我能够测试正常的流程,但是如何使窗口变为不同的数据类型,以便使代码覆盖率达到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"));
        });
    });
});

感谢您的帮助

0 个答案:

没有答案