Exclude dependencies from JS Test Driver code coverage - javascript

In my JS Test Driver configuration file, I'm excluding unit tests from code coverage calculation by putting them under test instead of load.
However, I can't do this for dependencies, like jQuery of Underscore.js, since they need to be loaded before my code.
Is there any way around this? Or do I just deal with the slow code coverage runs and statistic clutter?

Solution 1:
There's a way using the ´args´ parameter as Greg says, but that way unfortunately you have to specify the full path, as this (asuming Windows):
plugin:
- name: "coverage"
jar: "lib/coverage-1.3.2.jar"
module: "com.google.jstestdriver.coverage.CoverageModule"
#Here put the files that have to be ignored by coverage. Non-existent files do not harm.
args: "
D:\\apache\\htdocs\\XTIME\\js\\lib\\ext-all.js,
D:\\apache\\htdocs\\XTIME\\js\\lib\\jquery-1.7.2.min.js,
"
For linux filesystems, you don't have to use double slash.
Solution 2:
There's also a patched jar for 1.3.5 on this thread that allows you to exclude files that match a regular expression, so you'd have:
plugin:
- name: "coverage"
jar: "lib/coverage-1.3.5.serve-patch.jar" #this patched jar allows to use excludesRegex
module: "com.google.jstestdriver.coverage.CoverageModule"
args: "excludesRegex: /js/lib/.*\\.js$"
The /js/lib/.*\.js$ regex means "Exclude all the .js files located inside js/lib". (With this patch you don't have to worry about Windows backslashes)
I prefer this way much more, as it's portable because it does not depend on a specific path for your application.
You can download the patched version here (look for Comment 11 in the thread).
Hope this helps.
Cheers, from La Paz-Bolivia

You can exclude libraries from code coverage by specifying them under "args" in the config. However, note that the paths must be absolute. At the time of writing, the latest jsTestDriver code-coverage plugin will only ignore the libraries if the paths are absolute.
See here.

Related

Webpack & Testing: Helper to delete/replace modules from the require cache

For our tests we need to be able to replace or delete modules from the require cache, e.g. to replace them with a fake implementation.
In order to achieve this we implemented a little helper function:
fakeModule = function(modulePath, fakeExportsObject){
require.cache[require.resolve(modulePath)] = {exports: fakeExportsObject}
}
However when we run this through webpack we get the following critical warning: "the request of a dependency is an expression" and all JavaScript files in the project are included in the webpack build.
Is there any possibility to disable the interpretation of the helper function? In our tests we can safely assume that we are only deleting/replacing existent modules from the require cache. Even if not, it wouldn´t really matter.
Have you looked at rewire and rewire-webpack? I just started looking into testing with webpack and will need to find a way to accomplish this as well. Rewire sounds promising, but I haven't used it yet.

Excluding files from coverage when using Karma and Istanbul

I am using Karma to test my JavaScript and get coverage reports. I am using the Istanbul coverage report, which is the default. Here is my preprocessors parameter:
preprocessors: {
'framework/**/*.js':'coverage',
'framework/*.js':'coverage',
'!framework/node/**/*.js':'coverage',
'!framework/test/**/*.js':'coverage',
'framework-lib/**/*.js':'coverage',
'!framework-lib/tool-data-api/tool-data-api.js':'coverage'
}
As you can see, I am trying to use the "!" as a negate command, which usually works with Node. However, it is not working here and none of my directories are being excluded.
Is there any way to do what I am trying to accomplish?
According to https://karma-runner.github.io/0.12/config/configuration-file.html:
**/*.js: All files with a "js" extension in all subdirectories
**/!(jquery).js: Same as previous, but excludes "jquery.js"
**/(foo|bar).js: In all subdirectories, all "foo.js" or "bar.js" files
So, based on this, I tried the following:
preprocessors: {
'framework/**/!(node|test)/*.js': 'coverage',
'framework-lib/**/!(tool-data-api).js': 'coverage'
}
Which seems to have accomplished what you are looking for.
As a note to others who come here looking for how to target all files EXCEPT .spec.js files, try:
'**/!(*spec).js'
Which seems to work for me.
In the Karma used minimatch.js lib for mathing files.
So you need rewrite you rules.
For instance to exclude folder node node it should has
preprocessors: {
'framework/*[!node]/*.js':'coverage',
}
I'm not sure if you are running "istanbul cover ..." to run your coverage report, but if you are, you can use the -x flag to exclude files/patterns. Typing in "istanbul help cover" will show you usage including this.
-x <exclude-pattern> [-x <exclude-pattern>]
one or more fileset patterns e.g. "**/vendor/**"
Make sure that the directories / file you want to exclude are not loaded by any other include. for example, 'framework//.js':'coverage' will load files you are trying to exclude in '!framework/node//.js':'coverage'
you can modify in angular.json under test->options
"codeCoverageExclude": ["src/testing/**/*"]

Generating source maps for multiple concatenated javascript files compiled from Coffeescript

Has any one had any success with this?
I think it's more or less an unsolved problem:
https://github.com/jashkenas/coffee-script/issues/2779 . Last meanigingful comment was from jwalton, a month ago.
Still, it doesn't seem rocket science to add support for it, so it will probably come soon.
Michael Ficarra (creator of CoffeeScript Redux) suggested using https://github.com/michaelficarra/commonjs-everywhere .
Two caveats:
It only works for bundling CommonJS modules.
It uses CoffeeScript Redux, which is still in beta (although working quite well it seems), and not 100% compatible with original CoffeeScript compiler.
So this does not work for what you ask for specifically, "concatenation".
Added April 14
You might have luck with these: combine-source-map and/or generate-sourcemap, both by same author.
Added April 26
This looks really simple: https://npmjs.org/package/mapcat . You just have to feed it the individual source map files generated by the coffee compiler.
Added May 16
Mariusz Nowak has just released webmake-coffee. Like CommonJS Everywhere, it requires code to be organized as CommonJS modules. Unlike CommonJS everywhere, it uses regular CoffeeScript.
It also seems the Grunt Coffee-Script plugin has had source-map support for concatenated files for quite a while (two months), effectively proving my original answer to be incorrect.
The upcoming version 2.0 of Snockets will have support for it too.
I ended up going with browserify using coffeeify as the transform option, and enabling browserify's debug option. I bundle up the app on each request for my main.js file, and any runtime errors show up in my original source with pretty decent accuracy.
Sure beats mapping runtime errors in the concatenated/compiled js back to the coffee source with my eyeballs!
I needed to annotate AngularJS code before minification, but grunt-ng-annotate didn't accept input source maps, thus I would not be able to use maps generated by the CoffeeScript compiler.
Apparently, with gulp-sourcemaps this is not an issue:
var gulp = require('gulp');
var $ = require('gulp-load-plugins')(); // loading gulp plugins lazily
// remember to include them in the package.json
gulp.task('appJS', function() {
// concatenate compiled .coffee files and js files into build/app.js
gulp.src(['./app/**/*.js','./app/**/*.coffee'])
.pipe($.sourcemaps.init())
.pipe($['if'](/[.]coffee$/, $.coffee({bare: true}).on('error', $.util.log)))
.pipe($.concat('app.js'))
.pipe($.ngAnnotate())
.pipe($.uglify())
.pipe($.sourcemaps.write())
.pipe(gulp.dest('./build'))
});
The same approach works in other situations, too. In my case, this is the only approach that worked.
I have written a grunt task that does this flawless. Check it out

Is there a way to include file in coffee script?

I'd like to know if there is a way to include a file in a coffee script.
Something like #include in C or require in PHP...
If you use coffeescript with node.js (e.g. when using the commandline tool coffee) then you can use node's require() function exactly as you would for a JS-file.
Say you want to include included-file.coffee in main.coffee:
In included-file.coffee: declare and export objects you want to export
someVar = ...
exports.someVar = someVar
In main.coffee you can then say:
someVar = require('included-file.coffee').someVar
This gives you clean modularization and avoids namespace conflicts when including external code.
How about coffeescript-concat?
coffeescript-concat is a utility that preprocesses and concatenates
CoffeeScript source files.
It makes it easy to keep your CoffeeScript code in separate units and
still run them easily. You can keep your source logically separated
without the frustration of putting it all together to run or embed in
a web page. Additionally, coffeescript-concat will give you a single
sourcefile that will easily compile to a single Javascript file.
Tl;DR: Browserify, possibly with a build tool like Grunt...
Solutions review
Build tool + import pre-processor
If what you want is a single JS file to be run in the browser, I recommend using a build tool like Grunt (or Gulp, or Cake, or Mimosa, or any other) to pre-process your Coffeescript, along with an include/require/import module that will concatenate included files into your compiled output, like one of these:
Browserify: probably the rising standard and my personal favourite, lets you to use Node's exports/require API in your code, then extracts and concatenates everything required into a browser includable file. Exists for Grunt, Gulp, Mimosa and probably most others . To this day I reckon it is probably the best solution if you're after compatibility both Node and the browser (and even otherwise)
Some Rails Sprocket-like solutions like grunt-sprockets-directives or gulp-include will also work in a consistent way with CSS pre-processors (though those generally have their own importing mechanisms)
Other solutions include grunt-includes or grunt-import
Standalone import pre-processor
If you'd rather avoid the extra-complexity of a build tool, you can use Browserify stand-alone, or alternatives not based on Node's require like coffeescript-concat or Coffee-Stir
[Not recommended] Asynchronous dynamic loading (AJAX + eval)
If you're writing exclusively for the browser and don't mind, or rather really want, your script being spread across several files fetched via AJAX, you can use a myriad of tools like:
yepnope.js or Modernizr's .load based on yepnope: Please note that yepnope is now deprecated by its maintainer, who recommend using build tools and concatenation instead of remote loading
RequireJS
HeadJS
jQuery's $.getScript
Vanilla AJAX + eval
your own implementation of AMD
You can try this library I made to solve this same problem coffee-stir
its very simple.
Just type #include and the name of the file that you want to include
#include MyBaseClass.coffee
For details
http://beastjavascript.github.io/Coffee-Stir/
I found that using "gulp-concat" to merge my coffee scripts before processing them did the trick. It can be easily installed to your project with npm.
npm install gulp-concat
Then edit your gulpfile.js:
var gulp = require('gulp')
,coffee = require('gulp-coffee')
,concat = require('gulp-concat');
gulp.task('coffee', function(){
gulp.src('src/*.coffee')
.pipe(concat('app.coffee')
.pipe(coffee({bare: true}).on('error', gulp.log))
.pipe(gulp.dest('build/')
})
This is the code I used to concatenate all my coffee scripts before gulp processed it into the final build Javascript. The only issue is the files are processed in alphabetical order. You can explicitly state which file to process to achieve your own file order, but you lose the flexibility of adding dynamic .coffee files.
gulp.src(['src/file3.coffee', 'src/file1.coffee', 'src/file2.coffee'])
.pipe(concat('app.coffee'))
.pipe(coffee({bare: true}).on('error', gulp.log))
.pipe(gulp.dest('build/')
gulp-concat as of February 25th, 2015 is available at this url.
Rails uses sprockets to do this, and this syntax has been adapted to https://www.npmjs.org/package/grunt-sprockets-directives. Works well for me.

Client Side Dependency Management in CoffeeScript

What is the best way to do Dependency Management amongst CoffeeScript files if the resulting javascript files eventually need to be concatenated together for use on the client side?
For server side CoffeeScript I can just use the 'require' keyword to require other pieces of javascript. When this is compiled for client side apps to have the dependency tree, based on the requires, calculated and a concatenated stand alone javascript file produced. Is there anyway to do this in a generic way?
Another option is to use CoffeeToaster, which uses another approach than implementing AMD / CJS module patterns.
Take a look:
http://github.com/serpentem/coffee-toaster
Usually, for client-side packaging of JavaScript (and CSS), you want some sort of asset-packaging plugin. We use Jammit, but there are many other options: Sprockets, Django-Compress ... and more.
Villain (a CoffeeScript game engine for browsers) defines functions that do just that (dependency management and js concatenation).
The code for that is in these two files:
cake.coffee, see , determineDependencies(), wrapModule(), and bundleSources()
brequire.coffee, a require replacement for the browser, to use with wrapModule()
I use it here (see the 'bundle' Cake task).
Note: I just declare the 'main' module's build directory, and Villain scans my compiled JS files to build the dependency tree (starting with index.js), then creates a JavaScript bundle file containing Villain's require replacement and all my relevant code sorted and correctly wrapped.
Villain's author uses it in orona, a CoffeeScript game made with Villain.
For dependency management on client side, I use requirejs for javascript and coffeescript source. It'possible to use a requirejs plugin to load natively coffee files, but I prefer to "compile" into js.
requirejs also provide / work with r.js optimizer. It can be used to aggregate a set of js file into one and minified it. you don't have to specify the file to aggregate it is the dependency definition of each module require by your "main.js". (feature that match your request)
Something I like a lot with requirejs, it "promots" creating module and declare explicit dependencies.
# A.coffee
define(() ->
class A
constructor: (#c1, #c2) ->
#c2 ?= 1
m1 : () ->
"hello"
toString : () -> "#{#c1}#{#c2}"
)
# B.coffee
define(['A'], (A) ->
a = new A(33)
console.log(a, a.m1())
)
I've used (and I guess am still using) requirejs but I've started to find it to be fairly clumsy. A lot of my files end up having ~10-12 imports at the top which just take up a lot of space and don't look great.
For a new project I tried browserify. It's great! And if you use grunt (you should), you can make a watch task to browserify your code on change. grunt-browserify also provides the ability to do a coffeescript transform.
https://github.com/jmreidy/grunt-browserify
So your watch task in your Gruntfile.coffee would look something like:
watch:
files: [
"app/**/*.coffee"
]
tasks: "browserify"
browserify:
'build/app.js': ['app/**/*.coffee']
options:
transform: ['coffeeify']

Categories

Resources