简体   繁体   中英

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.

Eg

describe('67618056', () => {
  it('should pass', () => {
    document.body.innerHTML = `
        <div class='wrapper'>
            <span>test</span>
        </div>
    `;
    expect(document.body.innerHTML.toString()).toMatchInlineSnapshot(`
      "
              <div class=\\"wrapper\\">
                  <span>test</span>
              </div>
          "
    `);
  });
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM