Jasmine单元测试入门

标签:前端开发 单元测试 jasmine


1. 什么是Jasmine

Jasmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests.This guide is running against Jasmine version 2.4.1.

简而言之,Jasmine就是一个行动驱动开发模式的JS的单元测试工具。
Jasmine github主页
官网教程: 英文,简单明了,自带demo,强烈推荐学习
Jasmine下载: 里面有一个自带的例子,SpecRunner.html, 打开就知道jasmine的大致使用了。


2. 基本使用

跟Qunit差不错,首先要有一个模板接收测试结果。
当然也可以配合自动化工具,例如grunt,直接显示在控制台。




  
  Jasmine v2.4.1

  
  
  
  
  
  

  
  
 
  
  






测试用例如下

describe("A suite", function() {
   it("contains spec with an expectation", function() { 
        expect(true).toBe(true);
        expect(false).not.toBe(true);
        //fail("test will fail if this code excute");  //可用于不想被执行的函数中
   });
});

describe定义一组测试,可嵌套;
it定义其中一个测试;

注意:应该按BDD的模式来写describe与it的描述。
关于BDD可参考:说起BDD,你会想到什么?

expect()的参数是需要测试的东西,toBe()是一种断言,相当于===,not相当于取非。
jasmine还有更多的断言,并且支持自定义断言,详细可见官网教程。


3. SetUp与TearDown

在jasmine中用beforeEach,afterEach,beforeAll,afterAll来表示

describe("A spec using beforeEach and afterEach", function() {
  var foo = 0;

  beforeEach(function() {
    foo += 1;
  });

  afterEach(function() {
    foo = 0;
  });

  it("is just a function, so it can contain any code", function() {
    expect(foo).toEqual(1);
  });

  it("can have more than one expectation", function() {
    expect(foo).toEqual(1);
    expect(true).toEqual(true);
  });
});

4. 自定义断言(matcher)

官网custom_matcher教程

beforeEach(function(){
  jasmine.addMatchers({
    toBeSomeThing: function(){  //定义断言的名字
      return {
        compare: function (actual, expected) {  //compare是必须的
          var foo = actual;
          return { 
               pass: foo === expected || 'something' ,
               message: "error message here"  //断言为false时的信息
          }  //要返回一个带pass属性的对象,pass就是需要返回的布尔值
       
       //negativeCompare: function(actual, expected){ ... }  //自定义not.的用法
        }
      };
    }
  });
});

5. this的用法

每进行一个it测试前,this都会指向一个空的对象。可以利用这一点来共享变量,而不用担心变量被修改

describe("A spec", function() {
  beforeEach(function() {
    this.foo = 0;
  });

  it("can use the `this` to share state", function() {
    expect(this.foo).toEqual(0);
    this.bar = "test pollution?";
  });

  it("prevents test pollution by having an empty `this` created for the next spec", function() {
    expect(this.foo).toEqual(0);
    expect(this.bar).toBe(undefined);  //true
  });
});

6. 闲置测试

describeit前加一个x,变成xdescribe,xit,就可以闲置该测试,这样运行时就不会自动测试,需要手动开始。


7. Spy

功能强大的函数监听器,可以监听函数的调用次数,传参等等,甚至可以伪造返回值,详细可参考官网教程

describe("A spy", function() {
  var foo, bar = null;

  beforeEach(function() {
    foo = { setBar:function(value){bar = value;} };
    spyOn(foo, 'setBar');   //关键,设定要监听的对象的方法
    foo.setBar(123);  
    foo.setBar(456, 'another param');
  });

  it("tracks that the spy was called", function() {
    expect(foo.setBar).toHaveBeenCalled();
  });

  it("tracks that the spy was called x times", function() {
    expect(foo.setBar).toHaveBeenCalledTimes(2);
  });

  it("tracks all the arguments of its calls", function() {
    expect(foo.setBar).toHaveBeenCalledWith(123);
    expect(foo.setBar).toHaveBeenCalledWith(456, 'another param');
  });

  it("stops all execution on a function", function() {
    expect(bar).toBeNull();
  });
});

8. 创建spy

当没有函数需要监听时,也可以创建一个spy对象来方便测试。

describe("A spy, when created manually", function() {
  var whatAmI;

  beforeEach(function() {
    whatAmI = jasmine.createSpy('whatAmI');  //创建spy对象,id='whatAmI'
    whatAmI("I", "am", "a", "spy");  //可以当作函数一样传入参数
  });

  it("is named, which helps in error reporting", function() {
    expect(whatAmI.and.identity()).toEqual('whatAmI');
  });

  it("tracks that the spy was called", function() {
    expect(whatAmI).toHaveBeenCalled();
  });

  it("tracks its number of calls", function() {
    expect(whatAmI.calls.count()).toEqual(1);
  });

  it("tracks all the arguments of its calls", function() {
    expect(whatAmI).toHaveBeenCalledWith("I", "am", "a", "spy");
  });

  it("allows access to the most recent call", function() {
    expect(whatAmI.calls.mostRecent().args[0]).toEqual("I");
  });
});


9. 定时任务测试

