1.npm安装Karma:
# Install Karma:
$ npm install karma
# Install plugins that your project needs:
$ npm install karma-jasmine karma-chrome-launcher karma-cli
2.初始化配置Karma
$ karma init karma.require.config.js
Which testing framework do you want to use ?
press tab to list possible options. Enter to move to the next question.
> jasmine
Do you want to use Require.js ?
This will add Require.js plugin.
Press tab to list possible options. Enter to move to the next quesstion.
> yes
Do you want to capture any browsers automatically ?
Press tab to list possible options. Enter empty string to move to the next question.
> Chrome
What is the location of your source and test files ?
You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".
Enter empty string to move to the next question
>
Should any of the files included by the previous patterns be excluded ?
You can use glob patterns, eg. "**/*.swp".
Enter empty string to move to the next question.
>
Do you wanna generate a bootstrap file for RequireJS?
This will generate test-main.js/coffee that configures RequireJS and starts the tests.
> yes
Do you want Karma to watch all the files and run the tests on change ?
Press tab to list possible options.
> yes
3.修改生成的karma.require.config.js配置文件
// Karma configuration
// Generated on Thu Jul 23 2015 14:14:03 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', 'requirejs'],
// list of files / patterns to load in the browser
files: [
{pattern: './bower_components/angular/angular.js', included: false},
{pattern: './bower_components/angular-cookies/angular-cookies.js', included: false},
{pattern: './bower_components/angular-resource/angular-resource.js', included: false},
{pattern: './bower_components/angular-sanitize/angular-sanitize.js', included: false},
{pattern: './bower_components/angular-mocks/angular-mocks.js', included: false},
{pattern: './modules/*/*/*.js', included: false},
{pattern: './test/*/*.js', included: false},
{pattern: './test/*.js', included: false},
{pattern: './test-main.js', included: true},
],
// 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
})
}
4.修改test-main.js文件
var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;
// Get a list of all the test files to include
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
// If you require sub-dependencies of test files to be loaded as-is (requiring file extension)
// then do not normalize the paths
var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');
allTestFiles.push(normalizedTestModule);
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base',
paths: {
'angular': 'bower_components/angular/angular',
'angular-cookies': 'bower_components/angular-cookies/angular-cookies',
'angular-sanitize': 'bower_components/angular-sanitize/angular-sanitize',
'angular-resource': 'bower_components/angular-resource/angular-resource',
'angular-mocks': 'bower_components/angular-mocks/angular-mocks',
'lib': 'test/base/lib',
'app': 'test/app'
},
shim: {
'angular': {'exports': 'angular'},
'angular-cookies': ['angular'],
'angular-sanitize': ['angular'],
'angular-resource': ['angular'],
'angular-mocks': ['angular']
},
// dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
5.编写测试文件
lib.js
define(
[
'angular',
'angular-cookies',
'angular-sanitize',
'angular-resource',
'angular-mocks'
], function (angular) {
var ApplicationConfiguration = (function () {
// Init module configuration options
var applicationModuleName = 'DemoApplicaton';
var applicationModuleVendorDependencies = ['ngResource', 'ngCookies', 'ngSanitize', 'ngMock'];
})();
return {
angular: angular,
ApplicationConfiguration: ApplicationConfiguration
}
test.js
define(
[
'lib',
'app'
],
function (Lib, app) {
//先把angular通过调用bootstrap启动起来。
app();
var angular = Lib.angular,
ApplicationConfiguration = Lib.ApplicationConfiguration;
describe("login unit test case", function () {
var = LoginService,
httpBackend,
scope;
beforeEach(function () {
module(ApplicationConfiguration.getApplicationModuleName());
module('login');
});
beforeEach(inject(function ($injector, $httpBackend) {
LoginService= $injector.get('LoginService');
scope = $injector.get('$rootScope');
spyOn(scope, '$broadcast').and.callThrough();
httpBackend = $httpBackend;
httpBackend.when('POST', '/login.action').respond({
access: {
token: {
id: 'test'
},
user: {}
}
});
}));
it('broadcast should send login.success event', function () {
LoginService.login({
usr: 'admin',
pwd: '123'
});
httpBackend.flush();
expect(scope.$broadcast).toHaveBeenCalledWith('login.success');
});
});
});