JSON report not generating for failed scenarios using protractor - json

If my scenarios got failed the JSON report not generating. But for passes scenarios I can able to see the JSON report.
Please find my config file as below.
In comment prompt console I can able to see the failure message:
W/launcher - Ignoring uncaught error AssertionError: expected false to equal true
E/launcher - BUG: launcher exited with 1 tasks remaining

You can save the report by using a hook, so don't generate the file form the protractor.conf.js file, but use a cucumber-hook for it.
The hook can look like this
reportHook.js:
const cucumber = require('cucumber');
const jsonFormatter = cucumber.Listener.JsonFormatter();
const fs = require('fs-extra');
const jsonFile = require('jsonfile');
const path = require('path');
const projectRoot = process.cwd();
module.exports = function reportHook() {
this.registerListener(jsonFormatter);
/**
* Generate and save the report json files
*/
jsonFormatter.log = function(report) {
const jsonReport = JSON.parse(report);
// Generate a featurename without spaces, we're gonna use it later
const featureName = jsonReport[0].name.replace(/\s+/g, '_').replace(/\W/g, '').toLowerCase();
// Here I defined a base path to which the jsons are written to
const snapshotPath = path.join(projectRoot, '.tmp/json-output');
// Think about a name for the json file. I now added a featurename (each feature
// will output a file) and a timestamp (if you use multiple browsers each browser
// execute each feature file and generate a report)
const filePath = path.join(snapshotPath, `report.${featureName}.${new Date}.json`);
// Create the path if it doesn't exists
fs.ensureDirSync(snapshotPath);
// Save the json file
jsonFile.writeFileSync(filePath, jsonReport, {
spaces: 2
});
};
}
You can save this code to the file reportHook.js and then add it to the cucumberOpts:.require so it will look like this in your code
cucumberOpts: {
require: [
'../step_definitions/*.json',
'../setup/hooks.js',
'../setup/reportHook.js'
],
....
}
Even with failed steps / scenario's it should generate the report file.
Hope it helps

Related

ipfs add single item from type FileStream

I was expecting ipfs.add with onlyHash:true to return the same hash as onlyHash:false, what don't I understand here?
data.file is coming from a file upload const data = await request.file(); which is a FileStream
const onlyHash = await ipfs.add(data.file, {
pin: false,
onlyHash: true,
});
console.log(onlyHash.path) // QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH
and
const notOnlyHash = await ipfs.add(data.file, {
pin: true,
onlyHash: false,
});
console.log(notOnlyHash.path) // QmdPcEi2MAiJmSvv1YHjRafKueDygQNtL33yX6WRgDYPXn
if I cat either cid with ipfs cat QmdPcEi2MAiJmSvv1YHjRafKueDygQNtL33yX6WRgDYPXn ipfs just hangs and never shows me the content
if I add the file with ipfs add text.txt the cid does match QmSiLSbT9X9TZXr7uvfBgZ2jWpekSGNjYq3cCAebLyN8yD but I can now cat it and get its contents
I tried using ipfs.addAll
https://github.com/ipfs/js-ipfs/blob/master/docs/core-api/FILES.md#ipfsaddallsource-options
but I get this error
ERROR (71377): Unexpected input: single item passed - if you are using ipfs.addAll, please use ipfs.add instead
Do I need to buffer the file and then add it to IPFS or save it to disk and then add it?
I can write the file to disk just fine
await pump(data.file, fs.createWriteStream(data.filename));
trying to avoid using server resources as much as possible

Error.invalid json response Unexpected token T in JSON at position 0 sanity nextjs typscript [duplicate]

