Jest学习笔记(2)-- 测试DOM,Vue组件

101 阅读1分钟

DOM测试

// dom.test.js
function renderHtml () {
  const div = document.createElement("div");
  div.innerHTML = `<h1>Hello World</h1>`;
  document.body.appendChild(div);
}
test('DOM Test', () => {
  renderHtml();
  expect(document.querySelector('h1').innerHTML).toBe('Hello World');
})

image.png

Vue组件测试

  • vue2写法
function renderVueComponent () {
  document.body.innerHTML = `
    <div id="app"></div>
  `
  new Vue({
    template: `
      <div id="app">
       <h1> {{message}} </h1>
      </div>
    `,
    data: {
      message: 'Hello World'
    }
  }).$mount('#app');
}
test('Vue Test', () => {
  renderVueComponent();
  console.log(document.body.innerHTML);
  expect(document.querySelector('h1').innerHTML).toBe('Hello World');
})
  • vue3写法
import { createApp, ref, reactive, watchEffect } from 'vue';

function renderVueComponent () {
  document.body.innerHTML = `
    <div id="app"></div>
  `
  const app = createApp({
    template: `
      <h1>{{ message }}</h1>
    `,
    setup() {
      const data = reactive({
        message: 'Hello, Vue3!',
      })
      const message = ref(data.message)
      watchEffect(() => {
        message.value = data.message
      })
      return {
        message,
      }
    }
  })
  app.mount('#app');
}

test('Vue Test', () => {
  renderVueComponent();
  console.log(document.body.innerHTML);
  expect(document.body.innerHTML).toMatch(/Hello, Vue3/);
})

image.png

快照测试

test.only('SnapShot Test', () => {
  renderVueComponent();
  // 第一次运行的时候,会生成快照文件字符串
  // 下一次运行测试的时候会和快照文件进行对比
  expect(document.body.innerHTML).toMatchSnapshot();
})

image.png

  • 假如我们不小心误改了某一处代码,例如更改了id,此时运行会捕获不同

image.png

  • 如果我们确定要修改,此时可以执行命令更新快照
jest --updateSnapshot
  • 如果没有全局安装jest,可以执行npx jest --updateSnapshot
  • 此时发现可以测试通过

image.png