Reputation: 11
Is it possible to access iframe
contents within Jest test?
This is my approach. Unfortunately no luck in there. headerElement
is undefined.
document.body.innerHTML = `
<iframe
class="js-iframe"
src="https://example.com"
onload="${iframeLoaded()}"
></iframe>
<script></script>
`;
function iframeLoaded() {
const headerElement = domMethodsService.getElement<HTMLIFrameElement>('.js-iframe')?.contentWindow?.document.getElementsByTagName('h1')
expect(headerElement).toBe('Example Domain');
doneCallback();
}
Upvotes: 1
Views: 3569
Reputation: 13078
You are calling iframeLoaded()
function before iframe loads it's content. Try creating the iframe
element using document.createElement
:
const iframe = document.createElement("iframe");
iframe.classList.add("js-iframe");
iframe.onload = iframeLoaded;
iframe.src = "https://example.com";
document.body.appendChild(iframe);
function iframeLoaded() {
const headerElement = iframe.contentWindow.document.querySelector('h1'); //--> getElementsByTagName will return more than one element
expect(headerElement).toBe('Example Domain');
doneCallback();
}
By default, jsdom
will not load any sub-resources like iframes. You can load such resources by setting resources: "usable"
, which will load all usable resources.
jest.config.js
"testEnvironmentOptions": { "resources": "usable" }
Upvotes: 3