Grunt - read json object from file - json

I want to use grunt-hash plugin for renaming my js files.
This plugin create a new file containing map of renamed files:
hash: {
options: {
mapping: 'examples/assets.json', //mapping file so your server can serve the right files
Now I need to fix links to this files by replacing all usages (rename 'index.js' to 'index-{hash}.js') so I want to use grunt-text-replace plugin.
According to documentation I need to cofigure replacements:
replace: {
example: {
replacements: [{
from: 'Red', // string replacement
to: 'Blue'
}]
}
}
How could I read json mapping file to get {hash} values for each file and provide them to replace task?

grunt.file.readJSON('your-file.json')
is probably what you are looking for.
I've set up a little test. I have a simple JSON file 'mapping.json', which contains the following JSON object:
{
"mapping": [
{"file": "foo.txt"},
{"file": "bar.txt"}
]
}
In my Gruntfile.js I've written the following simple test task, which reads the first object in the 'mapping'-array:
grunt.registerTask('doStuff', 'do some stuff.', function() {
mapping = grunt.file.readJSON('mapping.json');
grunt.log.write(mapping.mapping[0]["file"]).ok();
});
When invoking the Grunt task, the console output will be as follows:
$ grunt doStuff
Running "doStuff" task
foo.txtOK
Done, without errors.
I hope this helps! :)

Related

Importing JSON file in Cucumber Protractor framework

I want to keep my test data in a JSON file that I need to import in cucumber-protractor custom framework. I read we can directly require a JSON file or even use protractor params. However that doesn't work. I don't see the JSON file listed when requiring from a particular folder.
testdata.json
{
"name":"testdata",
"version":"1.0.0",
"username":"1020201",
"password":"1020201"
}
Code in the Config.js
onPrepare: function() {
var data = require('./testdata.json');
},
I don't see the testdata.json file when giving path in require though its available at the location.
I wish to access JSON data using data.name, data.version etc.
Following is my folder structure:
You should make sure your json file is located in the current directory & and in the same folder where your config file resides as you are giving this path require('./testdata.json'); -
There are many ways of setting your data variables and accessing them globally in your test scripts -
1st method: Preferred method is to use node's global object -
onPrepare: function() {
global.data = require('./testdata.json');
},
Now you could access data anywhere in your scripts.
2nd Method Is to use protractor's param object -
exports.config = {
params: {
data: require('./testdata.json');
}
};
you can then access it in the specs/test scripts using browser.params.data

Webpack - Yaml -> JSON -> Extract file

I have a YAML file with a few translations. I need to transform these files into a JSON file. I've tried using yaml-import-loader and json-loader but I get an error.
Here's my setup:
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractEnglish = new ExtractTextPlugin('lang/en.js');
module.exports = {
entry: [
'./src/locales/application.en.yml',
],
output: {
filename: 'english.js',
},
module: {
strictExportPresence: true,
rules: [
{
test: /\.en\.yml$/,
use: extractEnglish.extract({
use: [
// { loader: 'json-loader' },
{
loader: 'yaml-import-loader',
options: {
output: 'json',
},
}],
}),
},
],
},
plugins: [
extractEnglish,
],
};
And the error I get:
Users/xxx/Documents/Project/node_modules/extract-text-webpack-plugin/dist/index.js:188
chunk.sortModules();
^
TypeError: chunk.sortModules is not a function
at /Users/xxx/Documents/Project/node_modules/extract-text-webpack-plugin/dist/index.js:188:19
Same error whether or not the json-loader is commented or not.
I really don't understand what is going wrong.
Versions:
"webpack": "2.6.1",
"extract-text-webpack-plugin": "^3.0.0",
"json-loader": "^0.5.7",
Not sure if this will help your situation but I recently found a solution to my i18n loading problem. I do this to extract YAML into JSON files upfront as I use angular-translate and needed to load files dynamically and on-demand. I avoid extract-text-webpack-plugin and use only loaders: file-loader and yaml-loader.
First I setup the import of my .yaml files near the beginning of source (in my case a specific chain of import files for webpack to process)
import "./i18n/en.user.yaml";
I updated webpack config to translate YAML to JSON and have it available to load dynamically (everything originates from my 'src' directory, hence the context):
rules: [{
test: /.\.yaml$/,
use: [{
loader: 'file-loader',
options: {
name: '[path][name].json',
context: 'src'
}
},{
loader: 'yaml-loader'
}]
}]
This will translate my yaml file(s) and export them to my public directory, in this case at '/i18n/en.user.json'.
Now when angular-translate uploads my configured i18n settings via $http on-demand, it already has the parsed YAML and avoids having to parse it with js-yaml (or similar) on the front end.
A relatively old question, but I found it while searching for a solution to the same problem, so I thought it worth to chip in.
If you're not really using translation files in your code (i.e. you never import and use them directly) then using a Webpack loader is not the most elegant solution (you'd be forced to import them just so that the loader could be triggered and perform the conversion).
An alternative would be to use the CopyWebpackPlugin instead: it supports a transform option, which takes a function receiving the content of the file as a Buffer.
With a YAML parser (like js-yaml) as an additional dependency, adding this to your Webpack configuration would work:
const yaml = require('js-yaml');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
// OTHER WEBPACK CONFIG HERE
plugins: [
new CopyWebpackPlugin({
patterns: [
{
from: 'i18n/**/*',
to: 'i18n/[name].json',
transform(content) {
return Buffer.from(
JSON.stringify(
yaml.load(content.toString('utf8'), {
schema: yaml.JSON_SCHEMA
})
),
'utf8'
)
}
}
]
})
]
}
The i18n folder in the above example would contain your .yml translations.
The Copy plugin would load them, convert them to JSON, and save them in the output folder under i18n/ (as specified by the to option).

