记一次简单的vue组件单元测试

栏目: 编程语言 · 发布时间: 5年前

内容简介:记录一些在为项目引入单元测试时的一些困惑,希望可以对社区的小伙伴们有所启迪,少走一些弯路少踩一些坑。通过上述的表格,作为一个vue项目,引入单元测试,大致思路已经有了:这并不是最终结果,测试vue单文件组件,当然少不了vue-test-utils,但是将它放在什么位置呢。 需要阅读vue-test-utils源码。
记一次简单的vue组件单元测试

记录一些在为项目引入单元测试时的一些困惑,希望可以对社区的小伙伴们有所启迪,少走一些弯路少踩一些坑。

  • jest, mocha, karma, chai, sinon, jsmine, vue-test-utils都是些什么东西?
  • chai,sinon是什么?
  • 为什么以spec.js命名?
  • 如何为聊天的文字消息组件写单元测试?
    • 运行在哪个目录下?
    • karma.conf.js怎么看?
    • 人生中第一次单元测试
  • istanbul是什么?
  • vue-test-utils的常用api?
  • 前端的单元测试,到底该测什么?

jest, mocha, karma, chai, sinon, jsmine, vue-test-utils都是些什么东西?

名词 Github描述 个人理解
jest Delightful JavaScript Testing. Works out of the box for any React project.Capture snapshots of React trees facebook家的测试框架,与react打配合会更加得心应手一些。
mocha Simple, flexible, fun JavaScript test framework for Node.js & The Browser 强大的测试框架,中文名叫抹茶,常见的describe,beforeEach就来自这里
karma A simple tool that allows you to execute JavaScript code in multiple real browsers. Karma is not a testing framework, nor an assertion library. Karma just launches an HTTP server, and generates the test runner HTML file you probably already know from your favourite testing framework. 不是测试框架,也不是断言库,可以做到抹平浏览器障碍式的生成测试结果
chai BDD / TDD assertion framework for node.js and the browser that can be paired with any testing framework. BDD/TDD断言库,assert,expect,should比较有趣
sinon Standalone and test framework agnostic JavaScript test spies, stubs and mocks js mock测试框架,everything is fake,spy比较有趣
jsmine Jasmine is a Behavior Driven Development testing framework for JavaScript. It does not rely on browsers, DOM, or any JavaScript framework. Thus it's suited for websites, Node.js projects, or anywhere that JavaScript can run. js BDD测试框架
vue/test-utils Utilities for testing Vue components 专门为测试单文件组件而开发,学会使用vue-test-utils,将会在对vue的理解上更上一层楼

通过上述的表格,作为一个vue项目,引入单元测试,大致思路已经有了:

测试框架:mocha
抹平环境:karma
断言库:chai
BDD库:jsmine
复制代码

这并不是最终结果,测试vue单文件组件,当然少不了vue-test-utils,但是将它放在什么位置呢。 需要阅读vue-test-utils源码。

chai,sinon是什么?

chai是什么?

  • Chai是一个node和浏览器可用的BDD/TDD断言库。
  • Chai类似于Node内建API的assert。
  • 三种常用风格:assert,expect或者should。
const chai = require('chai');
const assert = chai.assert;
const expect = chai.expect();
const should = chai.should();
复制代码

sinon是什么?

  • 一个 once函数,该如何测试这个函数?
  • spy是什么?
function once(fn) {
    var returnValue, called = false;
    return function () {
        if (!called) {
            called = true;
            returnValue = fn.apply(this, arguments);
        }
        return returnValue;
    };
}
复制代码

Fakes

it('calls the original function', function () {
    var callback = sinon.fake();
    var proxy = once(callback);

    proxy();

    assert(callback.called);
});
复制代码

只调用一次更重要:

it('calls the original function only once', function () {
    var callback = sinon.fake();
    var proxy = once(callback);

    proxy();
    proxy();

    assert(callback.calledOnce);
    // ...or:
    // assert.equals(callback.callCount, 1);
});
复制代码

而且我们同样觉得this和参数重要:

it('calls original function with right this and args', function () {
    var callback = sinon.fake();
    var proxy = once(callback);
    var obj = {};

    proxy.call(obj, 1, 2, 3);

    assert(callback.calledOn(obj));
    assert(callback.calledWith(1, 2, 3));
});
复制代码

行为

once返回的函数需要返回源函数的返回。为了测试这个,我们创建一个假行为:

