How to test content of iframe using jest?

by aniya.jaskolski , in category: Javascript , 3 months ago

How to test content of iframe using jest?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 3 months ago

@aniya.jaskolski 

To test the content of an iframe using Jest, you can use the following steps:

  1. First, you need to make sure that the iframe is actually present in the DOM. You can use a tool like jest-dom to help with this:
1
2
3
4
5
6
import "@testing-library/jest-dom/extend-expect";

test("iframe is present in the document", () => {
  const iframe = document.querySelector(".iframe-class");
  expect(iframe).toBeInTheDocument();
});


  1. Next, you can use the Jest and JSDOM APIs to access and test the content inside the iframe. You can access the content of the iframe using the contentWindow property and then manipulate it as needed. Here's an example:
1
2
3
4
5
6
test("content of iframe is correct", () => {
  const iframe = document.querySelector(".iframe-class");
  const iframeDocument = iframe.contentWindow.document;
  
  expect(iframeDocument.body.innerHTML).toContain("Expected content");
});


  1. If the content inside the iframe is dynamically loaded, you may need to wait for it to fully load before running your tests. You can use async/await and setTimeout to simulate this delay:
1
2
3
4
5
6
7
8
9
test("content of iframe is correct", async () => {
  const iframe = document.querySelector(".iframe-class");
  const iframeDocument = iframe.contentWindow.document;

  // Delay for 1 second to allow content to fully load
  await new Promise(resolve => setTimeout(resolve, 1000));
  
  expect(iframeDocument.body.innerHTML).toContain("Expected content");
});


By following these steps, you can effectively test the content of an iframe using Jest in your unit tests.