天天看点

Jasmine单元测试

Jasmine

Jasmine 作为一款流行的 JS 测试工具,很轻巧。虽然只有 20K 左右, 但功能挺丰富的。另外学过Junit的话,会感觉它跟 JUnit 很像。

安装

可以在github上下载最新的 Jasmine 安装包.

下载地址: https://github.com/jasmine/jasmine/releases

目录

    ├── lib   Jasmine 源代码

    ├── spec  测试用例的代码

    ├── src   待测试的源代码

    ├── SpecRunner.html   用浏览器打开该文件,可以简单执行测试

例如:

<html>

<head>
    <meta charset="utf-8">
    <title>Jasmine Spec Runner v2.2.0</title>
    <link rel="stylesheet" href="lib/jasmine-1.3.1/jasmine.css" target="_blank" rel="external nofollow" >
    <script src="lib/jasmine-1.3.1/jasmine.js"></script>
    <script src="lib/jasmine-1.3.1/jasmine-html.js"></script>
    <!-- <script src="lib/jasmine-2.0.0/boot.js"></script> -->

    <!-- include source files here... -->
    <script src="src/Animal.js"></script>   

    <!-- include spec files here... -->
    <script src="spec/TestAnimal.js"></script>

    <script type="text/javascript">
      var jasmineEnv = jasmine.getEnv();
      var htmlReporter = new jasmine.HtmlReporter();

      jasmineEnv.addReporter(htmlReporter);

      jasmineEnv.specFilter = function(spec) {
          return htmlReporter.specFilter(spec);
      };

      window.onload = function() {
          jasmineEnv.execute();
      };
    </script>
</head>

<body></body>

</html>
           

describe

定义一个测试集合 Test Suite,测试的代码的开始。该函数是 Jasmine 的全局函数,有两个参数 : 

字符串 : Suite 的名字和标题。

方法 : 测试代码。

it

使用全局函数 it() 定义一个测试。跟 describe 一样,it 也是有 2 个参数,字符串和方法。同时包含一到多个断言 expect 。

另外,根据JS的作用域可知,在 describe 中定义的变量对 Suite 中的任何 it 代码块都是可见的。

到这有没有觉得 describe 对应Junit的测试类,it 对应 Junit的 单元测试用例了。

expect

类似 Junit 中一些断言,Jasmine 中也提供了大量实用的Matchers 供我们使用。

describe("This is an exmaple suite", function() {
    	it("contains spec with an expectation", function() {
    		expect(true).toBe(true);
			expect(false).toBe(false);
			expect(false).not.toBe(true);
		});

	});
           

其他的 Matchers 还有:

toBe()
toNotBe()
toBeDefined()
toBeUndefined()
toBeNull()
toBeTruthy()
toBeFalsy()
toBeLessThan()
toBeGreaterThan()
toEqual()
toNotEqual()
toContain()
toBeCloseTo()
toHaveBeenCalled()
toHaveBeenCalledWith()
toMatch()
toNotMatch()
toThrow()
           

有兴趣的话可以自己一一尝试。

beforeEach和afterEach 

Junit中提供了setup 和 teardown 用于一些环境预置、DB连接等,很是实用。Jasmine中给我们提供了beforeEach和afterEach。 只是有点不同的是,这两个函数更多的是为了是测试用例干净重复的执行一些代码。

describe("Animal", function() {

    beforeEach(function() {
        animal = new Animal();
        // JavaScript 的作用域的规则适用,所以在 describe 定义的变量对 Suite 中的任何 it 代码块都是可见的。
    });

    afterEach(function() {
    	console.log('afterEach')
    });
});
           

describe嵌套

describe 不光为我们提供了一个测试集。还能通过嵌套帮助我们对单元测试进行分组。

在配合 it()可以在任何一层进行。这样一个测试集就由一组树状的方法组成。在每个 it() 执行前,Jasmine 遍历树结构,按顺序执行每个 beforeEach 方法。it()执行后,Jasmine 同样执行相应的 afterEach。而且Jasmine也会为describe执行一次。

xdescribe 和 xit

当我们更改代码后,可以需要跳过一些单元测试。在Junit中 我们可以使用 @Ignore 来实现。到了Jasmine中,我们可以用xdescribe 和 xit来忽略一些单元测试。

Karma

类似Maven,可以对Junit的测试用例进行自动化单元测试;Karma 作为 JS 测试执行过程管理工具,也可用于自动化完成单元测试。

安装命令

>npm install karma -g
           

初始化

>karma init
           
该命令会生成 karma.conf.js 文件。这里一路默认,最后我们再更改配置文件即可。
修改 karma.conf.js 配置文件。一般我们只需要修改两三个即可。
files : 被测试文件,测试文件。用模式的方式。
exclude : 顾名思义,让 karma 忽略的文件。一般是让其忽略 karma.conf.js。
autoWatch 设置为 true,这样如果修改测试文件并保存后,Karma 会检测到然后自动执行。
           

这里是一个例子:

// Karma configuration
// Generated on Mon May 15 2017 14:27:55 GMT+0800 (China Standard Time)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],


    // list of files / patterns to load in the browser
    files: [
      'src/*.js',
      'spec/Test*.js'
    ],


    // list of files to exclude
    exclude: [
        'karma.conf.js'
    ],


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}
           

自动化执行

>karma start karma.conf.js
           

例子中我用的是chrome。它会打开浏览器,并在控制台输出如下:

Jasmine单元测试