Angular тестирование с помощью кармы: "модуль не определен"
Я знаю, что этот вопрос задавался много раз, и я знаю, что в большинстве случаев людям не хватает файла angular-mocks.js
.
Я столкнулся с той же проблемой, пытаясь протестировать factory на модуле. К сожалению, я продолжаю сталкиваться с проблемами с тестами (почему, Angular, oh, почему вы должны предполагать объект window
и document
?), В котором указано, что этот модуль не определен. Я в недоумении. Я также пробовал использовать angular.mocks.module, но затем я получаю сообщение о том, что Angular не определен. Что я делаю неправильно?
Следует отметить, что я использую gulp в качестве задачи. Мой gulpfile (еще не идеальный, задачи не связаны):
var gulp = require('gulp'),
uglify = require('gulp-uglify'),
jshint = require('gulp-jshint'),
jasmine = require('gulp-jasmine'),
karma = require('gulp-karma'),
paths = {
scripts: "scripts/*.js",
spec: "spec/*.js",
dist: "dist"
};
gulp.task('prepare', function () {
return gulp.src(paths.scripts)
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(uglify())
.pipe(gulp.dest(paths.dist))
});
gulp.task('test', function () {
gulp.src([paths.scripts, paths.spec])
.pipe(karma({
configFile: 'karma.conf.js',
action: 'run'
}));
});
gulp.task('default', ['prepare', 'test']);
My karma.conf.js, созданный кармой init:
// Karma configuration
// Generated on Fri Mar 14 2014 14:24:30 GMT-0400 (EDT)
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: [
'./lib/angular/angular.min.js',
'./lib/angular-mocks/angular-mocks.js',
'./src/*.js',
'./spec/*.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: false,
// 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
});
};
И наконец, мой тестовый набор (ничего не настроено, если я смогу преодолеть это препятствие, мы будем хорошо):
/* Tests for memento.js. */
describe('memento core test suite', function () {
var memento;
beforeEach(module('Memento'));
beforeEach(function() {
inject(function(_memento_) {
memento = _memento_;
});
});
// Check functions.
// check to see if it has the expected function
it('should match expected interface', function () {
expect(angular.isFunction(memento.canUndo)).toBe(true);
expect(angular.isFunction(memento.canRedo)).toBe(true);
expect(angular.isFunction(memento.undo)).toBe(true);
expect(angular.isFunction(memento.redo)).toBe(true);
expect(angular.isFunction(memento.push)).toBe(true);
});
it('should initialize', function () {
this.fail(Error('Test not implemented'));
});
it('should push() a changed object', function () {
this.fail(Error('Test not implemented'));
});
it('should not push() an unchanged object', function () {
this.fail(Error('Test not implemented'));
});
it('should return original object on undo()', function () {
this.fail(Error('Test not implemented'));
});
it('should return modified object on redo()', function () {
this.fail(Error('Test not implemented'));
});
it('should not undo() if at beginning of stack', function () {
this.fail(Error('Test not implemented'));
});
it('should not redo() if at end of stack', function () {
this.fail(Error('Test not implemented'));
});
// TODO: Implement revert to original, clearing history.
//
// it('should return seed object on revert()', function () {
// this.fail(Error('Test not implemented'));
// });
// it('should clear the stack on clear()', function () {
// this.fail(Error('Test not implemented'));
// });
});
Кто-нибудь видит что-то плохое? Я не уверен, есть ли что-то действительно очевидное, что мне не хватает - я мог бы использовать дополнительный набор глаз или многих. Первоначально я думал, что смогу запустить это как простой набор тестов Jasmine без Karma, но из-за Angular у этого есть проблемы. Если я не могу заставить это работать, я могу просто использовать пакет npm Angular и изменить мой модуль Angular, чтобы он поддерживал CommonJS...
Спасибо, всем! Надеюсь, я не сумасшедший.
Изменить: я включил свои devdependencies.
"devDependencies": {
"gulp": "~3.5.6",
"gulp-uglify": "~0.2.1",
"gulp-jshint": "~1.5.0",
"gulp-jasmine": "~0.2.0",
"angular": "~1.2.10",
"karma": "~0.12.0",
"gulp-karma": "0.0.4",
"karma-jasmine": "~0.2.2",
"karma-chrome-launcher": "~0.1.2"
}
Ответы
Ответ 1
Сообщение о том, что модуль / angular не определен, означает, что ваш файл angular -mocks.js не загружается, несмотря на то, что вы указали его в файле karma.conf.js.
Проблема, с которой вы столкнулись, - это gulp -karma, игнорирующий ваш массив karma.conf.js. Это происходит, когда вы передаете строку или glob в gulp.src в gulpfile.
Чтобы обойти это, передайте gulp.src строку для фиктивного файла, например,.fofoar, и это приведет к тому, что вместо этого будет использован массив файлов в файле karma.conf.js.
gulp.task('test', function () {
gulp.src('./foobar')
.pipe(karma({
configFile: 'karma.conf.js',
action: 'run'
}));
});
Надеюсь, это поможет!
Ссылка:
https://github.com/lazd/gulp-karma/issues/9