How to bootstrap a JSON configuration file for an Angular 2 module without using a http.get approach

I have one json file at root:
config.json
{ "base_url": "http://localhost:3000" }
and in my service class, I want to use it in this way:
private productsUrl = config.base_url + 'products';
I've found a ton of posts with either solutions that require a http.get request to load that one file to get that one variable or outdated solutions for angular.js (angular 1)
I cant believe there isnt an easier way to include this file that we already have in place without having to make an additional request to the server.
In my opinion, I would have expected that at least the bootstrapping function would be able to provide this kind of functionality, something like:
platformBrowserDynamic().bootstrapModule(AppModule, { config: config.json });
btw, this works, but its not the ideal solution:
export class Config {
static base_url: string = "http://localhost:3004/";
}
and the use it where you need it:
private productsUrl = Config.base_url + 'products';
Its not ideal, because I will have to create the class (or replace properties) in a build script. (exactly what I was thinking to do with the config.json file).
I still prefer the config.json file approach, since it would not be intrusive with the TypeScript compiler. Any ideas how to do are welcome and really appreciated!
This link explains how to use System.js to load json files in an angular app.
Special thanks to #eotoole that pointed me in the right direction.
If the link above is not clear enough, just add a map into the System.js conf. like this:
map: { 'plugin-json': 'https://unpkg.com/systemjs-plugin-json' }*
*(using external package)
or
map: { 'plugin-json': 'plugin-json/json.js' }**
**if you download the plugin from:
official system.js plugin
now I can use:
const config = require('./config.json');
anywere in my app.
and since it is official from the "systemjs" - guys, I feel comfortable using it to load app settings like base_url or other endpoints.
Now I need to figure out how to encapsulate this logic for testing purposes. Maybe requiring the file in its own class and replacing the values for the specific test case.
Are you using webpack? If you are, and you can just do
const config = require('./config.json');
#Injectable()
export class MyService {
private config:any = config;
....
}
in your webpack config you will need the json-loader
...
module: {
...
loaders: [
...
{
test: /\.json$/,
loaders: ["json-loader"]
},
...
]
}
...

How to generate Json file after execution finish

I'm working with cucumber and protractor and to generate reports i'm using
cucumber-html-reporter I already add the configuration to generate the report
var options = {
theme: 'bootstrap',
jsonFile: 'reporter/cucumber_report.json',
output: 'reporter/cucumber_report.html',
reportSuiteAsScenarios: true,
launchReport: true,
};
defineSupportCode(function({ After }) {
After((scenario)=> {
reporter.generate(options);
});
});
but i'm not generate the json file with this code, I search in google and the code to generate the json file should be add into the cucumberOpts in the conf.js but i'm not sure what's the code should be into cucumberOpts to generate the json file and the convert into report.
I hope you can help me guys.
Maybe this can help you, it's for Typescript but the code is almost the same. You can export the file in an After-hook. The link is for CucumberJS 1, if you look into the master branch you can also find the CucumberJS 2 solution
The advantage of this in comparison to generating the JSON file with the format option is that you can modify the JSON before saving
Hope it helps
For people that still have this problem, in my case the problem was that I was using cucumber v1 instead cucumber v2. For this case I should use registerHandler instead After this is the complete example:
defineSupportCode(function({registerHandler}) {
registerHandler('AfterFeatures', function (features) {
reporter.generate(options);
});
});
Hope this help u guys.

Generating JSON object of the tests ran using Protractor?

I'm relatively new to end to end testing with Protractor, Mocha and Yadda (for integration with Mocha so I can use Gherkin and step definitions).
I've seen a plugin called Mochawesome which generates an HTML report which can be viewed offline, along with this JSON object of the test results, all of which contained in a 'reports' folder.
I presume it's Mochawesome which generates these JSON objects as the HTML page seems to have corresponding tags etc. Is there any way to generate a JSON object of the tests ran without the HTML reporter? The idea was to create my own sort of 'dashboard' containing information about the tests based on the JSON information.
Yes you can create a JSON report of your specs/tests with protractor.You just have to put resultJsonOutputFile: './Report.json' in your config file.
your config file should somewhat look like this:
exports.config = {
directConnect: true,
capabilities: {
'browserName': 'chrome'
},
baseUrl: 'http://juliemr.github.io/protractor-demo/',
framework: 'jasmine2',
specs: ['*spec.js '],
allScriptsTimeout: 180000,
getPageTimeout: 180000,
jasmineNodeOpts: {
defaultTimeoutInterval: 180000
},
resultJsonOutputFile: './Report.json', // It would create report.json file in your current folder
onPrepare: function () {
browser.driver.manage().window().maximize();
browser.ignoreSynchronization = true;
}
};
You can consume this json report and use it in your way!
I'm not sure about generating JSON object directly in protractor. But what i know is that, we can generate results in XML and then convert xml to json by writing some customized code.
Code for generating XML reports are as follows:
framework: "jasmine2",
onPrepare: function() {
var jasmineReporters = require('jasmine-reporters'),
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
savePath: '../result/',
filePrefix: ‘report’,
consolidateAll: true
});
);
},