I am using jest, jsdom and testing-libray/dom to test this page (index.html). i expect paragraph to be "welcome" but i am getting empty string ("") because a page (index.html) is loading before javascript.
I would like to ask if there are other ways to do it. thanks.
this is how my code looks like. index.html
<html>
<body>
<p data-testid="paragraph"></p>
<script type="text/javascript">
const p = document.querySelector("p");
p.textContent = "welcome";
</script>
</body>
</html>
index.test.js
const { getByTestId } = require("@testing-library/dom");
const { JSDOM } = require("jsdom");
require("@testing-library/jest-dom/extend-expect");
const path = require("path");
const fs = require("fs");
let dom;
let container;
const html = fs.readFileSync(path.join(__dirname, "./index.html"));
describe("index", () => {
beforeEach(() => {
dom = new JSDOM(html, { runScripts: "dangerously" });
container = dom.window.document.body;
});
it("should display welcome text", () => {
const pEl = getByTestId(container, "paragraph");
expect(pEl.textContent).toEqual("welcome");
});
});
screenshoot enter image description here thanks