sails js add a custom task - gruntjs

I am trying to add custom task to a sails js application. accroding to the documentation I create files in the following way.
tasks/register/test.js
module.exports = function (grunt) {
grunt.registerTask('test', ['mochaTest']);
};
tasks/config/mochaTest.js
module.exports = function(grunt) {
grunt.config.set('mochaTest', {
test: {
options: {
reporter: 'spec',
captureFile: 'results.txt', // Optionally capture the reporter output to a file
quiet: false, // Optionally suppress output to standard out (defaults to false)
clearRequireCache: false // Optionally clear the require cache before running tests (defaults to false)
},
src: [
'test/bootstrap.test.js',
'test/unit/**/*.js'
]
}
});
grunt.loadNpmTasks('grunt-mocha-test');
};
I have written test cases inside test/unit folder. I can run these test using grunt mochaTest command. But using 'sails lift --test' command does not run the test cases. instead it just run the sails application. I also tried the following command. ()
NODE_ENV=test sails lift
It also does not run the test cases. It just run the sails application. (http://sailsjs.org/documentation/concepts/assets/task-automation)
What am I missing here ?

Modify the file "tasks/register/default.js" to have the following code:
module.exports = function (grunt) {
grunt.registerTask('default', ['compileAssets', 'linkAssets', 'grunt-mocha-test', 'watch']);
};
then just launch the app with "sails lift"

Related

Filter output of a grunt task

I have several grunt tasks which internally use grunt-shell to execute various CLI commands.
I want to hide certain logs printed to the output console by these CLI commands.
Am trying to use grunt-reporter for this but unable to get it working.
Gruntfile.js
reporter: {
shell:{
options: {
tasks: ['shell'],
header: false
}
}
}
The short answer... It's not possible for grunt-reporter by itself to hide logs generated by a grunt-shell command.
The long answer including workaround... The logs from a grunt-shell command are generated by the shell/bash command itself and not via a node package/script. The examples shown on the grunt-reporter homepage are intercepting/manipulating a message from a node package written to stdout.
Consider the following...
Simple gist
module.exports = function(grunt) {
grunt.initConfig({
shell: {
listFiles: {
command: 'ls src/js/*.js'
}
}
});
require('load-grunt-tasks')(grunt);
grunt.registerTask('default', [
'shell:listFiles'
]);
};
Running $ grunt via the CLI outputs something like this:
Running "shell:listFiles" (shell) task
src/js/a.js
src/js/b.js
src/js/c.js
Done.
Hide the header...
Utilizing grunt-reporter it's possible, (at best for this scenario), to hide the header using a config as follows:
module.exports = function(grunt) {
grunt.initConfig({
reporter: {
shell: {
options: {
tasks: ['shell:listFiles'],
header: false
}
}
},
shell: {
listFiles: {
command: 'ls src/js/*.js'
}
}
});
require('load-grunt-tasks')(grunt);
grunt.registerTask('default', [
'reporter:shell', //<-- Note: The reporter task is called first.
'shell:listFiles'
]);
};
Running $ grunt via the CLI will now output something like this (Note: the header has been hidden, however the log from the ls command persists as it directly comes from the bash/shell command):
src/js/a.js
src/js/b.js
src/js/c.js
Done.
Even after adding the suppress: true to the reporter options the paths logs from the ls command persist.
Workaround
I think the only way to hide the logs from a CLI command will be to redirect the output messages to /dev/null in the 'grunt-shell' commands:
module.exports = function(grunt) {
grunt.initConfig({
reporter: {
shell: {
options: {
tasks: ['shell:listFiles'],
header: false,
}
}
},
shell: {
listFiles: {
command: 'ls src/js/*.js > /dev/null' //<-- redirect the output messages
}
}
});
require('load-grunt-tasks')(grunt);
grunt.registerTask('default', [
'reporter:shell', //<-- Note: The reporter task is called first.
'shell:listFiles'
]);
};
This time running $ grunt via the CLI successfully hides the messages/logs and only reports:
Done.
Note: The addition of > /dev/null will only redirect the messages/logs and any errors will continue to get reported. Using > /dev/null 2>&1 would also hide any errors too.

Looking for Modernizr references

I'm trying to use the grunt-modernizr plugin in my project but I'm receiving the following output when I run tasks:
Running "modernizr:dist" (modernizr) task
>> Explicitly including these tests:
>> pointerevents
Looking for Modernizr references
I'm not receiving any type of error the terminal just goes back to the directory that I'm in, as if it's just giving up.
Here is my grunt file:
module.exports = function(grunt) {
grunt.initConfig ({
// Do grunt-related things in here
pkg: grunt.file.readJSON('package.json'),
modernizr: {
dist: {
"dest": "javascripts/modernizr-custom.js",
"parseFiles": true,
"customTests": [],
"devFile": "javascripts/modernizr-custom.js",
"outputFile": "javascripts/min/modernizr-custom.min.js",
"tests": [
"pointerevents",
"css/pointerevents"
],
"extensibility": [
"setClasses"
],
"uglify": false
}
},
cssmin: {
target: {
files: {
'css/min/bootstrap.min.css': ['css/bootstrap.css']
}
}
},
});
grunt.loadNpmTasks("grunt-modernizr");
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.registerTask('default',['modernizr', 'cssmin']);
};
Output from running grunt --verbose:
Initializing
Command-line options: --verbose
Reading "gruntfile.js" Gruntfile...OK
Registering Gruntfile tasks.
Reading package.json...OK
Parsing package.json...OK
Initializing config...OK
Registering "grunt-modernizr" local Npm module tasks.
Reading /Applications/MAMP/htdocs/bootstrap-three-wordpress/wp-content/themes/brandozz/node_modules/grunt-modernizr/package.json...OK
Parsing /Applications/MAMP/htdocs/bootstrap-three-wordpress/wp-content/themes/brandozz/node_modules/grunt-modernizr/package.json...OK
Loading "modernizr.js" tasks...OK
+ modernizr
Registering "grunt-contrib-cssmin" local Npm module tasks.
Reading /Applications/MAMP/htdocs/bootstrap-three-wordpress/wp-content/themes/brandozz/node_modules/grunt-contrib-cssmin/package.json...OK
Parsing /Applications/MAMP/htdocs/bootstrap-three-wordpress/wp-content/themes/brandozz/node_modules/grunt-contrib-cssmin/package.json...OK
Loading "cssmin.js" tasks...OK
+ cssmin
Loading "gruntfile.js" tasks...OK
+ default
No tasks specified, running default tasks.
Running tasks: default
Running "default" task
Running "modernizr" task
Running "modernizr:dist" (modernizr) task
Verifying property modernizr.dist exists in config...OK
Files: -> javascripts/modernizr-custom.js
Verifying property modernizr exists in config...OK
>> Explicitly including these tests:
>> pointerevents
Looking for Modernizr references
This is something I just came across too and seems to be grunt-modernizr stopping after customizr doesn't find any files to crawl (it crawls by default).
If you add "crawl": false to your modernizr:dist task that should fix the problem.
Also, I think "extensibility": [ "setClasses" ], should be "options": [ "setClasses" ],.
To use the grunt-modernizr task to crawl your code for Modernizr references you'll have to look at the config properties for the customizr task as this is part of grunt-modernizr 's node_modules:
modernizr: {
dist: {
dest: 'bower_components/modernizr/build/modernizr.custom.js',
uglify: false,
options: [
'setClasses',
'addTest'
],
files: {
src: ['js/app/**/*.js', 'js/app/*.js']
}
}
}
devFile: doesn't seem to matter where you point at
dest: instead of outputFile, note I'm just outputting to a build directory that's not part of the package
uglify: false if you have other minifying options like bundleconfig.json
options: to bypass the default options { "setClasses", "addTest", "html5printshiv", "testProp", "fnBind" }
files: to enlist your crawlable director(y|ies), make sure you take care of the root files and/or subdirectories as well
Load the required tasks, in my case:
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-modernizr');
grunt.loadNpmTasks('grunt-contrib-copy');
Refer to the 'modernizr:dist' task => grunt.registerTask('default', ['clean', 'modernizr:dist', 'copy']);
Which results in an unminified 34kb file:
Running "clean:files" (clean) task
19 paths cleaned.
Running "modernizr:dist" (modernizr) task
Looking for Modernizr references
1 match in js/app/classes/yambo.options.js
bgpositionxy
1 match in js/app/modules/yambo.audio.js
audio
Ready to build using these settings:
setClasses, addTest
Building your customized Modernizr...OK
Success! Saved file to bower_components/modernizr/build/modernizr.custom.js
Process terminated with code 0.
Running "copy:main" (copy) task
Copied 11 files
Done, without errors.
This way there's no need to even go to the online build to add a feature test. Simply reference Modernizr throughout your js code:
window.Yambo = (function($, modernizr, ns){
ns.Audio = {
extension: (function () {
return modernizr && modernizr.audio.mp3
? 'mp3'
: modernizr.audio.ogg
? 'ogg'
: 'wav';
}())
};
return ns;
}(window.jQuery, window.Modernizr, window.Yambo || {}));
Make sure to use the correct property name for a feature detection, so customizr can pick it up and provide a test to your custom build.
This should be also possible for css but haven't been testing that for the moment.
It looks like you missed source files.
http://gruntjs.com/configuring-tasks#files-object-format
Try to include
"dist": {
"files": {
"src": ['!<%= appDir %>assets/js/bower/modernizr/**']
}
}

How to run multiple karma targets in Grunt?

We're using Grunt to build multiple, but similar, applications in one build.
It's a rather complex and large project with a folder for each application and a folder named share with lots of shared components.
multiple karma targets
Angular injects dependency by name (String) and our applications have files with the same names like HomeController, MenuController. This forces us to split up the karma targets per application so dependencies are loaded only from the shared and specific application being tested.
Fatal error
When using grunt to run the karma targets it only runs the first successful and fails to run the second. Fatal error: listen EADDRINUSE The error is somehow related to a port being used.
Karma config (simplified)
module.exports = function(config) {
'use strict';
config.set({
autoWatch: false,
basePath: '../',
frameworks: ['jasmine'],
exclude: [],
browsers: ['PhantomJS'],
plugins: [
'karma-html-reporter',
'karma-junit-reporter',
'karma-coverage',
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-brackets'
],
singleRun: false,
colors: true,
logLevel: config.LOG_DEBUG
});
};
Grunt-karma config
var dep = [
'bower_components/**/*.js',
'app/shared/**/*.js',
];
module.exports = {
options: {
configFile: 'test/karma.conf.js',
reporters: ['brackets', 'html', 'junit', 'coverage'],
browsers: ['PhantomJS'],
port: 9002,
singleRun: true
},
A: {
options: {
files: dep.concat([
'app/A/src/**/*.js'
]),
}
},
B: {
options: {
files: dep.concat([
'app/B/src/**/*.js'
]),
}
}
};
How can I run both karma targets (A and B) in the same the grunt task?
My guess is I have to either reset the karma server (phantomJs?) or run them as separate "sets" on the same target, but I can't find out how to do it.
Hope anyone out there might help! Thanks!
Update1
This issue on github seems to address the same problem, but has not yet made it to a release.
Maybe you can just move your port option into the targets and choose a different port for each one?
A: {
options: {
port: 9011,
files: dep.concat([
'app/A/src/**/*.js'
]),
}
},
B: {
options: {
port: 9012,
files: dep.concat([
'app/B/src/**/*.js'
]),
}
}
workaround that works
Remove the the karma tasks from the the distribution task.
Instead of trying to run multiple karma targets in one grunt task, you can execute multiple grunt commands separately from the command line (mainly on the continuous integration server. For development there is rarely a need to run all targets)
The command could be: (optional xxxxxx is any task you want to run after testing has completed)
grunt testA && grunt testB && grunt xxxxxx

How to get grunt.file.readJSON() to wait until file is generated by another task

I'm working on setting up series of grunt tasks that work with RequireJS r.js compiler:
1) generates a .json file listing of all files in a directory
2) strips the ".js" from the filename (requirejs requires this)
3) use grunt.file.readJSON() to parse that file and use as a configuration option in my requirejs compilation task.
Here is the relevant code from my gruntfile.js:
module.exports = function (grunt) {
grunt.initConfig({
// create automatic list of all js code modules for requirejs to build
fileslist: {
modules: {
dest: 'content/js/auto-modules.json',
includes: ['**/*.js', '!app.js', '!libs/*'],
base: 'content/js',
itemTemplate: '\t{' +
'\n\t\t"name": "<%= File %>",' +
'\n\t\t"exclude": ["main"]' +
'\n\t}',
itemSeparator: ',\n',
listTemplate: '[' +
'\n\t<%= items %>\n' +
'\n]'
}
},
// remove .js from filenames in module list
replace: {
nodotjs: {
src: ['content/js/auto-modules.json'],
overwrite: true,
replacements: [
{ from: ".js", to: "" }
]
}
},
// do the requirejs bundling & minification
requirejs: {
compile: {
options: {
appDir: 'content/js',
baseUrl: '.',
mainConfigFile: 'content/js/app.js',
dir: 'content/js-build',
modules: grunt.file.readJSON('content/js/auto-modules.json'),
paths: {
jquery: "empty:",
modernizr: "empty:"
},
generateSourceMaps: true,
optimize: "uglify2",
preserveLicenseComments: false,
//findNestedDependencies: true,
wrapShim: true
}
}
}
});
grunt.loadNpmTasks('grunt-fileslist');
grunt.loadNpmTasks('grunt-text-replace');
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.registerTask('default', ['fileslist','replace', 'requirejs']);
I'm running into a problem where, if the "content/js/auto-modules.json" file doesn't already exist on load of my config file, the file.readJSON() is executed immediately, before the file exists and the entire task fails and throws "Error: Unable to read file " If the file already exists, everything works beautifully.
How can I set this up so that the task configuration waits for that file to be created in the first task, and modified in the second task before it tries to load & parse the JSON in it for the third task? Or is there another way (perhaps using a different plugin) to generate a json object in one task, and then pass that object to another task?
Old post but I had a similar experience.
I was trying to load a some json config like:
conf: grunt.file.readJSON('conf.json'),
but if this file did not exist then it would fall in a heap and not do anything.
So I did the following to load it and populate defaults if it didnt exist:
grunt.registerTask('checkConf', 'ensure conf.json is present', function(){
var conf = {};
try{
conf = grunt.file.readJSON('./conf.json');
} catch (e){
conf.foo = "";
conf.bar = "";
grunt.file.write("./conf.json", JSON.stringify(conf) );
}
grunt.config.set('conf', conf);
});
You still may have some timing issues but this approach may help someone with a readJSON error.

Sending specs in grunt using grunt-protractor-runner

I am using grunt-protractor-runner plugin and in the protractor target I want to send the specs param containing the test to run.
In the grunt file my target looks as follows:
testIntegration:
{
options:
{
args: {
specs: ['test1.js'],
browser: 'firefox'
}
}
The protractor parent task option contains setting of the protractor config file.
When running this target I get this error:
$ grunt protractor:testIntegration
Running "protractor:testIntegration" (protractor) task
Starting selenium standalone server...
Selenium standalone server started at ...
Warning: pattern t did not match any files.
Warning: pattern e did not match any files.
Warning: pattern s did not match any files.
Warning: pattern t did not match any files.
Warning: pattern 1 did not match any files.
Warning: pattern j did not match any files.
Warning: pattern s did not match any files.
and then some more errors.
the same line works well in Protractor config file.
Tried a few other variation but no success.
What am I missing? Any ideas?
Try this configuration:
module.exports = function(grunt) {
// Project configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
protractor: {
options: {
keepAlive: true,
singleRun: false,
configFile: "PROTRACTOR_CONFIG_FILE.js"
},
run_firefox: {
options: {
args: {
browser: "firefox"
}
}
}
});
// load grunt-protractor-runner
grunt.loadNpmTasks('grunt-protractor-runner');
// register tasks
grunt.registerTask('default', 'Run Protractor using Firefox',
['protractor:run_firefox']);
};
Funny, if you read every error message, it spells out "test1.js". Looks like it's not reading in the config file correctly, probably because you're not using grunt.file.readJSON('FILENAME.json')

Resources