Skip to content

Instantly share code, notes, and snippets.

@spamshaker
Last active August 26, 2024 14:07
Show Gist options
  • Save spamshaker/cedad30442c331c02cf76301ee40d330 to your computer and use it in GitHub Desktop.
Save spamshaker/cedad30442c331c02cf76301ee40d330 to your computer and use it in GitHub Desktop.
IFrame jest simulation with jest by custom IFrameJSDOMEnvironment
const {default: JSDOMEnvironment} = require('jest-environment-jsdom');
const {JSDOM} = require('jsdom');
const createWindow = (url) => new JSDOM('', {
runScripts: 'dangerously',
url
}).window;
class IFrameJSDOMEnvironment extends JSDOMEnvironment {
constructor(config, context) {
super(config, context);
const windowTop = createWindow('http://localhost:8080/');
this.dom.reconfigure({windowTop});
Object.defineProperty(this.dom.window, 'parent', {value: windowTop});
}
}
module.exports = IFrameJSDOMEnvironment;
/**
* @jest-environment ./iframe-jest-jsdom-environment.js
* @jest-environment-options {"url": "http://localhost:8080/child.html"}
*/
describe('given a global window', () =>{
it('should be different than window.parent', () => expect(window!==window.parent).toBeTruthy());
it('should be different than window.top', () => expect(window!==window.top).toBeTruthy());
it('should have correct locations', () => {
expect(window.location.href).toEqual('http://localhost:8080/child.html');
expect(window.top?.location.href).toEqual('http://localhost:8080/');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment