Running grunt with mochaProtractor specifying dependancies?? chai assertion library? - gruntjs

I've set up a gruntfile that looks like the following. The aim being to perform e2e tests using protractor for my angularjs project. When running this using mochaProtractor Chrome fires up as expect but the lint is telling me that I'm missing the dependancies for the expect statement. This should referencing the assertion library chai. How do I include dependencies for chai to get this to work correctly?
Thanks
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
watch: {
scripts: {
files: ['public/specs/e2e/*.js'],
tasks: ['mochaProtractor','jshint'],
options: {
spawn: false,
},
},
},
jshint: {
all: [
'Gruntfile.js',
'public/app/js/*.js'
],
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
unused: true,
boss: true,
eqnull: true,
node: true
}
},
mochaProtractor: {
options: {
browsers: ['Chrome']
},
files: ['public/specs/e2e/*.js'],
baseUrl: 'http://localhost:3000/'
},
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-mocha-protractor');
Below is the spec I'm trying to test against. Note: I added the require statement at the top in attempt to get it to work. Any thoughts?
var chai = require('chai');
var expect = chai.expect;
describe("Given a task entry screen", function() {
ptor = protractor.getInstance();
beforeEach(function() {
ptor.get('#/');
button = ptor.findElement(protractor.By.className('btn-say-hello'));
button.click();
});
it('says hello', function() {
message = ptor.findElement(protractor.By.className('message'));
expect(message.getText()).toEqual('Hello!');
});
});

You have to add chai as a dev dependency in your package.json.
{
"name": "yourProject",
"devDependencies": {
"chai": "~1.8.1"
}
}
then install the dependenvy via
npm install`
and then you should be able to write a spec :
var chai = require('chai');
var expect = chai.expect;
describe("Given a task entry screen", function() {
ptor = protractor.getInstance();
beforeEach(function() {
ptor.get('#/');
button = ptor.findElement(protractor.By.className('btn-say-hello'));
button.click();
});
it('says hello', function() {
message = ptor.findElement(protractor.By.className('message'));
expect(message.getText()).toEqual('Hello!');
});
});

Related

Grunt Livereload to reload just the styles

Added "grunt-contrib-livereload": "^0.1.2" to sass compile grunt config. Yes, it's reloading, but the whole DOM. Magento 2 native config reloader reloading just the styles, not page reload. How I can setup grunt in this way?
Thanks
module.exports = function (grunt) {
const sass = require('node-sass');
const timer = require('grunt-timer');
require('time-grunt')(grunt);
require('load-grunt-tasks')(grunt);
timer.init(grunt, { deferLogs: true, friendlyTime: false, color: "blue" });
grunt.initConfig({
notify_hooks: {
options: {
enable: true,
title: 'Task Completed',
max_jshint_notifications: 5,
},
uncss: {
options: {
title: 'Task Completeddd',
message: "Error occured",
},
},
},
sass: {
dist: {
options: {
implementation: sass,
sourceMap: true,
message: "Less task complete"
},
files: {
'../../../../../pub/static/frontend/Laf/v1/en_US/css/quickview.css': 'styles/quickview.scss',
'../../../../../pub/static/frontend/Laf/v1/en_US/css/locations.css': 'styles/locations.scss',
}
}
},
watch: {
files: ['styles/*.scss', 'Magento_Cms/styles/*.scss'],
tasks: ['sass'],
options: {
livereload: true,
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-notify');
grunt.task.run('notify_hooks');
grunt.registerTask('default', ['sass', 'notify', 'livereload']);
};

Grunt: override properties of a task, from arguments of another

html-build` and I'm trying to pass custom properties of it's config from a custom task that I'm creating.
This is my current code:
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
htmlbuild: {
dist: {
src: 'template.html',
dest: 'tests/',
options: {
beautify: true,
scripts: {
mocha: [
'assets/scripts/mocha/mocha.min.js',
'assets/scripts/mocha/chai.min.js',
]
},
styles: {
mocha: [
'assets/css/mocha.min.css'
]
}
}
}
}
});
grunt.registerTask('js-test', 'Generate JS test', function(scripts, tests) {
var htmlBuildScripts = grunt.config.get('htmlbuild.dist.options.scripts');
htmlBuildScripts.scripts = [scripts];
htmlBuildScripts.tests = [tests];
grunt.config.set(htmlBuildScripts, htmlBuildScripts);
grunt.task.run('htmlbuild');
});
Right now when I run in the CMD
js-test:assets/scripts/graphicUnitsConvert.js:assets/tests/graphicUnitsConvertTest.js
I get this warning Warning: str.replace is not a function
I found the answer
grunt.registerTask('js-test', 'Generate JS test', function(scripts, tests) {
grunt.config.set('htmlbuild.dist.options.scripts.scripts', [scripts.toString()]);
grunt.config.set('htmlbuild.dist.options.scripts.tests', [tests.toString()]);
grunt.task.run('htmlbuild');
});

