I have getcookie(username,password) function of javascript in getcookies.js file.
'use strict';
var getcookie = function(username,password){
//body of the getcookie method.
};
I am calling this function using grunt for that I have written task in grunt.js file.
module.exports = function(grunt) {
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
protractor: {
options: {
keepAlive: false,
configFile: "./config/protractorConf.js"
},
getcookie: {
options: {
args: {
specs: ['getcookie.js']
}
}
}
}
});
//Note: Create task and add it to register task. In order to run single task comment all other tasks and run
grunt.registerTask('getcookie', ['protractor:getcookie']);
};
I want to pass the arguments username and password to the getcookie function from the grunt file.
How can I achieve this?
Related
I have custom functions that work well when the tasks are defined in the same gruntfile.js but my gruntfile.js now has more than 2000 lines and its becoming hard to maintain. Is it possible to use the functions globally without having to define them again in each task file?. When they are called from the external task neither of the two functions work. I just get error function not defined.
I have next structure
gruntfile.js
grunt/tasks/functions.js
grunt/tasks/styles.js
The content of the files is as follows:
gruntfile.js
module.exports = function(grunt) {
require('jit-grunt')(grunt)
function globalFunctionOne(param1) {
console.log('yay it works from main file');
}
grunt.initConfig({});
console.log(grunt.config());
grunt.loadTasks('grunt/tasks')
grunt.registerTask('default', ['sass:dist'];
}
functions.js
module.exports = function(grunt) {
function globalFunctionTwo(param1) {
console.log('yay it works from partial file');
}
}
styles.js
module.exports = function(grunt) {
grunt.config('sass', {
options: {
implementation: sass,
includePaths: globalFunctionOne('dev'),
outputStyle: 'expanded',
sourceMap: true
},
dist: {
files: {
globalFunctionTwo('dist'),
}
}
});
}
2,000 lines? That's a long gruntfile. Here's a gruntfile you can adopt to break apart your code into something more modular:
gruntfile.js
function init(grunt) {
"use strict";
function loadConfig(pattern) {
let config = {},
fileName,
fileData;
grunt.file.expand(pattern).forEach(function (filePath) {
fileName = filePath.split('/').pop().split('.')[0];
fileData = require('./' + filePath)(grunt);
config[fileName] = fileData;
});
return config;
}
function loadGrunt() {
const config = {
pkg: grunt.file.readJSON('package.json')
};
require('load-grunt-tasks')(grunt);
if (grunt.file.exists('grunt/tasks')) {
grunt.log.writeln('task directory found, loading tasks...');
grunt.loadTasks('grunt/tasks');
}
grunt.util._.extend(config, loadConfig('grunt/configs/**/*.js'));
grunt.initConfig(config);
}
loadGrunt();
}
module.exports = init;
What this gruntfile does:
It dynamically creates a config object for grunt to use by loading
every .js file it finds in project-root/grunt/configs. The name
of each file corresponds to its key for the grunt config object.
It dynamically loads any tasks from project-root/grunt/tasks
If your config uses grunt-contrib-copy, then in your project, you'd have a config file resembling the following:
project-root/grunt/configs/copy.js
module.exports = function (grunt) {
"use strict";
return {
base: {
options: {
process: function (content) {
return grunt.template.process(content);
}
},
src: 'grunt/templates/base.url.js',
dest: 'www/source/config/base.url.js'
},
pluginManifest: {
src: 'cordova/template/package.json',
dest: '<%= grunt.task.current.args[0] %>/package.json'
},
splashScreens: {
expand: true,
cwd:"grunt/templates/",
src: "screen/**",
dest: '<%= create.dest %>/res/'
}
};
};
You can then shift your global functions to a helpers javascript file and import them into the configs in typical Node.js fashion:
project-root/grunt/configs/sass.js
module.exports = function (grunt) {
const helpers = require("../helpers.js)(grunt);
return {
options: {
implementation: sass,
includePaths: helpers.globalFunctionOne('dev'),
outputStyle: 'expanded',
sourceMap: true
},
dist: {
files: {
globalFunctionTwo('dist'),
}
}
};
};
project-root/grunt/helpers.js
module.exports = function (grunt) {
function globalFunctionOne(param1) {
console.log('yay it works from main file');
}
function globalFunctionTwo(param1) {
console.log('yay it works from partial file');
}
return {
globalFunctionOne,
globalFunctionTwo
};
};
I am writing custom grunt task to concat multiple JS files from different folders into a single JS file. When i run grunt command, it shows that "Running 'read-folder-concat' task. After that, nothing happens. I am unable to see any errors on the console. I am totally stuck here.
There are two files, one is Gruntfile.js & concat-task.js. I am sharing code here of these files.
Gruntfile.js
// Grunt configuration file
(function () {
'use strict';
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: ';'
}
}
});
//load grunt tasks
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.task.loadTasks('./tasks');
//register grunt default task
grunt.registerTask('default', ['read-folder-concat']);
};
})();
concat-task.js
(function () {
'use strict';
module.exports = function (grunt) {
function readFolderAndConcat(pathArr) {
// get the current concat config
var i,
src = [],
concat = grunt.config.get('concat') || {};
for (i = 0; i < pathArr.length; i++) {
grunt.file.expand(pathArr[i]).forEach(function (dir) {
src.push(dir);
});
}
// set the config for this modulename-directory
concat = {
dist: {
src: [src.join(",")],
dest: 'app_min_safe/app/min/app.js'
}
};
// save the new concat configuration
grunt.config.set('concat', concat);
// when finished run the concatinations
grunt.task.run('concat');
}
grunt.registerTask("read-folder-concat", "read folder dynamically and concat it.", function () {
readFolderAndConcat(["app/*.js", "app/modules/js/*/*.js"]);
});
};
})();
Please help me understand what is the issue in my concat task.
Working on Windows I have installed Ruby and the Ruby DevKit to get things working with Cucumber. Now I have the following basic setup:
/app
/features
example.feature
/step_definitions
example.steps.js
In the example.feature file I have:
Feature: This is an example feature
In order to learn Cucumber
As a developer
I want to make this feature pass
Scenario: wrote my first scenario
Given a variable set to 1
When I increment the variable by 2
Then the variable should contain 3
And in the example.step.js file I have:
'use strict';
module.exports = function () {
this.givenNumber = 0;
this.Given(/^a variable set to (\d+)$/, function(number, next) {
this.givenNumber = parseInt(number);
next();
});
this.When(/^I increment the variable by (\d+)$/, function (number, next) {
this.givenNumber = this.givenNumber + parseInt(number);
next();
});
this.Then(/^the variable should contain (\d+)$/, function (number, next) {
if (this.givenNumber != number)
throw(new Error("This test didn't pass, givenNumber is " + this.givenNumber + " expected 0"));
next();
});
};
Now, when I run 'cucumber' from the /app dir I keep getting the folowing output:
1 scenario (1 undefined)
3 steps (3 undefined)
0m0.004s
I tried moving around the files, adding the --require option, etc. but nothing seems to be helping.
Any ideas?
Apparently this cannot be executed directly using the 'cucumber' command.
Settings things up using grunt and the grunt-cucumber task seems to be working as expected:
My Gruntfile.js
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
cucumberjs: {
src: 'features',
options: {
steps: 'features/step_definitions',
format: 'pretty'
}
}
});
grunt.loadNpmTasks('grunt-cucumber');
grunt.registerTask('default', ['cucumberjs']);
};
Additionally: if you are using protractor. It has cucumber build in. Just create the right config for protractor (protractor.conf.js):
exports.config = {
specs: [
//'e2e/features/*.feature'
'**/*.feature'
],
capabilities: {
'browserName': 'chrome'
},
baseUrl: 'http://localhost:9000/',
framework: 'cucumber'
}
I am using the code bellow for arguments which are using in protractor configuration file
protractor: {
options: {
keepAlive: true,
configFile: "test/config.js",
args:{
params:{
user:"user1",
password:"password1"
}
}
},
and retrieving in protractor conf file as browser.params.user,browser.params.password
These are working files.
I want to change the user and password values from command.
How to change the values?
This is a simple work around:
When you pass a parameter to your grunt task:
grunt e2e --user=alex --password=password
it's available as
grunt.option('user')
You can then edit the values you have in the config using:
var protConfig = grunt.config.get('protractor');
protConfig.options['someKey']=newValue;
grunt.config('protractor', protConfig);
grunt.task.run('protractor');
Not sure this is the best way to go about it, but it's working fine for me.
Also notice that we're wrapping the protractor task rather than calling it right away
how to fetch --user argument in protractor Specs?
In the code below I register a task "myprotractor" and whatever comes after the task as argument will go as parameter into the anonymous function:
grunt myprotractor:dev:pwd
module.exports = function(grunt) {
grunt.registerTask('myprotractor', function(user, pwd) {
console.log(user + pwd);
grunt.config('protractor', {
options: {
keepAlive: true,
configFile: "test/config.js",
args: {
params: {
user: user,
password: pwd
}
}
}
});
//here I am running the task
grunt.task.run([
'protractor'
]);
});
};
If you need you can configure 2 targets for protractor, having some common configuration and the args being set depending if you wish them from cmd or from config.
grunt myprotractor:cmd:dev:pwd
module.exports = function(grunt) {
grunt.registerTask('myprotractor', function(target, user, pwd) {
console.log(user + pwd);
grunt.config('protractor', {
options: {
keepAlive: true,
configFile: "test/config.js"
},
cmd: {
options: {
args: {
params: {
user: user,
password: pwd
}
}
}
},
config: {}
});
//here I am running the task with a target
grunt.task.run([
'protractor:' + target
]);
});
};
I am using a configuration file with JSON format containing names of other files which I concatenate when one of the files is changed. It works great so far, but I want to make the Grunt to reload the configuration file once it's changed (I remove or add something to the JSON) and update other task options (the concat task).
Here is my simplified Gruntfile.js:
module.exports = function(grunt) {
function getModules() {
var modules = grunt.file.readJSON('src/js/modules.json').modules;
for ( var module in modules ) {
if ( modules.hasOwnProperty(module) ) {
modules[module] = 'src/js/modules/' + modules[module] + '.js';
}
}
modules.push('src/js/scripts.js');
return modules;
}
var modules = getModules();
grunt.initConfig({
concat: {
options: {
separator: ';',
},
dist: {
src: modules,
dest: 'assets/js/scripts.min.js',
},
},
watch: {
js_modules: {
files: ['src/js/modules.json'],
tasks: ['reload_modules', 'concat'],
options: {
spawn: false,
livereload: true,
},
}
}
});
grunt.registerTask('reload_modules', "Reload JavaScript modules", function() {
modules = getModules();
});
};
As you can see I have some attempt to solve my problem, but the updated modules variable is not used in the concat task. The task uses the variable value loaded when the grunt default task is started.
You should be able to overwrite the config using grunt.config.merge:
var config = {
// ...
};
grunt.config.init(config);
grunt.registerTask('reload_modules', "Reload JavaScript modules", function() {
config.concat.options.dist.src = getModules();
grunt.config.merge(config);
});
http://gruntjs.com/api/grunt.config