it("returns the return value from the original function", function () {
    var callback = sinon.fake.returns(42);
    var proxy = once(callback);

    assert.equals(proxy(), 42);
});
复制代码

同样还有 Testing Ajax,Fake XMLHttpRequest,Fake server,Faking time等等。

sinon.spy()?

test spy是一个函数,它记录所有的参数,返回值,this值和函数调用抛出的异常。 有3类spy:

  • 匿名函数
  • 具名函数
  • 对象的方法

匿名函数

测试函数如何处理一个callback。

"test should call subscribers on publish": function() {
    var callback = sinon.spy();
    PubSub.subscribe("message", callback);
    PubSub.publishSync("message");
    assertTrue(callback.called);
}
复制代码

对象的方法

用spy包裹一个存在的方法。 sinon.spy(object,"method") 创建了一个包裹了已经存在的方法object.method的spy。这个spy会和源方法一样表现(包括用作构造函数时也是如此),但是你可以拥有数据调用的所有权限,用object.method.restore()可以释放出spy。这里有一个人为的例子:

{
    setUp: function () {
        sinon.spy(jQuery, "ajax");
    },
    tearDown: function () {
        jQuery.ajax.restore();// 释放出spy
    },
}
复制代码

引申问题

BDD/TDD是什么?

What’s the difference between Unit Testing, TDD and BDD? [译]单元测试,TDD和BDD之间的区别是什么?

为什么以spec.js命名?

SO上有这样一个问题: What does “spec” mean in Javascript Testing

spec是sepcification的缩写。

就测试而言,Specification指的是给定特性或者必须满足的应用的技术细节。最好的理解这个问题的方式是:让某一部分代码成功通过必须满足的规范。

如何为聊天的文字消息组件写单元测试?

运行在哪个文件夹下?

test文件夹下即可,文件名以.spec.js结尾即可,通过files和preprocessors中的配置可以匹配到。

karma.conf.js怎么看?

看不懂karma.conf.js,到 karma-runner.github.io/0.13/config… 学习配置。

const webpackConfig = require('../../build/webpack.test.conf');
module.exports = function karmaConfig(config) {
  config.set({
    browsers: ['PhantomJS'],// Chrome,ChromeCanary,PhantomJS,Firefox,Opera,IE,Safari,Chrome和PhantomJS已经在karma中内置,其余需要插件
    frameworks: ['mocha', 'sinon-chai', 'phantomjs-shim'],// ['jasmine','mocha','qunit']等等,需要额外通过NPM安装
    reporters: ['spec', 'coverage'],//  默认值为progress,也可以是dots;growl,junit,teamcity或者coverage需要插件。spec需要安装karma-spec-reporter插件。
    files: ['./index.js'],// 浏览器加载的文件,  `'test/unit/*.spec.js',`等价于 `{pattern: 'test/unit/*.spec.js', watched: true, served: true, included: true}`。
    preprocessors: {
      './index.js': ['webpack', 'sourcemap'],// 预处理加载的文件
    },
    webpack: webpackConfig,// webpack配置,karma会自动监控test的entry points
    webpackMiddleware: {
      noInfo: true, // webpack-dev-middleware配置
    },
    // 配置reporter 
    coverageReporter: {
      dir: './coverage',
      reporters: [{ type: 'lcov', subdir: '.' }, { type: 'text-summary' }],
    },
  });
};
复制代码

结合实际情况,通过https://vue-test-utils.vuejs.org/guides/testing-single-file-components-with-karma.html 添加切合vue项目的karma配置。

demo地址: github.com/eddyerburgh…

人生中第一次单元测试

karma.conf.js

// This is a karma config file. For more details see
//   http://karma-runner.github.io/0.13/config/configuration-file.html
// we are also using it with karma-webpack
//   https://github.com/webpack/karma-webpack

const webpackConfig = require('../../build/webpack.test.conf');

module.exports = function karmaConfig(config) {
  config.set({
    // to run in additional browsers:
    // 1. install corresponding karma launcher
    //    http://karma-runner.github.io/0.13/config/browsers.html
    // 2. add it to the `browsers` array below.
    browsers: ['Chrome'],
    frameworks: ['mocha'],
    reporters: ['spec', 'coverage'],
    files: ['./specs/*.spec.js'],
    preprocessors: {
      '**/*.spec.js': ['webpack', 'sourcemap'],
    },
    webpack: webpackConfig,
    webpackMiddleware: {
      noInfo: true,
    },
    coverageReporter: {
      dir: './coverage',
      reporters: [{ type: 'lcov', subdir: '.' }, { type: 'text-summary' }],
    },
  });
};
复制代码