jasmine可以模仿js的定时任务setTimeOut,setInterval,并可以通过tick()来控制时间,方便定时任务的测试

  beforeEach(function() {
    timerCallback = jasmine.createSpy("timerCallback");
    jasmine.clock().install();   //关键
  });

  afterEach(function() {
    jasmine.clock().uninstall();  //关键
  });

  it("causes a timeout to be called synchronously", function() {
    setTimeout(function() {
      timerCallback();
    }, 100);

    expect(timerCallback).not.toHaveBeenCalled();

    jasmine.clock().tick(101);  //关键,控制时间进度

    expect(timerCallback).toHaveBeenCalled();
  });

  it("causes an interval to be called synchronously", function() {
    setInterval(function() {
      timerCallback();
    }, 100);

    expect(timerCallback).not.toHaveBeenCalled();

    jasmine.clock().tick(101);
    expect(timerCallback.calls.count()).toEqual(1);

    jasmine.clock().tick(50);
    expect(timerCallback.calls.count()).toEqual(1);

    jasmine.clock().tick(50);
    expect(timerCallback.calls.count()).toEqual(2);
  });

10. 异步测试

传入done参数表示执行异步测试,在beforeEach调用done()表示测试的开始,再次调用done()表示测试结束,否则测试不会结束

describe("Asynchronous specs", function() {
  var value;

  beforeEach(function(done) {   //传入done参数表示执行异步测试
    setTimeout(function() {
      value = 0;
      done();
    }, 1);
  });

  it("should support async execution of test preparation and expectations", function(done) {
    value++;
    expect(value).toBeGreaterThan(0);
    done();
  });

  describe("long asynchronous specs", function() {
    beforeEach(function(done) {
      done();
    }, 1000);  //beforeEach的第二个参数表示延迟执行?

    it("takes a long time", function(done) {
      setTimeout(function() {
        done();
      }, 9000);
    }, 10000);  //jasmine默认等待时间是5s,超出这个时间就认为fail,可以在it的第二个参数设置等待时
   //jasmine.DEFAULT_TIMEOUT_INTERVAL 可以设置全局的等待时间

    afterEach(function(done) {
      done();
    }, 1000);
  });

  describe("A spec using done.fail", function() {
    var foo = function(x, callBack1, callBack2) {
      if (x) {
        setTimeout(callBack1, 0);
      } else {
        setTimeout(callBack2, 0);
      }
    };

    it("should not call the second callBack", function(done) {
      foo(true,
        done,
        function() {
          done.fail("Second callback has been called");  //可以用done.fail()来实现结束测试,但fail的情况
        }
      );
    });
  });
});

11. jasmine配合karma 与 grunt使用

用法就在jasmine搭在karma上实现自动化,再搭在grunt上实现与其他插件集成,方便管理。不过jasmine也可以直接搭在grunt上,所以我不太懂为什么要多个karma? anyway大家都在用,那么就学一下吧。

如果后面执行命令出错,试下换个控制台

karma文档
首先npm init生成package.json
然后安装karma,去到相应的文件夹,命令行中输入
1 npm install -g karma-cli 只有这个全局安装
2 npm install karma --save-dev
3 npm install karma-chrome-launcher --save-dev 用什么浏览器就装什么
4 npm install karma-jasmine --save-dev
5 npm install jasmine-core --save-dev 上面那条命令装不了jasmine-core,这里补上
然后karma init生成karma.conf.js,过程类似生成package.json,全部默认即可,然后手动更改。

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: [
      '*.js'
    ],

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

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
        'src.js':'coverage'  //预处理,检查测试覆盖率
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'coverage'],
    
    coverageReporter:{  //用于检查测试的覆盖率,生成的报告在./coverage/index.html中
        type:'html',
        dir:'coverage',
    },

    // 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_ERROR,

    // 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: ['Firefox'],

    // 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,

    captureTimeout: 5000,  //连接浏览器的超时
  })
}

karma start karma.conf.js 就可以自动运行测试了,并且检测文件的变化。

注意:如果浏览器不是默认安装的路径需要设置路径到环境变量.
cmd: set FIREFOX_BIN = d:\your\path\firefox.exe
$ export CHROME_BIN = d:\your\path\chrome.exe
好像只在当前控制台窗口生效

可以参考该文 Karma和Jasmine自动化单元测试


然后就是搭在grunt上
npm install grunt
npm install grunt-karma
npm install grunt-contrib-watch
配置gruntfile.js

module.exports = function(grunt){
    grunt.initConfig({
        pkg:grunt.file.readJSON('package.json'),
        karma:{
            unit:{
                configFile:'karma.conf.js',
                //下面覆盖karma.conf.js的设置
                background: true,  //后台运行
                singleRun: false,   //持续运行
            }
        },
        watch:{
            karma:{
                files:['*.js'],
                tasks:['karma:unit:run']
            }
        }
    });

    grunt.loadNpmTasks('grunt-karma');
    grunt.loadNpmTasks("grunt-contrib-watch");
    grunt.registerTask('default',['karma','watch']);
}

命令行直接输入grunt就可以弹出浏览器自动监听和测试了,
不知道为什么第一次运行时不能测试,要修改了源码才会开始测试。
更多可看见grunt-kamra官方文档


结语

搬运了官网的教程,有很多地方没说清楚,jasmine还有更多更强大的功能,详细还是要参考官网教程

你可能感兴趣的:(Jasmine单元测试入门)