当窗口未定义时,我正try 在自定义钩子中测试此逻辑.
if (typeof window !== "undefined") {
console.log('inside');
return true;
}
console.log('outside');
return false;
};
从而模拟窗口,如下所示并运行后续测试.
import React from "react";
import { renderHook, act } from "react-hooks-testing-library";
const windowSpy = jest.spyOn(window, "window", "get");
afterEach(() => {
windowSpy.mockRestore();
});
test("should return false when window is undefined", () => {
windowSpy.mockImplementation(() => undefined);
const { result } = renderHook(() => myHook("test"));
expect(result.current).toBe(false);
});
当我运行这个测试时,窗口没有像预期的那样定义,但我最终得到了以下错误,从react-test-renderer.development.js
开始.
TypeError: Cannot read property 'event' of undefined: line 2352
当我在If判断期间查看下面的库时,窗口并不是未定义的.
但当我们到达WindowEvent,Window时.是未定义的.
if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
// .....
var windowEvent = window.event; // This is the error. window undefined here.
// .....
}
}
可以肯定地说,解决方案不在这个自由党的范围内.但更多的是关于我如何在这里没有问题地嘲笑.
如何编写测试,以便在窗口未定义但不受此库错误影响时进行测试?
全钩子实现,供参考.
import React from "react";
import isWindowDefined from "../isWindowDefined";
export const isWindowDefined = () => window !== undefined;
const useMediaQuery = (query: string): boolean => {
const getMatches = (query: string): boolean => {
if (isWindowDefined()) {
return window.matchMedia(query).matches;
}
return false;
};
const [matches, setMatches] = React.useState<boolean>(getMatches(query));
const handleChange = () => {
setMatches(getMatches(query));
};
React.useEffect(() => {
const matchMedia = window.matchMedia(query);
handleChange();
matchMedia.addEventListener("change", handleChange);
return () => {
matchMedia.removeEventListener("change", handleChange);
};
}, [query]);
return matches;
};
export default useMediaQuery;