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还有更多更强大的功能,详细还是要参考官网教程