Can someone please assist in following:
I have to assert array with x elements (usually not more than 6 or 7) and if there is any duplicates, it has to throw error - or step to fail. So far I did the following:
Cypress.Commands.add('addTextElementIntoArray', (list) => {
var textsArray = []
cy.xpath(list).each(($el) => {
const text = $el.text().replace(' ', '')
textsArray.push(text)
cy.log(text)
})
})
Tried this solution: Find duplicates, but it does not work in Cypress. How can I solve this?
Thank you in advance
Found solution, and here it is:
Cypress.Commands.add('addTextElementIntoArray', (list) => {
var textsArray = []
var non_unique = []
cy.xpath(list)
.each(($el) => {
const text = $el.text().replace(' ', '')
textsArray.push(text)
cy.log(text)
non_unique = textsArray.filter((item, i) =>
textsArray.includes(item, i + 1)
)
})
.then(() => {
expect(non_unique.length).equal(0)
})
})
Using the answer from the linked question in Cypress,
Cypress.Commands.add('listHasNoDuplicates', (list) => {
cy.xpath(list)
.then($els => [...$els].map(el => el.innerText.trim()))
.then(texts => {
const unique = new Set(texts)
expect(texts.length).to.eq(unique.size)
})
})
})
Related
What I want is to join my arrays that I get from my map function.
I tried to do with reduce :
const onFinish = (values) => {
values.fields.map((el, idx) => {
console.log({ ...el, index: idx }); // this `console.log` prints me one array after the other
}).reduce((acc, x) => {console.log(acc,x)}); // I tried with `reduce` but it prints me null
Also tried to do with useState:
const onFinish = (values) => {
values.fields.map((el, idx) => {
if (myArray === null){
setMyArray(() => {
return { ...el, index: idx };
});
}
else {
setMyArray(() => {
return {...myArray,...el, index: idx };
});
}
});
console.log(myArray) // at my first call to this const onFinish myArray is printed as [] and at the second it prints with the last object only
};
Someone knows how to get these objects joined/merged ?
Sample data the way that it's print:
How I want to be:
Altghough it is still not very clear from the screenshots (always prefer to use text and not images for data/code), it looks like you want
const onFinish = (values) => {
const updatedValues = values.fields.map((field, index) => ({...field, index}));
console.log( updatedValues );
}
Does this help?
if (myArray === null){
setMyArray(() => {
return [{ ...el, index: idx }];
});
}
else {
setMyArray(() => {
return [...myArray, {...el, index: idx }];
});
}
const url = `https://catfact.ninja/fact?max_length=140`;
const getFact = () => {
return fetch('https://catfact.ninja/fact?max_length=140')
.then(res => res.json())
}
const createFactDiv = (fact) => {
const factContainer = document.createElement('div')
const setup = document.createElement('p')
setup.innerText = fact.fact
factContainer.append(setup)
return factContainer
}
const appendFact = (factDiv) => {
const factContainer = document.getElementById('factContainer')
factContainer.append(FactDiv)
}
document.addEventListener('DOMContentLoaded', () => {
})
getFact().then ((fact) => {
const FactDiv = createFactDiv(fact)
append.fact (FactDiv)
})
I have tried several things, fairly new to JS and it is tricky. I am trying to create an app that displays cat facts. I was seeing the DIV with the FACT inside correctly in the console.log in the elements of the DOM, but now I don't see it and I keep seeing
Uncaught (in promise) ReferenceError: append is not defined
Any idea what to do? Much appreciated !
Yep, it's our old friend spelling errors! Here is some working code:
const url = `https://catfact.ninja/fact?max_length=140`;
const getFact = () => {
return fetch('https://catfact.ninja/fact?max_length=140')
.then(res => res.json())
}
const createFactDiv = (fact) => {
const factContainer = document.createElement('div');
const setup = document.createElement('p');
setup.innerText = fact.fact;
factContainer.append(setup);
return factContainer
}
const appendFact = (factDiv) => {
const factContainer = document.getElementById('factContainer');
factContainer.append(factDiv);
}
//This is unused
/*
document.addEventListener('DOMContentLoaded', () => {
})
*/
getFact().then ((fact) => {
const factDiv = createFactDiv(fact);
appendFact(factDiv);
})
This is why it's important to consistently use camelCase:
In appendFact() you took a factDiv parameter but then tried to use FactDiv, which doesn't exist in that function
As noted by Robin, you typed append.fact(FactDiv) instead of appendFact(FactDiv)
This should be refactored to appendFact(factDiv) to stick with camelCase.
Also watch your spacing, and I like to have semicolons at the end of my lines also!
I am the new guy in the JS and reactJS.
I want to get info from API to an array. I made API that show all the info from my DB.
It looks like this :
const [tempNew, setTempNew] = useState([]);
const getAllWeatherCelsius = () => {
fetch('http://localhost:5000/weather')
.then(response => {
return response.json();
})
.then((jsonData) => {
let tmpArray = [];
for (var i = 0; i < jsonData.length; i++) {
tmpArray.push(jsonData.dayCelsius[i]) <---- here is the error
}
setTempNew(tmpArray);
})
}
Im want to collect all values from "dayCelsius" line into array.
What i need to change in this code ? Thank you :)
Can you provide more info about the error? But You can try using the map function like
const tmpArray = jsonData.map(r => r.dayCelsius);
You can use map function to return the dayCelsius value of each element and store them in the tmpArray.
let tmpArray = jsonData.map((el, i) => el.dayCelsius);
So, what I understand is that you are facing difficulty in just getting the dayCelsius value from the array of objects you fetch from your API.
It is difficult to make out what the problem is as more info about the error is required to see what is going wrong.
What I have done differently here is instead of the for-loop and jsonData.dayCelsius[i], I have used data.map((r,e) => r.dayCelsius).
const [temp, setTemp] = useState([]);
const getAllWeatherCelsius = () => {
fetch('http://localhost:5000/weather', {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
}
})
.then(response => {
return response.json();
})
.then((data) => {
const tempArray = data.map((r,e) => r.dayCelsius);
setTemp(tempArray);
})
.catch(err => console.log(err));
}
I hope it helps you, have a good day :)
My code so far:
recentTracks.items.map(item => {
res.push({
trackName: item.track.name,
artistNames: item.track.artists.map(artist=>
{
console.log(artist.name);
return // not sure what to do here
})
})
})
res is the object and for each artist.name, I want to push it into the array but I'm not sure how.
You seem to be close there. Hard to tell what's inside item.track.artists, but let's assume there is a name attribute that stores the artist's name. Then do this:
const res = [];
recentTracks.items.map(item => {
res.push({
trackName: item.track.name,
artistNames: item.track.artists.map(artist => artist.name)
})
})
You can even shorten it a little further:
const res = recentTracks.items.map(item => {
return {
trackName: item.track.name,
artistNames: item.track.artists.map(artist => artist.name)
}
})
recentTracks.items.map(item => {
res.push({
trackName: item.track.name,
artistNames: item.track.artists.map(artist => artist.name)
})
})
I have to read a json file, I followed the following code: stackoverflow
Trying the example shown in the comment, but it's not working for me.
I have to read this file that I have locally, but I'm not succeeding.
Can you give me a hand?
Link: Codesandbox
Code:
fetch("/user.json")
.then(res => res.json())
.then(res => res.results)
.then(res => {
console.log(res);
let u = res.map((suggestion, i) => ({
label: suggestion.email,
name: suggestion.name.first,
surname: suggestion.name.last,
address: suggestion.location.street.name,
email: suggestion.email,
picture: suggestion.picture.thumbnail
}));
let options =
inputLength === 0
? []
: u.filter(suggestion => {
const keep =
count < 5 &&
suggestion.label &&
suggestion.label.slice(0, inputLength).toLowerCase() ===
inputValue;
if (keep) count += 1;
return keep;
});
this.setState({ options });
})
.catch(e => console.log("Er:", e));
You can just use import or require as follows:
const data = require("./myFile.json")
import data from "./myFile.json"