Skip to content

Jest with vanilla JS – tesing generated elements on DOM

Searched a lot online but cant find the best way to get an element’s innerHTML and just compare it with the results that should be rendered (I’m trying to compare with string)

expect(document.body.innerHTML.toString()).toBe("<div class='wrapper'><span>test</span></div>");

what I’m trying is adding some whitespace and test failed so I’m guessing there is better ways

Also, unable to query a specific element generated inside body, why?



You can use Snapshot Testing to test the DOM tree structure.

Snapshot tests are a very useful tool whenever you want to make sure your UI does not change unexpectedly.


describe('67618056', () => {
  it('should pass', () => {
    document.body.innerHTML = `
        <div class='wrapper'>
              <div class=\"wrapper\">

test result:

 PASS  examples/67618056/index.test.ts (7.563 s)
    ✓ should pass (17 ms)

 › 1 snapshot written.
Snapshot Summary
 › 1 snapshot written from 1 test suite.

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   1 written, 1 total
Time:        8.03 s, estimated 9 s
User contributions licensed under: CC BY-SA
6 People found this is helpful