博客 / 詳情

返回

Vue項目單元測試入門

本文以Jest測試框架為例子,介紹常用的api和用法

安裝

第一種:創建項目的時候勾選 Unit Testing,後續選擇 Jest
第二種:在項目根目錄執行 vue add @vue/cli-plugin-unit-jest

常用api

describe:創建測試分組
test(別名:it):創建測試用例
expect:提供各種方法判定測試結果是否符合預期

匹配函數

toBe: 值類型判斷相等
toEqual: 引用類型判斷相等
toBeNull
toBeUndefined
toBedefined
toBeNaN
toBeTruthy
toBeFalsy
toContain: 數組是否包含
toHaveLenth: 數組長度
toThrow: 異常匹配

生命週期

beforeAll:所有測試用例執行前觸發(只觸發一次)
beforeEach:每個測試用例執行前觸發
afterAll:所有測試用例執行後觸發(只觸發一次)
afterEach:每個測試用例執行後觸發

組件

mount:掛載組件,包括子組件
shallowMount:只掛載當前組件,不包括子組件

Wrapper:掛載後返回vnode和測試相關的方法
vm:返回vue實例
classes:返回相關類名的dom或者集合
find:返回滿足一個條件的dom
findAll:返回滿足所有條件的dom
html:返回html字符串
text:返回內容字符串
setData:設置組件data
setProps:設置組件props
trigger:觸發事件

用法

// utils.js
export function add(a, b) {
    return a + b
}

export class Count {
    constructor() {
        this.number = 1
    }

    increase() {
        this.number++
    }

    decreate() {
        this.number--
    }
}

export function timeout(fn) {
    setTimeout(function() {
        fn()
    }, 2000)
}

export function promise() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(2)
        }, 2000)
    })
}

常規測試

const { add } = require('./utils')

test('add 1 + 2 to equal 3', () => {
    expect(add(1, 2)).toBe(3)
})

分組測試

const { Count } = require('./utils')

describe('分組測試', () => {
    let obj = null
    beforeAll(() => {
        console.log('所有test執行前觸發')
    })

    beforeEach(() => {
        // 利用生命週期,避免類對象狀態相互影響
        console.log('每個test執行前觸發')
        obj = new Count()
    })

    afterAll(() => {
        console.log('所有test執行完觸發')
    })

    afterEach(() => {
        console.log('每個test執行完觸發')
    })

    test('測試increase', () => {
        expect(obj.increase()).toBe(2)
    })

    test('測試decrease', () => {
        expect(obj.decrease()).toBe(0)
    })
})

異步代碼測試

調用done函數

const { timeout } = require('./utils')

test('異步代碼測試', done => {
    timeout(() => {
        expect(2 + 2).toBe(4)
        done()
    })
})

跳過等待的時間

const { timeout } = require('./utils')

test('異步代碼測試', done => {
    jest.useFakeTimers()
    const fn = jest.fn()
    timeout(fn)
    jest.advanceTimersByTime(2000)
    expect(fn).toHaveBeenCalledTimes(1)
})

promise函數處理

方法一

const { promise } = require('./utils')

test('promise', () => {
    return promise().then(res => {
        expect(res).toBe(2)
    }) 
})

方法二

const { promise } = require('./utils')

test('promise', () => {
    return expect(promise()).resolves.toBe(2)
})

組件測試

// @/components/Modal.vue
<template>
  <div v-show="visible" class="modal-box">
    <div class="modal-title">{{ title }}</div>
    <div class="modal-content"></div>
  </div>
</template>

<script>
expect default {
  name: 'Modal',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    }
  }
}
</script>
// @/tests/unit/Modal.spec.js
import { shallowMount } from '@vue/test-utils'
import Modal from '@/components/Modal'

it('test Modal props.title', () => {
  const title = '標題'
  const wrapper = shallowMount(Modal, {
    propsData: { title }
  })
 
  expect(wrapper.find('.modal-title').text()).toBe(title)
})
user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.