test/unit/specs/chat.spec.js

import { mount } from '@vue/test-utils';
import { expect } from 'chai';
import ChatText from '@/pages/chat/chatroom/view/components/text';
describe('ChatText.vue', () => {
  it('人生中第一次单元测试:', () => {
    const wrapper = mount(ChatText);
    console.log(wrapper.html());
    const subfix = '</p> <p>默认文字</p></div>';
    expect(wrapper.html()).contain(subfix);
  });
});
复制代码

注意,被测试组件必须以index.js暴露出组件。 NODE_ENV=testing karma start test/unit/karma.conf.js --single-run 测试结果:

记一次简单的vue组件单元测试

意外收获

1.PhantomJS是什么?

  • 是一个无头的脚本化浏览器。
  • 可以运行在Windows, macOS, Linux, and FreeBSD.
  • QtWebKit,可以做DOM处理,可以CSS选择器,可以JSON,可以Canvas,也可以SVG。

下载好phantomjs后,就可以在终端中模拟浏览器操作了。 foo.js

var page = require('webpage').create();
page.open('http://www.google.com', function() {
    setTimeout(function() {
        page.render('google.png');
        phantom.exit();
    }, 200);
});
复制代码
phantomjs foo.js
复制代码

运行上述代码后,会生成一张图片,但是画质感人。

记一次简单的vue组件单元测试

2.karma-webpack是什么? 在karma中用webpack预处理文件。

istanbul是什么?

记一次简单的vue组件单元测试

vue-test-utils的常用api及其option?

  • mount:propsData,attachToDocument,slots,mocks,stubs?
  • mount和shallowMount的区别是什么?

啥玩意儿???一一搞定。

mount:propsData,attachToDocument,slots,mocks,stubs?

this.vm.$options.propsData // 组件的自定义属性,是因为2.1.x版本中没有$props对象,https://vue-test-utils.vuejs.org/zh/api/wrapper/#setprops-props
const elm = options.attachToDocument ? createElement() : undefined // "<div>" or undefined
slots // 传递一个slots对象到组件,用来测试slot是否生效的,值可以是组件,组件数组或者字符串,key是slot的name
mocks // 模拟全局注入
stubs // 存根子组件
复制代码

后知后觉,这些都可以在Mounting Options文档查看: vue-test-utils.vuejs.org/api/options…

mount和shallowMount的区别是什么?

mount仅仅挂载当前组件实例;而shallowMount挂载当前组件实例以外,还会挂载子组件。

前端的单元测试,到底该测什么?

这是一个一直困扰我的问题。 测试通用业务组件?业务变更快速,单元测试波动较大。:x: 测试用户行为?用户行为存在上下文关系,组合起来是一个很恐怖的数字,这个交给测试人员去测就好了。:x: 那我到底该测什么呢?要测试 功能型组件,vue插件,二次封装的库 。:heavy_check_mark:

就拿我负责的项目来说:

  • 功能型组件:可复用的上传组件,可编辑单元格组件,时间选择组件。(前两个组件都是老大写的,第三个是我实践中抽离出来的。)
  • vue插件:mqtt.js,eventbus.js。(这两个组件是我抽象的。)
  • 二次封装库:httpclient.js。(基于axios,老大初始化,我添砖加瓦。)

上述适用于单元测试的内容都有一个共同点: 复用性高!

所以我们在纠结要不要写单元测试时,抓住 复用性高 这个特点去考虑就好了。

单元测试是为了保证什么呢?

  • 按照预期输入,组件或者库有预期输出,告诉开发者all is well。
  • 未按照预期输入,组件或者库给出预期提醒,告诉开发者something is wrong。

所以,其实单元测试是为了帮助开发者的突破自己内心的最后一道心理障碍,建立 老子的代码完全ojbk,不可能出问题 的自信。

其实最终还是保证用户有无bug的组件可用,有好的软件或平台使用,让自己的生活变得更加美好。


以上所述就是小编给大家介绍的《记一次简单的vue组件单元测试》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Real-Time Collision Detection

Real-Time Collision Detection

Christer Ericson / CRC Press / 2004-12-22 / USD 98.95

Written by an expert in the game industry, Christer Ericson's new book is a comprehensive guide to the components of efficient real-time collision detection systems. The book provides the tools and kn......一起来看看 《Real-Time Collision Detection》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具