简体   繁体   English

用 vanilla JS 开玩笑 - 在 DOM 上测试生成的元素

[英]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)在网上搜索了很多,但找不到获取元素的 innerHTML 并将其与应呈现的结果进行比较的最佳方法(我正在尝试与字符串进行比较)

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.您可以使用快照测试来测试 DOM 树结构。

Snapshot tests are a very useful tool whenever you want to make sure your UI does not change unexpectedly.当您想确保您的 UI 不会发生意外更改时,快照测试是一个非常有用的工具。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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