Importing JSON file in Cucumber Protractor framework - json

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

Related

Returning json from .csv asset in nuxt api

Using Nuxt 3, I am struggling to do something that appears simple: I would like to get a list of restaurants from an api served by nuxt/nitro in order to use it on the client side. My original file, is a .csv file stored under assets/: assets/list.csv.
Here is what I have in my component .vuefile:
//...
const { restaurants } = await useFetch('/api/restaurants')
//...
And the content of server/api/restaurants.js:
import csv from 'csvtojson'
export default defineEventHandler(async(event) => {
const data = await csv().fromFile('~/assets/list.csv')
return { data }
})
But I get an error "[500] File does not exist". I've tried many variants but always get an error here or there. Could you help me figure out the solution? Thanks.
Actually solved by realizing the following:
As the doc suggests, the assets/ directory is for assets that are processed by the bundler (Vite or Webpack). Nuxt won't serve files in the assets/ directory unless nuxt.config.ts is configured with the appropriate loader (e.g. a csv loader). Hence the 500 error.
Nuxt Content, on the other hand, is useful to automatically parse a .csv file located in the content/ directory:
In nuxt.config.ts:
modules: ["#nuxt/content"]
In the component .vue file, the following will expose the parsed csv in data.body:
const { data } = await useAsyncData("list", () => queryContent("/list").findOne())
The beauty of nuxt is that you don't need to import anything, it does it for you.

How to access any .json from windows file explorer in vuejs

I looked up how to access a .json file without saving it to my code base but was not able to find it - all posts are like this one: How to acces external json file objects in vue.js app
where they assumed that I could save the .json file in the code base like so: import json from './json/data.json' - they are going to call it json, it is in json folder from the file named data.json.
In my case, on the contrary, when the user tries to read their own .json file saved in their windows file explorer's "Download" folder, there can be one or multiple files, and the user will select any one of them to be accessed and read by the website.
Me as a developer don't own the file that the user will select, don't know which file the user will choose, therefore don't know the name of the file or the file content, and so, I cannot have that file saved in the code base.
Is there a way for me to enable the user to select any .json file they want, have that accessed and read?
Thank you.
UPDATE: from the suggestions from the comment section, fileSelector appears as null in the dev tool
<input type="file" id="file-selector" accept="application/JSON" multiple>
interface HTMLInputEvent extends Event {
target: HTMLInputElement & EventTarget;
}
mounted() {
const fileSelector = document.getElementById('file-selector');
fileSelector.addEventListener('change', (event: HTMLInputEvent) => {
let files: any = event.target.files[0];
const fileList = event.target.files;
console.log(fileList);
});
}
Apparently you're using Typescript, so your error is at runtime or at build time?
the type of the event argument doesn't seem correct to me, try:
fileSelector.addEventListener('change', (event: Event) => {
const files = (e.target as HTMLInputElement).files
})

vuejs: the correct path of local json file for axios get request

In my Vue project, I have mocked some data for next step development. I already save the test data in a json file. And my vue project is typical one created with Vue-Cli, and the structure for my project goes as following:
My_project
build
config
data
service_general_info.json
node_modules
src
components
component-A
component-A.vue
as you can see, all the folders are created by the vue-cli originally. And I make a new folder data and place the test data json file inside.
And I want to read in the data by axios library in an event handling function inside the component of component-A as following:
methods: {
addData() {
console.log('add json data...');
axios.get('./../../data/service_general_info.json');
},
},
I use relative path to locate the target file.But get 404 error back. So how to set the path correctly? Currently I am running the dev mode in local host.
The error message is: GET http://localhost:8080/data/service_general_info.json 404 (Not Found)
In Vue-cli project, axios can't get data from custom folder.
You should use static folder to save test json file.
So you should change axios call like this:
axios.get('/static/service_general_info.json');
This will get data from json.
If you are doing just for sake of testing then you can save it in public folder and access it directly on http root.
e.g. I have the file results.json in public folder then I can access it using http://localhost:8080/results.json
For me it didn't work using static folder. I had to put it in public folder.
I put json folder in public & then accessed it like below.
getCountries() {
return axios.get('json/country-by-abbreviation.json', { baseURL: window.location.origin })
.then((response) => { return response.data; })
.catch((error) => {
throw error.response.data;
});
}
When the http call is made from the server, axios has no idea that you're on http://localhost:8080, you have to give the full url.
Like this:
methods: {
addData() {
console.log('add json data...');
axios.get('http://localhost:8080/data/service_general_info.json');
},
},
I had this same issue, only the above solutions wouldn't work as it is being uploaded to a subdirectory. I found I needed to put it in the public/assets folder and use:
axios.get(process.env.BASE_URL+'assets/file.json')
While in vue.config.js I have set the local and live paths
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/path/to/app/'
: '/'
}
You can simply read a static JSON file using import. Then assign in data.
import ServiceInfo from './../../data/service_general_info.json';
export default{
data(){
return {
ServiceInfo
}
}
}

Unable to print complete JSON using console.log

I am trying to import JSON file into Sample variable but only first few characters are displayed from Sample variable.
The sample.json is 20,00,000 characters, When i print Sample variable on Console only first 3,756 characters are printed.Is there any limitations on the characters that can be printed through console.log?
Complete data persists in Sample variable, I verified it by searching for strings that occur at the end of sample.json file
var Sample = require('./sample.json');
export default class proj extends Component {
constructor(props) {
super(props);
this.state = {
locations: [],
};
}
loadOnEvent() {
console.log(Sample);
//this.state={ locations : Sample };
}
}
Is there any other way to print data in Sample variable.
You have to convert json to string using JSON.stringify before logging.
/* ... */
loadOnEvent() {
console.log(JSON.stringify(Sample));
//this.state={ locations : Sample };
}
/* ... */
Try to use another way to load. Use fetch if file is remote or use fs if file is local.
If it is memory problem supposed by #Shota consider to use server side processing requests to json file. It is good solution to setup microservice which load json file at startup and handle requests to data struct parsed from json file.
Answer for webpack use case:
Configure webpack to use file-loader or copy-webpack-plugin for specifically this file because it enough big. Consider to load it in parallel with webpack bundle. If your application have big parts which need not each case they must be moved to separated bundles.

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
});
);
},