Указание зависимостей с помощью gulp-jasmine

У меня есть следующее gulpfile.js:

var gulp = require('gulp'),
    jasmine = require('gulp-jasmine');

gulp.task('default', function () {
    return gulp
        .src('spec/test.js')
        .pipe(jasmine());
});

Код внутри spec/test.js использует глобальный angular переменная, однако, и выдает ошибку о ее неопределенности, когда я запускаю задачу gulp default, Скажем angular определяется в файле spec/lib.jsв глобальном масштабе.

Как мне сказать jasmine() какие зависимости нужно загрузить сначала в глобальную область видимости перед запуском describe()внутри test.js? Другими словами, как мне сказать jasmine() загрузить spec/lib.js во-первых, прежде чем он запускает тесты?

1 ответ

Вы пробовали карму?

КАРМА ЛИНК

Если вы используете карму, жасмин и глоток, что я и делаю, вы можете настроить тестирование следующим образом

В gulpfile.js

var gulp = require('gulp');
var karma = require('karma').server; // Note the server property here.

gulp.task('karma', function (done) {
  karma.start({
    configFile: __dirname + '/karma.conf.js'
  }, done);
});

Вам нужно будет импортировать ng-html2js для угловых шаблонов

npm install ng-html2js

В karma.config.js (необходимо создать)

module.exports = function(config) {

  config.set({

  // base path that will be used to resolve all patterns (eg. files, exclude)
  basePath: '',

  frameworks: ['jasmine'],

  files: setFilesUpForTesting(),

  // list of files to exclude during testing. CHANGE THIS TO YOURS!!!
  exclude: [
    'public/js/boot.js',
    'public/js/socket.io.js'
    // 'yourRootPath/folder/stuff.js
  ],

  // NOTE THE NG-HTML2JS preprocessor you will need via NPM.    
  preprocessors: {
    // CHANGE TO YOUR PATH for all HTML PARTIALS.
    'public/directives/**/partials/*.html': 'ng-html2js',
    'public/directives/**/*.js': ['coverage']
  },

  ngHtml2JsPreprocessor: {
    stripPrefix:'public',
    moduleName: 'templates'
  },

  reporters: ['progress', 'coverage'],

  coverageReporter: {
    type : 'html',
    dir : 'coverage/'
  },

  port: 9876,

  colors: true,

  // 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
  });
};

// ------------------------------------------------------------------ >
// Below code is for running either single or all test files.
// To run a single test, just pass in the test file name like so...

// If the test file name was rs-test-me-now_spec.js
// To spool up Karma you would enter

// gulp karma --single-test=rs-test-me-now  <note the proceeding double hyphen>
// To just run all tests
// gulp karma

// CHANGE THE FILE PATHS BELOW!!!!!

var fixedPath = [
  'public/js/jquery.js',
  'public/js/jquery-ui.min.js',
  'public/js/foundation.min.js',
  'public/js/angular.min.js',
  'public/js/angular-mocks.js',

];

var baseTestPath = 'public/test/'; // CHANGE THIS TO YOUR ROOT PATH!!!

function setFilesUpForTesting(){
  fixedPath.push( testPath());
  return fixedPath;
}

function testPath(){
  return singleTestPath() || fullTestPath();
}

function fullTestPath(){
  return  'public/test/**/*_spec.js'; // CHANGE THIS TO YOUR SPEC FOLDER!!!
  // like rootFolder/somethinghere/spec/**/*_spec.js
  // note the underscore that proceeds the spec.js. Get rid of if you file name does not have it.
}

function singleTestPath(){
  var passedArgument = process.argv.filter(function(item){ if(/--single-test=/.test(item)){return item; }});
  if( isEmpty( passedArgument )){ return false; }
  return baseTestPath + '**/*' + fileName( passedArgument ) + '_spec.js';
}

function fileName( argument ){
  if( !argument ){ return; }
  return argument[0].replace('--single-test=', '');
}

function isEmpty( array ){
  return array.length === 0;
}

------------------- END KARMA.CONFIG.js file ----------------------

Теперь для запуска тестов

// To run all tests
gulp karma

// To run one single file test
gulp karma --single-test=rs-test-me-now

ПРИМЕЧАНИЕ: если вы не можете сразу заставить его работать, дайте мне знать, и мы это сделаем. Возможно, я что-то пропустил. Мои тестовые файлы называются нечто_test.js, а не нечто_spec.js. Я изменил код для создания _spec.js. Кроме того, вы должны убедиться, что вы включили все файлы, необходимые для запуска Angular. Я привел несколько примеров в моем karma.config.js. Я бегу Angular, а также.

Препроцессор (ng-html2js) компилирует угловые шаблоны для директив. Вы должны установить его в свой package.json.

Другие вопросы по тегам