可以在Jest测试中访问iframe内容吗

可以在Jest测试中访问iframe内容吗,iframe,jestjs,Iframe,Jestjs,是否可以访问Jest测试中的iframe内容? 这是我的方法。不幸的是,那里没有运气头关联未定义 document.body.innerHTML = ` <iframe class="js-iframe" src="https://example.com" onload="${iframeLoaded()}" ></iframe> <script></scri

是否可以访问Jest测试中的
iframe
内容? 这是我的方法。不幸的是,那里没有运气<代码>头关联未定义

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();
}
document.body.innerHTML=`
`;
函数iframeload(){
const headerElement=domMethodsService.getElement('.js iframe')?.contentWindow?.document.getElementsByTagName('h1'))
expect(headerElement).toBe('Example Domain');
doneCallback();
}

在iframe加载其内容之前调用函数iframeload()。尝试使用
文档创建元素。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();
  }
默认情况下,
jsdom
不会加载任何子资源,如iframe。要加载此类资源,可以传递
资源:“可用”
选项,该选项将加载所有可用资源

jest.config.js

"testEnvironmentOptions": { "resources": "usable" }

工作起来很有魅力!谢谢你,欢迎你;)