angularjs自动化测试系列之karma

时间:2021-07-09 03:57:54

angularjs自动化测试系列之karma

karma test with jasmine

更好的利用工具是为了让生活更美好。

需要安装的东西:

npm install karma -g

mkdir karma-test
cd karma-test npm init npm install -g jasmine --save-dev
npm install -g jasmine-core --save-dev
npm install -g karma-jasmine --save-dev karma init
//生成器向导,一路Enter

代码结构

D:.
│ karma.conf.js
│ package.json

├─js
│ │ home.js
│ │
│ └─plugin
│ angular-mocks.js
│ angular.js

└─tests
home.tests.js

代码

D:\GitHub\karma_test\package.json

// Karma configuration
// Generated on Mon Nov 07 2016 12:51:05 GMT+0800 (中国标准时间) 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/plugin/angular.js",
"js/plugin//angular-mocks.js",
"js/*.js",
"tests/*.tests.js"
], // list of files to exclude
exclude: [
], // 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
})
}

D:\GitHub\karma_test\js\home.js

'use strict';
var app = angular.module('netsos.cnblogs.com',[]);
app.controller('Hevily',['$scope',function($scope){
$scope.text = 'hello';
}]);

D:\GitHub\karma_test\tests\home.tests.js

'use strict';
describe('Hevily',function(){
var scope;
//module都是angular.mock.module的缩写
beforeEach(module('netsos.cnblogs.com'));
//inject都是angular.mock.inject的缩写
beforeEach(inject(function($rootScope,$controller){
scope = $rootScope.$new();
$controller('Hevily',{$scope:scope});
}));
it('text = hello',function(){
expect(scope.text).toBe('hello');
});
});

运行测试

karma start karma.conf.js

结果

angularjs自动化测试系列之karma

angularjs自动化测试系列之karma

github

Demo 代码下载 https://github.com/wancy86/karma_test

Reference

http://www.tuicool.com/articles/aemI7b6

http://www.cnblogs.com/NetSos/p/4371075.html