单元测试

黑盒测试BDD(先开发功能再测试是否能实现)    白盒测试TDD(先写测试用例,测试驱动开发)

测试框架:vue/test-utils(vue用)    Jest(node模拟dom环境)

测试用例文件:.test.js结尾   .spec.js结尾(vue)

 

npm init -y
npm install jest
npm install @types/jest
npm install @babel/core @bable/preset-env --save-dev

.babelrc: 高级语法转es5
{
    "presets":[  预设
        [ 写成数组可以传参数
            "@babel/preset-env",{
                "targets": {"node":"current"}  目标,转到node版本最新的
            }
        ]
    ]
}

package.json: 配置运行
"scripts": {"test": "jest --watchAll"}

import引入被测试的js文件
describe('用例的作用域',()=>{
    it('测试函数',()=>{
    //断言
        expect(1+1).toBe(2);                      //计算等于
        expect({name:'zf'}).toEqual({name:'zf'}); //是否一模一样
        expect(true).toBeTruthy();                //是不是true
        expect(false).toBeFalsy();                //是不是false
        expect(1+1).not.toBe(3);                  //取反
        expect(1+1).toBeLessThan(3);              //是不是小于
        expect(1+1).toBeGreaterThan(1);           //是不是大于
        expect('hello').toContain('h');           //是否包含h
        expect('hello').toMatch(/h/);             //用正则
    })
})

 

自动化测试
npm run test
按f 强制刷新报错的
按o 只运行修改的,根据git历史
按p 输入文件名
按t 输入test测试名
按q 退出
按enter 全部重新执行

git init
加.gitignore文件:node_modules
git add .
git commit -m 'init'

 

dom.js:

export const removeNode = (node) => {
    node.parentNode.removeChild(node)
};
dom.test.js:
//单元测试中使用jsdom,然后你可以在测试文件中正常使用document对象
const { JSDOM } = require('jsdom');
const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`, { runScripts: "dangerously" });
global.document = dom.window.document;

import { removeNode } from "./dom";

describe('测试能否删除dom节点',()=>{
    it('removeNode',()=>{
        document.body.innerHTML = `<div><button id="btn"></button></div>`;
        let btn = document.querySelector('#btn');
        expect(btn).not.toBeNull(); //刚开始btn是否存在
        removeNode(btn);
        btn = document.querySelector('#btn');
        expect(btn).toBeNull(); //btn是否被删除掉了
    })
})

 

 

Karma

npm install --save-dev  karma karma-chrome-launcher karma-mocha karma-sourcemap-loader karma-spec-reporter karma-webpack mocha karma-chai

karma.conf.js

var webpackConfig = require('@vue/cli-service/webpack.config')

module.exports = function(config) {
  config.set({
    frameworks: ['mocha'],
    files: ['tests/**/*.spec.js'],
    preprocessors: {
      '**/*.spec.js': ['webpack', 'sourcemap']
    },
    autoWatch: true,
    webpack: webpackConfig,
    reporters: ['spec'],
    browsers: ['ChromeHeadless']
  })
}
{
  "scripts": {
    "test": "karma start"
  }
}
import { expect } from 'chai'
import Button from '@/packages/button';
import Icon from '@/packages/icon';
// @ts-ignore
import { createApp } from 'vue/dist/vue.esm-bundler.js';

describe('HelloWorld.vue', () => {
  it('测试插槽显示是否正常', () => {
    const container = document.createElement('div');
    const app = createApp({
      template: `<zfButton>hello</zfButton>`,
      components: {
        "zfButton": Button,
      }
    }, {
      icon: 'edit',
    }).mount(container);
    let html = app.$el.innerHTML
    expect(html).to.match(/hello/)
  });

  it('测试icon是否能够正常显示', () => {
    const container = document.createElement('div');
    const app = createApp({
      ...Button,
    }, {
      icon: 'edit',
    }).use(Icon).mount(container);
    let useEle = app.$el.querySelector('use');
    let href = useEle.getAttribute('xlink:href');
    expect(href).to.eq('#icon-edit');
  });

  it('测试传入loading时 按钮为禁用态', () => {
    const container = document.createElement('div');
    const app = createApp({
      template: `<zfButton></zfButton>`,
      components: {
        "zfButton": Button,
      }
    }, {
      loading: true,
    }).use(Icon).mount(container);
    let useEle = app.$el.querySelector('use');
    let href = useEle.getAttribute('xlink:href');
    let disabeld = app.$el.getAttribute('disabled')
    expect(href).to.eq('#icon-loading');
    expect(disabeld).not.to.eq(null);
  });
  // todo....
})

 

posted @ 2025-03-26 10:30  石头记1  阅读(13)  评论(0)    收藏  举报