我在 React 应用程序中使用Navigator online来确定客户端是否在线。当客户端离线时,我显示离线后备组件。现在我已经将组件设为 Pure - 因此我可以通过将在线状态作为属性传递来在 Storybook 中显示它。但这并不总是合适的解决方案。
所以我想知道如何模拟 Storybook 中单个故事的全局(窗口)变量?我发现唯一的 - 非常脏的解决方案 - 看起来如下:
ClientOffline.decorators = [
(Story) => {
const navigatiorInitally = global.navigator
// I am overwritting the navigator object instead of directly the
// online value as this throws an 'TypeError: "x" is read-only' Error
Object.defineProperty(global, 'navigator', {
value: { onLine: false },
writable: false,
})
useEffect(() => {
return () => {
Object.defineProperty(global, 'navigator', {
value: navigatiorInitally,
writable: false,
})
location.reload() //needed because …Run Code Online (Sandbox Code Playgroud)