livereload fired but does not reload page when changes are generated by contrib-copy or tinyimg in destination (!)

Here is my problem.
All mentioned paths as per below gruntfile.js are watched fine (shown in grunt --verbose -v). Livereload fires whenever I change files (at least --verbose shows livereload fires). But the page is live reloaded ONLY in case I change my /development/index.html (in Sublime Text) or /less/mainpage.less (with contrib-less).
If I change development/img//* or anyting in /test//*, livereload FIRES but do not RELOAD my page.
I would really appreciate if someone could help.
Here is my folder structure:
source location root: /development/
destination location root: /test/
Here is my gruntfile.js:
module.exports = function(grunt) {
grunt.initConfig({
watch: {
livereload: {
files: ['development/*.html', "test/**/*", "development/img/**/*"],
options: {
livereload: true,
spawn: false
}
},
// watch tasks start here
scripts: {
files: ['development/js/**/*.js'],
tasks: ['concat']
},
html: {
files: ['development/*.html'],
tasks: ['copy:html']
},
less_compile: {
files: ['development/a_source/less/**/*.less'],
tasks: ['less', "stripCssComments"]
},
images: {
files: ['development/img/**/*'],
tasks: ['tinyimg']
}
},
// runs local server for livereload
connect: {
sever: {
options: {
hostname: 'localhost',
port: 3000,
base: 'test/',
livereload: true
}
}
},
// *** *.html, *.img copy task here
copy: {
html: {
expand: true,
cwd: 'development',
src: '*.html',
dest: 'test/',
}
},
// *** LESS tasks here
less: {
compile: {
options: {
paths: ["development/b_components/less/"]
},
files: {
"temp/css/style.css": "development/a_source/less/style.less"
}
}
}, // compiles less and put compiled version into /temp/css/style.test
stripCssComments: {
dist: {
files: {
'test/css/style.css': 'temp/css/style.css'
}
}
}, // strips comments from /temp/css/style.css and copies it to /test/
// minify images
tinyimg: {
dynamic: {
files: [{
expand: true, // Enable dynamic expansion
cwd: 'development/img/', // Src matches are relative to this path
src: ['**/*.{png,jpg,gif}'], // Actual patterns to match
dest: 'test/img/' // Destination path prefix
}]
}
}
}); //initConfig
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-strip-css-comments');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-tinyimg');
grunt.registerTask('default', ["connect", "watch"]);
}; //wrapper function
Try this
livereload:{
options:{
livereload:'<%= connect.options.livereload %>'
},
files:[
'app/{,*/}*.html',
'app/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
This should reload if you make changes in your images folder. (Customize the URL according to your structure.)
OK. I just wanted to wrap up after I solved all my problems.
I arrived at the following acceptably working setup:
- as per above: Grunt serves as only "files" worker doing all compile / concat / copy etc.
work.
- browser-sync is my local server (with bunch of other vital capabilities) and fast livereload tool, that additionally syncs
several open test windows (https://browsersync.io/).
- Divvy: great addition to my workflow capable of arranging windows on the desktop on the fly (http://mizage.com/divvy/).
Update:
Soon after I switched to Gulp + Browsersync. I could not be satisfied more. Gulp works roughly 10 times faster and Browsersync is smooth and convenient.
Here is my gulpfile.js example just to demonstrate the tasks this pair manages for me:
var gulp = require("gulp"),
gutil = require("gulp-util"),
less = require('gulp-less'),
concat = require('gulp-concat'),
browserify = require('gulp-browserify'),
browserSync = require('browser-sync').create(),
gulpcopy = require('gulp-copy'),
newer = require('gulp-newer'),
imagemin = require('gulp-imagemin'),
autoprefixer = require('gulp-autoprefixer'),
uglifyjs = require('gulp-uglify'),
cleanCSS = require('gulp-clean-css'),
uglifycss = require('gulp-uglifycss'),
htmlmin = require('gulp-htmlmin'),
htmlhint = require("gulp-htmlhint"),
htmlv = require('gulp-html-validator'),
validatecss = require('gulp-w3c-css'),
sourcemaps = require('gulp-sourcemaps');
var lessMain = ["src/styles/less/styles.less"],
lessSources = ["src/styles/less/*.less", "src/styles/**/*.css"],
jsSources = "src/js/*.js",
jsonSources = ["src/js/*.json"],
htmlSources = ["src/html/*.html"],
imgSources = ["z_design/images/processed/**/*.*"],
imgDest = ["public/img/**/*.*"],
cssTemp = ["src/temp/css/styles.css"],
srcjQuery = "node_modules/jquery/dist/jquery.min.js",
srcMustache = "node_modules/mustache/mustache.min.js";
gulp.task("message", function() {
gutil.log("============= Gulp script started ==============");
});
// compiling less
gulp.task("less-compile", function() {
gulp.src(lessMain)
// switches sourcemaps on/off
.pipe(sourcemaps.init())
.pipe(less()
.on("error", gutil.log))
// switches sourcemaps on/off
.pipe(sourcemaps.write())
// change .dest("folder") to "public/css"
// to make no-autoprefix
// or to "src/temp/css/" to switch autoprefix on
.pipe(gulp.dest("public/css"))
});
// prepare & copy js files
gulp.task("js", function() {
gulp.src([srcjQuery, srcMustache, jsSources])
.pipe(concat("script.js"))
.pipe(gulp.dest("public/js/"))
});
// .pipe(browserify())
// {bundleExternal: false}
// copy JSON files
gulp.task("copyjson", function() {
gulp.src(jsonSources)
.pipe(newer("public/js/"))
.pipe(gulpcopy("public/js/", {
prefix: 2
}))
});
// copy html files
gulp.task("copyhtml", function() {
gulp.src(htmlSources)
.pipe(newer("public/"))
.pipe(gulpcopy("public/", {
prefix: 2
}))
});
// --- minify & compress images: 2 tasks - auto and manual
// minify & copy images - manual task
gulp.task("img-ondemand", function() {
gulp.src("z_design/images/unprocessed/**/*.*")
.pipe(newer("public/img/"))
.pipe(imagemin({
progressive: true
}))
.pipe(gulp.dest('z_design/images/processed/'))
});
// minify & copy images - automatic task
gulp.task("processimages", function() {
gulp.src(imgSources)
.pipe(newer("public/img/"))
.pipe(imagemin({
progressive: true
}))
.pipe(gulp.dest('public/img/'))
});
// --- end
// forced reload
gulp.task("reload", function() {
browserSync.reload();
});
// autoprefixer
gulp.task("autoprefix", function() {
gulp.src(cssTemp)
.pipe(autoprefixer({
browsers: ['last 3 versions', 'safari 5', 'ie 8', 'ie 9', 'ie 10', "ie11", 'opera 12.1', 'ios 6', 'android 4'],
cascade: false
}))
.pipe(gulp.dest("public/css/"))
});
// watching for changes
gulp.task("watch", function() {
gulp.watch(lessSources, ["less-compile"])
gulp.watch(jsSources, ["js"])
gulp.watch(jsonSources, ["copyjson"])
gulp.watch(htmlSources, ["copyhtml"])
gulp.watch(imgSources, ["processimages"])
gulp.watch(imgDest, ["reload"])
gulp.watch("src/temp/css/styles.css", ["autoprefix"])
});
// serving localhost
gulp.task('browser-sync', function() {
browserSync.init({
server: ["public", "src"],
watchTask: true,
open: false,
files: ["public/*.html", "public/css/*.css", "public/js/*.*",
"public/img/**/*.*"]
});
});
// === production preparations: RUN SEPARATE TASKS ON DEMAND ===
// --- minify & compress HTML, CSS, JS
// uglify JS
gulp.task("compress-js", function() {
gulp.src("public/js/script.js")
.pipe(uglifyjs())
.pipe(gulp.dest('public/js/'))
});
// uglify CSS
gulp.task('uglify-css', function() {
gulp.src('public/css/styles.css')
.pipe(uglifycss({
"debug": true,
"uglyComments": true
}))
.pipe(gulp.dest('public/css/'));
});
// compress HTML
gulp.task('compress-html', function() {
return gulp.src('src/html/*.html')
.pipe(htmlmin({
collapseWhitespace: true,
removeComments: true
}))
.pipe(gulp.dest('public/'));
});
// --- lint HTML and validate CSS
// lint html
gulp.task('lint-html', function() {
gulp.src("public/*.html")
.pipe(htmlhint())
.pipe(htmlhint.reporter())
});
// validate html
// Option format set to html
gulp.task('validate-html', function() {
gulp.src('public/*.html')
.pipe(htmlv({
format: 'html'
}))
.pipe(gulp.dest('src/temp/validation/'));
});
// add css validation
gulp.task('validate-css', function() {
gulp.src('public/css/*.css')
.pipe(validatecss())
.pipe(gulp.dest('src/temp/validation/'));
});
gulp.task("validate", ["validate-html", "validate-css", "lint-html"]);
gulp.task("compress", ["compress-js", "uglify-css", "compress-html"]);
gulp.task("default", ["watch", "browser-sync"]);
// =======================

CSS version numbers with Grunt

I am using Grunt with php and am using a package to version my css with a date stamp as style.min.20160913230349.css.
However how do I find a package that will update the new string to the header in my php page. style.min.{grunt_this_string}.css.
I'm looking a usemin but can't see how I could implement it.
<link rel="stylesheet" media="all" href="/css/style.min.20160913230349.css" type="text/css"/>
Gruntfile.js
module.exports = function (grunt) {
grunt.initConfig({
/*=============================================
= Proxy server =
=============================================*/
php: {
dist: {
options: {
hostname: 'sau.dev',
base: 'website-v2', // Project root
keepalive: false,
open: false
}
}
},
browserSync: {
dev: {
bsFiles: {
src: [
'website-v2/*.php',
'website-v2/*/*.php',
'website-v2/css/*.css'
]
},
options: {
proxy: 'sau.dev',//<%= php.dist.options.hostname %>:<%= php.dist.options.port %>
ghostMode: {
clicks: false,
forms: false,
scroll: true
},
logLevel: 'info',//client
logConnections: true,
watchTask: true,
open: 'ui',
xip: true,
}
}
},
watch: {
html: {
files: ['src/*.html'],
}
},
cssmin: {
dist: {
files: {
'website-v2/css/style.min.css': ['website-v2/css/all.css']
}
}
},
uglify: {
dist: {
files: {
'website-v2/js/main.min.js': ['website-v2/js/jquery- 1.9.1.min.js','jquery-ui.min.js','main.js','featherlight.js']
}
}
},
assets_versioning: {
options: {
tag: 'date',
dateFormat: 'YYYYMMDDHH',
timezoneOffset: 10
},
dist: {
options: {
tasks: ['cssmin:dist']
}
},
},
});
//grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-browser-sync');
grunt.loadNpmTasks('grunt-php');
grunt.loadNpmTasks('grunt-assets-versioning');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-string-replace');
//grunt.loadNpmTasks('usemin');
//Static Server
grunt.registerTask('dist', ['versioning']);
//Proxy Server
grunt.registerTask('server', ['php:dist','browserSync','watch']);
};
After understand your problem, I think that you need to create a assets.map
You need to add this in gruntfile.js.
options: {
...
versionsMapFile: 'assets.json',
...
}
I would like to believe that grunt-assets-versioning create a version taken the date.
You need to replace in your html with the version that provide assest.json.
I recommend to use grunt-string-replace for this.
replace: {
dist: {
options: {
patterns: [
{
match: 'style.min.css',
replacement: replacement()
}
]
},
files: [
{src: ['src/assets/index.html'], dest: 'build/index.html'}
]
}
}
...
grunt.registerTask('versioning', ['assets_versioning']);
grunt.registerTask('replace', ['string-replace']
...
function replacements() {
var projectFile = "assets.json";
if (!grunt.file.exists(projectFile)) {
grunt.log.error("file " + projectFile + " not found");
return true;//return false to abort the execution
}
var project = grunt.file.readJSON(projectFile);//get file as json object
var version = project[0].version;
var replace = ''
// continue with the algorithm that you need
return replace;
}
I hope that helps.

Getting grunt karma to run one unit test

I was wondering if anyone has got grunt karma to run just one spec that is changed on watch. This is my config below. The problem is that the line grunt.config('karma.unit.options.files', filepath); doesn't seem to be doing anything as all the specs still get run however foo does get output before the karma:unit:run gets fired.
grunt.initConfig({
karma: {
unit: {
configFile: 'karma.conf.js',
background: true,
singleRun: false,
options: {
files: allFilesArray
}
}
},
watch: {
options: {
spawn: false,
livereload: true
},
karma: {
files: ['js/spec/**/*.spec.js', 'js/src/**/*.js'],
tasks: ['karma:unit:run']
}
}
})
grunt.event.on('watch', function (action, filepath){
console.log('foo');
grunt.config('karma.unit.options.files', filepath);
});
Is there anyone out there who has achieved running one spec in the terminal on file change? We have thousands of tests so it is starting to get slow.
Thanks,
Alex
I got this to work. Basically, you use watch with an event handler to dynamically change the karma config whenever a file changes. Here's the rundown:
My Grunt config has two karma tasks: "all" and "one". "all" runs all of them, and "one" only runs a single file which it does not know beforehand.
grunt.initConfig({
// ...
karma: {
all: {
configFile: 'karma.conf.js',
browsers: ['PhantomJS'],
singleRun: true,
options: {
files: [
'bower_components/jquery/dist/jquery.js', // dependencies
'src/js/**/*.js', // js source files
'src/js/**/*.spec.js' // unit test files
]
}
},
one: {
configFile: 'karma.conf.js',
browsers: ['PhantomJS'],
singleRun: true,
files: [
{src: 'bower_components/jquery/dist/jquery.js'}, // dependencies
{src: ['src/js/**/*.js','!src/js/**/*.spec.js']} // source files
// (exclude the unit test files)
// watchEventListener will add the unit test file to run
]
}
},
// ...
});
And then later in my gruntfile, I add a listener for watch events. This listener updates the karma:one task and adds the unit test file. We keep a copy of the original files array, or else our additions would persist and accumulate through the lifetime of the watch task.
// when a unit test changes, execute only it
var original_karmaOne_files = grunt.config.get('karma.one.files'); // keep the original files array
grunt.event.on('watch', function watchEventListener(action, filepath, target){
// this handler handles ALL watch changes. Try to filter out ones from other watch tasks
if (target == 'js_spec') handleJSHintSpec();
// ---------------------
function handleJSHintSpec() {
if (action == 'deleted') return; // we don't need to run any tests when a file is deleted
// this will probably fail if a watch task is triggered with multiple files at once
// dynamically change the config
grunt.config.set('karma.one.files', [].concat(original_karmaOne_files, [{src: filepath}]));
}
});
And here is my gruntfile's watch task:
watch: {
// ...
// when js spec files change,
// lint them
// run unit tests
js_spec: {
options: {
interrupt: true
},
files: 'src/js/**/*.spec.js',
tasks: ['jshint:js_spec', 'karma:one']
},
// ...
}
My karma.conf.js file is pretty default, but its files array is empty. Actually, I commented it out, so the property is undefined.
// list of files / patterns to load in the browser
//files: [], // specified in the gruntfile
TL; DR: Use karma:unit everywhere instead of karma:unit:run and use grunt.event.on('watch', function(){}); to edit the karma config to only include the test files you want to run.
I have this working, but it might not be what you want. I'm starting the server up again every time I save a file. Further explanation is below. Here is some of the config:
watch: {
tests: {
files: 'tests/**/*.js',
tasks: ['karma:unit']
},
tsChanged: {
files: config.tsFiles,
tasks: [
'ts',
'karma:unit'
]
}
}
grunt.event.on('watch', function(action, filepath){
grunt.config(['karma', 'unit', 'files'], [{
src: [
path/to/your/source/files,
path/to/your/test/file,
]
}]);
});
It seems to me that karma loads all of the app files and the test files into the browser whenever it starts the server. In your case, that would be when you enter "grunt karma:unit:start watch" into the command line. So here, I used "grunt watch" and just added a "karma:unit" to the process. Then I caught the save event and updated the karma config before it started up the server.
Hope this helps.
Using a combination of yargs and some runtime-magic, I do this:
var argv = require('yargs')
.default('t', '*.js')
.alias('t', 'tests')
.describe('t', 'A file or file pattern of the test files to run, relative to the test/unit dir')
.help('?')
.alias('?', 'help')
.argv;
var filesToLoad = ['src/**/*.js', 'test/unit/helpers/*.js'];
filesToLoad.push(path.join('test/unit/**', argv.t));
gulp.task('tdd', function (done) {
karma.start({
configFile: __dirname + '/../../karma.conf.js',
jspm: {
loadFiles: filesToLoad,
}
}, function(e) {
done();
});
});
Which takes a test file / path pattern as an argument to gulp and loads that in preference to all the files.
Based on the answer of Matthias and the comments my Grundfile.js is:
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
karma: {
all: {
configFile: 'karma.conf.js',
background: true,
files: [
{ src: './Leen.Managementsystem/bower_components/jquery/dist/jquery.js' },
{ src: './Leen.Managementsystem/bower_components/globalize/lib/globalize.js' },
{ src: './Leen.Managementsystem/bower_components/**/*.js', included: false },
{ src: './Leen.Managementsystem.Tests/App/test/mockFactory.js', included: false },
{ src: './Leen.Managementsystem/App/**/*.js', included: false },
{ src: './Leen.Managementsystem.Tests/App/test/*.js', included: false },
{ src: './Leen.Managementsystem.Tests/App/**/*.spec.js', included: false },
{ src: './Leen.Managementsystem.Tests/App/test-main.js' }
]
},
one: {
configFile: 'karma.conf.js',
files: [
{ src: './Leen.Managementsystem/bower_components/jquery/dist/jquery.js' },
{ src: './Leen.Managementsystem/bower_components/globalize/lib/globalize.js' },
{ src: './Leen.Managementsystem/bower_components/**/*.js', included: false },
{ src: './Leen.Managementsystem.Tests/App/test/mockFactory.js', included: false },
{ src: './Leen.Managementsystem/App/**/*.js', included: false },
{ src: './Leen.Managementsystem.Tests/App/test/*.js', included: false },
// (do not inlcude the *.spec.js files here! The watch event listener will add the single spec file to run)
{ src: './Leen.Managementsystem.Tests/App/test-main.js' }
]
}
},
watch: {
spec_js: {
options: {
interrupt: true,
spawn: false
},
files: 'Leen.Managementsystem.Tests/App/**/*.spec.js',
tasks: ['karma:one:start']
}
}
});
var originalKarmaOneFiles = grunt.config.get('karma.one.files'); // keep the original files array
grunt.event.on('watch', function watchEventListener(action, filepath, target) {
if (target === 'spec_js') {
handleChangedSpecFile();
}
function handleChangedSpecFile() {
if (action === 'deleted') {
return;
}
var testFilePath = "./" + filepath.replace(/\\/g, "/");
grunt.log.writeln(['Running single karma test for: ' + testFilePath]);
var updatedFiles = originalKarmaOneFiles.concat([{ src: testFilePath, included: false }]);
grunt.config.set('karma.one.files', updatedFiles);
}
});
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['karma:all','watch']);
};
karma.conf.js:
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '', //the solution root path, e.g. D:\Energienetzwerke\trunk
// frameworks to use
frameworks: ['jasmine', 'requirejs'],
// list of files / patterns to load in the browser
files: [
'./Leen.Managementsystem/bower_components/jquery/dist/jquery.js',
'./Leen.Managementsystem/bower_components/globalize/lib/globalize.js',
{ pattern: './Leen.Managementsystem/bower_components/**/*.js', included: false },
{ pattern: './Leen.Managementsystem.Tests/App/test/mockFactory.js', included: false },
{ pattern: './Leen.Managementsystem/App/**/*.js', included: false },
{ pattern: './Leen.Managementsystem.Tests/App/test/*.js', included: false},
{ pattern: './Leen.Managementsystem.Tests/App/**/*.spec.js', included: false},
'./Leen.Managementsystem.Tests/App/test-main.js'
],
// list of files to exclude
exclude: [
'./Leen.Managementsystem/App/main.js'
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress', 'coverage', 'notify', 'htmlDetailed', 'xml'],
coverageReporter: {
dir: './Leen.Managementsystem.Tests/testCoverage',
reporters: [
{ type: 'html',subdir: 'html'},
{ type: 'cobertura',subdir: 'xml', file: 'coverage.xml' },
{ type: 'lcov', subdir: 'lcov' },
{ type: 'text-summary' }
]
},
notifyReporter: {
reportEachFailure: true, // Default: false, Will notify on every failed spec
reportSuccess: false // Default: true, Will notify when a suite was successful
},
htmlDetailed: {
autoReload: true,
dir: './Leen.Managementsystem.Tests/testResults'
},
preprocessors: {
// source files, that you wanna generate coverage for
// do not include tests or libraries
// (these files will be instrumented by Istanbul)
'./Leen.Managementsystem/App/**/*.js': ['coverage']
},
// 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, //watching is done by Gruntfile.js to only execute changed tests
usePolling: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['Chrome_With_Saved_DevTools_Settings'],
customLaunchers: {
Chrome_With_Saved_DevTools_Settings: {
base: 'Chrome',
chromeDataDir: './.chrome'
}
},
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true
});
};
package.json:
{
"name": "solution",
"version": "1.0.0",
"description": "contains packages that are needed for running karma",
"main": "./Leen.Managementsystem.Tests/App/test-main.js",
"dependencies": {
"grunt": "1.0.1",
"grunt-cli": "1.2.0",
"grunt-contrib-watch": "1.0.0",
"grunt-karma": "2.0.0",
"jasmine-core": "2.6.4",
"karma": "1.7.0",
"karma-chrome-launcher": "2.2.0",
"karma-cli": "1.0.1",
"karma-coverage": "1.1.1",
"karma-firefox-launcher": "1.0.1",
"karma-html-detailed-reporter": "1.1.20",
"karma-ie-launcher": "1.0.0",
"karma-jasmine": "1.1.0",
"karma-notify-reporter": "1.0.1",
"karma-phantomjs-launcher": "1.0.4",
"karma-requirejs": "1.1.0",
"karma-xml-reporter": "0.1.4",
"requirejs": "2.3.4"
},
"devDependencies": {},
"scripts": {
"test": "karma run"
},
"author": "LEEN",
"license": "private"
}

Resources