我正在尝试在我们的传统AngularJS应用程序上设置单元测试。我使用标准业力和angular-mock来设置测试用例。但是当我尝试注入一些服务和工厂时,我遇到了Unknown provider
的问题。我的karma.conf看起来像这样(为了简洁,我删除了很多东西)
module.exports = function(config) { config.set({
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: [
'./node_modules/angular/angular.js',
"http://cf._____.com/content/myfootprints/js/priorityqueue.js",
"http://cf._____.com/content/myfootprints/js/ng-flow-standalone.js",
INCLUDED ALL THE DEPENDENCIES HERE
'./node_modules/angular-mocks/angular-mocks.js',
'./static/js/app/main.js',
'./static/tests/**/*.js'
]
preprocessors: {
'./static/js/app/**/main.js':['webpack', 'sourcemap'],
'./static/js/app/**/*.js':['webpack', 'sourcemap'],
},
在我们的应用程序中,我们有一个main.js,它使用imports
和requireDir
将所有控制器和工厂导入应用程序。它看起来像这样
const requireDir = require('webpack-requiredir');
import './isocurrency.js';
import './myfp_uirouter.js';
import './infobubble.js';
// other imports
requireDir(require.context('./controllers', true, /.*\.js$/))
requireDir(require.context('./directives', true, /.*\.js$/))
requireDir(require.context('./factories', true, /.*\.js$/))
requireDir(require.context('./filters', true, /.*\.js$/))
我有一个单元测试文件看起来像这样
describe('Unit test file, function(){
var generalUtilFactory;
beforeEach(inject(function($injector){
generalUtilFactory = $injector.get('generalUtilsFactory'); <--- getting unknown provider
// Also tried to inject it in
//via function($rootScope,... _generalUtilFactory_)
}));
Other code
.
.
.
.
});
现在我有通过main.js导入的一般工厂工厂,并在app模块中注册。我检查过在调试器中看到它。看起来像这样
angular.module('app').factory('generalUtilsFactory', ['$timeout', '$filter', 'FileSaver', 'Blob', function($timeout, $filter, FileSaver, Blob) {
var generalUtilsFactory = {};
generalUtilsFactory.getKeys = function(o){
我不太清楚这里发生了什么。已包含所有需要的文件,并且所有es6都已正确转换。我们将不胜感激
我认为你需要在注入服务之前注入主模块。也许做这样的事情会有所帮助:
describe('Service Tests', function () {
beforeEach(module('app'));
var _generalUtilsFactory;
beforeEach(inject(function (generalUtilsFactory) {
_generalUtilsFactory = generalUtilsFactory
}));
});