如果你使用 requirejs,你有很多事情要做。
首先,您必须将karma-requirejs
插件放入您的package.json
"karma-requirejs": "~0.1.0",
然后你必须改变你的配置文件。您必须添加部分然后排除您的requirejs
要求frameworks
main.js
然后通过配置添加所有库文件,pattern
而不是include
它
您必须添加您的要求main-test.js
(用于测试的配置文件在底部描述)
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'requirejs'],
files: [
{pattern: 'app/bower_components/jquery/jquery.min.js', included: false},
{pattern: 'app/bower_components/angular/angular.min.js', included: false},
{pattern: 'app/bower_components/angular-resource/angular-resource.min.js', included: false},
{pattern: 'app/bower_components/angular-mocks/angular-mocks.js', included: false},
{pattern: 'app/scripts/*.js', included: false},
{pattern: 'app/scripts/**/*.js', included: false},
{pattern: 'test/spec/**/*Spec.js', included: false},
'test/main-test.js'
],
exclude: ['app/scripts/main.js'],
port: 8082,
logLevel: config.LOG_DEBUG,
autoWatch: false,
browsers: ['Chrome'],
singleRun: false
});
};
现在创建你的main-test.js
.
您必须获取所有测试文件以将其作为依赖项。
然后做一个经典的 requirejs 配置(注意在baseUrl
我们使用/base
karma 常量),最后通过代码启动 karma:window.__karma__.start();
例子 :
var tests = [];
for (var file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if (/Spec\.js$/.test(file)) {
tests.push(file);
}
}
}
require.config({
// Karma serves files from '/base'
baseUrl: '/base/app/scripts',
paths: {
jquery: '../bower_components/jquery/jquery.min',
angular: '../bower_components/angular/angular.min',
angularMocks: '../bower_components/angular-mocks/angular-mocks',
ngResource: '../bower_components/angular-resource/angular-resource.min'
},
shim: {
jquery: {
exports: '$'
},
angular: {
deps: [ 'jquery', 'bootstrap'],
exports: 'angular'
},
ngResource: {
deps: [ 'angular' ],
exports: 'ngResource'
},
angularMocks: {
deps: [ 'ngResource' ],
exports: 'angularMocks'
}
},
priority: [
'angular'
],
// ask Require.js to load these files (all our tests)
deps: tests
});
require(tests, function(){
window.__karma__.start();
});
在您的测试文件中:
更改beforeEach(angular.module('myApp'));
为beforeEach(module('myApp'));
像这样更改定义的参数:
define(['angular',
'myApp',
'angularMocks',
'MyCtrl'
], function(angular, myApp, angularMocks, MyCtrl)
要注入控制器,只需执行此操作(您必须将MyCtrl
in 参数放入 require 函数):
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
$controller(MyCtrl, {
$scope: scope
});
}));
最后:
it('should call crudListMethods', function () {
expect(scope.test).toBe("sth");
});
现在它应该工作了!希望能帮助到你 !