This question already has an answer here:
Fetch error when building Next.js static website in production
(1 answer)
Closed 4 months ago.
hey i guys i have a question i did the build with react and typscript and sanity cms but the problems is when im trying to deploy the build to varcel it keeps rejecting it sayning that FetchError: invalid json response body at https://portfolio2-1-wn3v.vercel.app/api/getExperience reason: Unexpected token T in JSON at position 0 while it works on my local machine it find all the data and everything ... i read that it might be a problem somewhere down the line with getStaticProps or when fetching json and yes i did change the enviroment varibals from base_url in http 3000 to the varcel ones but other than that i have no idea what else i should do .... if anyone has any expirince with this kind of errors ? here is my code for the
`import {Experience} from '../typings'
export const fetchExperiences = async () =>{
const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getExperience`)
const data = await res.json()
const projects:Experience[] = data.experience
return experience
}`
the getExercise.ts file has all the api request
import type{NextApiRequest,NextApiResponse} from 'next'
import {groq} from 'next-sanity';
import {sanityClient} from '../../sanity';
import {Experience} from '../../typings'
const query = groq`
*[_type == "experience"]{
...,
technologies[]->
}
`;
type Data ={
experience:Experience[]
}
export default async function handler(
req:NextApiRequest,
res:NextApiResponse<Data>,
){
const experience:Experience[]= await sanityClient.fetch(query)
res.status(200).json(JSON.parse(JSON.stringify({experience})))
}
and this is the index.ts file part
export const getStaticProps: GetStaticProps<Props> = async() => {
const experience : Experience[] = await fetchExperiences();
const skills : Skill[] = await fetchSkills();
const projects : Project[] = await fetchProjects();
const socials : Social[] = await fetchSocials();
return{
props:{
experience,
skills,
projects,
socials,
},
revalidate:10
}
}
The error link you see (https://portfolio2-1-wn3v.vercel.app/api/getExperience) is the preview deployment link from vercel. That means, everytime you deploy to vercel it will create this preview link: https:// yourappname-(some unique deployment link).vercel.app.
However, in your api you pass ${process.env.NEXT_PUBLIC_BASE_URL} which will work on your local and probable on production, but it will not on your preview deployments (staging).
To avoid this, unfortunately you cannot only give /api/getExperience as only absolute URL's are supported. Therefore, I suggest the following approach by avoiding the API call as suggested in the [nextjs docs][1]:
you create an experience-queries.ts file in lib/
you add your GROQ query in there
export const getExperiences = groq`*[_type == "experience"]{..., technologies[]->}`
In index.ts, in getStaticProps you call getExperiences
const experiences = await sanityClient.fetch(getExperiences);
Note: Be careful with naming between experience (one single item) and experiences (a list of items) -> make sure you name if as you intend to get them.
[1]: https://nextjs.org/docs/basic-features/data-fetching/get-static-props#write-server-side-code-directly

Data from Mongo db arrives later than data from a json file on server in Next js App

I have a form that currently uses data from a json file.
The data is retrieved like so
const categoryList = require('../data/categories.json');
I am changing this to retrieve data from an api which fetches data from mongodb.
http://localhost:3000/api/categories
The above link gives me same results as the json file.
import { getCategories } from '../../lib/hooks';
....
const PostEditor = () => {
const [categories] = getCategories(); // this gives me all the categories from api as an array
console.log("categories from db")
console.log(categories)
const catList = require('../data/categories.json'); // same result as above
console.log("cat list from json file")
console.log(catList)
...
...
return (
<>
...
...
<Autocomplete
multiple
options={catList} // Data from db(categories field) does not reach here.
limitTags={2}
From the above code, both console log from db and console log from the json file have same values in browser.
The console log in command prompt shows values from db as "undefined". I think the data from db is not reaching the page in time but from the json file it does.
How to solve this problem?
I use Next js.
Edit:
I moved the data fetching from Api into a parent component (directly under pages) and passed the categories as props to the child component
<PostEditor categories={cats}/>
Still facing the same issue.
As mongodb data is external, so it's taking time to load. You have to call asynchronously. Check like this:
const PostEditor = async() => {
const [categories] = await getCategories();
...
}

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

Casperjs requiring local JSON file

I am trying to require local JSON files (such as config files) and pass those JSON objects to evaluate. For each config file, evaluate function will return different results depending on the given CSS selectors from config JSON.
For example:
The folder structure is like this:
rootdir
casperExample.js
config/
|_example.json
example.json
{
"title": "$('div.pointslocal-details-section h1').text();",
"date": "$('div.pointslocal-details-time p').text();"
}
casperExample.js
var casper = require('casper').create();
var require = patchRequire(require);
var json = require('./config/example.json');
casper.start('https://website/to/be/scraped');
casper.then(function(){
this.echo(json);
pageData = this.evaluate(function(json){
var results = {};
results['title'] = json.title;
results['date'] = json.date;
return results;
}, json);
this.echo(pageData);
});
casper.run(function(){
this.exit();
});
This is what I get when I try to run: casperjs casperExample.js
CasperError: Can't find module ./config/example.json
C:/Users/msarc/coding/casper/rootdir/phantomjs:/code/bootstrap.js:307 in patchedRequire
and if I use var json = require('./config/example'); (without .json) I get
SyntaxError: Expected token '}'
C:/Users/msarc/coding/casper/rootdir/phantomjs:/platform/example.js:32 in loadModule
C:/Users/msarc/coding/casper/rootdir/phantomjs:/platform/bootstrap.js:282 in _compile
C:/Users/msarc/coding/casper/rootdir/phantomjs:/platform/bootstrap.js:126 in .js
C:/Users/msarc/coding/casper/rootdir/phantomjs:/platform/bootstrap.js:278 in _load
C:/Users/msarc/coding/casper/rootdir/phantomjs:/platform/bootstrap.js:311 in require
C:/Users/msarc/coding/casper/rootdir/phantomjs:/platform/bootstrap.js:263 in require
C:/Users/msarc/coding/casper/rootdir/phantomjs:/code/bootstrap.js:302 in patchedRequire
I want to eventually make multiple config files, each with different selectors for different websites. casperjs version: 1.1.4 phantomjs version: 2.1.1
You're requireing json file as if it were a javascript module, which it is of course not, hence the error. Instead you need to read the file and process it is JSON structure:
var fs = require('fs');
var fileContents = fs.read('config/_example.json');
var json = JSON.parse(fileContents);
Then proceed working as planned.