开玩笑无法为window.parent.location.href设置唯一的href

问题描述

我在代码中进行了检查,以查看是否在iframe中加载了页面

App.js

if (window.location !== window.parent.location) {
  console.log('App is running inside iframe!');
}

开玩笑...

App.spec.js

delete window.location
window.location = new URL(`https://some-fake-url`)

delete window.parent.location
window.parent.location = new URL(`https://parent-fake-url`);

在Jest测试中,window.location.hrefwindow.parent.location.href都设置了相同的值。

如何将每个设置为唯一?

解决方法

我相信我可以通过以下方法解决此问题...

    global.window = Object.create(window);
    delete global.window.parent;
    global.window.parent = Object.create(window);

    Object.defineProperty(global.window,'location',{
        value: {
          href: 'https://my-site'
        }
    });

    Object.defineProperty(global.window.parent,{
        value: {
          href: 'https://my-parent-site'
        }
    });