天天看點

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單元測試