it ('check link', () => {
cy.visit(/)
var link1_value
var link2_value
var datasheet_value
cy.get('[class="classname"]').then(($link1) => {
if ($link1.find('[data-type="link1"]').length>0){
cy.get('[data-type="link1"]').invoke('text').as('link1')
cy.get('#link1').then((link1) => {
link1_value = 'Link1:' + link1
})
}
else {
link1_value= '0'
}
}) //there's another one like this for link2
cy.writeFile('txt.json', { link1: link1_value ,link2: link2_value })
})
The code above does not work because link1_value does not have any data. How should I add the value so that it will show in the json file?
To start with, wrap the cy.writeFile() in a .then().
it('check link', () => {
cy.visit('/')
let link1_value
let link2_value
let datasheet_value
cy.get('[class="classname"]').then(($link1) => {
if ($link1.find('[data-type="link1"]').length > 0) {
cy.get('[data-type="link1"]').invoke('text').as('link1')
cy.get('#link1').then((link1) => {
link1_value = 'Link1:' + link1
})
}
else {
link1_value = '0'
}
})
.then(() => { // delays the writeFile until after above code finishes
cy.writeFile('txt.json', { link1: link1_value, link2: link2_value })
})
})
You can also try with the cypress-if package
it('check link', () => {
cy.visit('/')
let link1_value
let link2_value
let datasheet_value
cy.get('[class="classname"]')
.find('[data-type="link1"]')
.if()
.then($link1 => link1_value = $link1.text())
.else()
.then(() => link1_value = '0')
.finally(() => {
cy.writeFile('txt.json', { link1: link1_value, link2: link2_value })
})
})
Without the variables (passing results down the chain)
it('check link', () => {
cy.visit('/')
cy.get('[class="classname"]')
.find('[data-type="link1"]')
.if()
.then($link1 => $link1.text())
.else()
.then(() => '0')
.finally(link1_value => {
cy.writeFile('txt.json', { link1: link1_value, link2: link2_value })
})
})
With the 2nd link
const getLink = (link) => {
return cy.get('[class="classname"]')
.find(`[data-type="${link}"]`) // backticks to insert "link" parameter
.if()
.then($link => $link.text())
.else()
.then(() => '0')
}
it('check link', () => {
cy.visit('/')
getLink('link1')
.then(link1_value => {
getLink('link2')
.then(link2_value => {
cy.writeFile('txt.json', {
link1: link1_value,
link2: link2_value
})
})
})
})
Related
I'm still figuring node.js and promises out.
There's an area in my code where I would like my sql statements to run sequentially.
I would like one sql statement to run once one sql statement is done. I'm not sure if I am implementing promises properly.
one of the sql statements:
var selectbotagentstoadd=new Promise((resolve,reject)=>{
var sql='SELECT tbltestbotagentstoadd.AgentID FROM tbltestbotagentstoadd WHERE tbltestbotagentstoadd.IDNumber=? AND tbltestbotagentstoadd.MSISDN=?;'
DB.query(sql,[agentidpassnum,agentnumber],function(err,results){
if (err){
return reject(err);
};
return resolve(results);
});
})
the promise statement:
await insertbotagentstoadd.then(()=>{
console.log("done with one");
})
.then(()=>{ selectbotagentstoadd.then((results)=>
{
AgenttoaddIDStore=[];
results.forEach(agent=>{
AgenttoaddIDStore.push({
AgentID:agent.AgentID
});
ctx.session.tempAgentID=agent.AgentID
});
console.log("agent ID: "+ctx.session.tempAgentID);
console.log("done with two");
})})
.then((results)=>{insertcctblricaagents
console.log("done with three");
})
.then((results)=>{selectcctblricaagents.then((result)=>{
console.log(result);
AgentnewIDStore=[];
result.forEach(agent=>{
AgentnewIDStore.push({
AgentID:agent.AgentID
})
ctx.session.AgentID=agent.AgentID
})
console.log("cctblricaagents agent ID: "+ ctx.session.AgentID);
console.log("done with four");
})})
.then(insertcctblricaagentsnum.then((result)=>{
console.log("done with five");
}))
.then(selectcctblricaagentsnum.then((result)=>{
console.log(result)
AgentIDStore=[];
result.forEach(agent=>{
AgentIDStore.push({
AgentID:agent.AgentID,
MainNumber:agent.MainNumber,
})
ctx.session.AgentID=agent.AgentID
ctx.session.agentnumber=agent.MainNumber
})
console.log("cctblricaagentsnum agent ID: "+ ctx.session.AgentID);
console.log("done with six");
}))
.then(insertcctblintblbotagents.then((result)=>{
console.log("done with seven");
}));
The results I get from the terminal:
Agent number: 27815567777
done with one
done with three
agent ID: 89
done with two
[]
cctblricaagents agent ID: null
done with four
If you properly return the promises in each of the then blocks, it should execute sequentially.
simplifying your code, for ex:
await insertbotagentstoadd
.then(() => {
console.log("done with one");
})
.then(() => selectbotagentstoadd)
.then((res) => {
console.log("done with two");
return res;
})
.then((results) => insertcctblricaagents)
.then((res) => {
console.log("done with three");
return res;
})
.then((results) => selectcctblricaagents)
.then((res) => {
console.log("done with four");
return res;
})
.then(() => insertcctblricaagentsnum)
.then((res) => {
console.log("done with five");
return res;
})
.then(() => selectcctblricaagentsnum)
.then((res) => {
console.log("done with six");
return res;
})
.then(() => insertcctblintblbotagents)
.then((res) => {
console.log("done with seven");
return res;
});
Edit:
How it will look with your calculation included:
await insertbotagentstoadd
.then(() => {
console.log("done with one");
})
.then(() => selectbotagentstoadd)
.then((results) => {
AgenttoaddIDStore = [];
results.forEach((agent) => {
AgenttoaddIDStore.push({
AgentID: agent.AgentID,
});
ctx.session.tempAgentID = agent.AgentID;
});
return AgenttoaddIDStore;
})
.then((res) => {
console.log("done with two");
return res;
})
.then((results) => insertcctblricaagents)
.then((res) => {
console.log("done with three");
return res;
})
.then((results) => selectcctblricaagents)
.then((result) => {
AgentnewIDStore = [];
result.forEach((agent) => {
AgentnewIDStore.push({
AgentID: agent.AgentID,
});
ctx.session.AgentID = agent.AgentID;
});
return AgentnewIDStore;
})
.then((res) => {
console.log("done with four");
return res;
});
Why am I asking this question (main return) is finsied, but board.writer is not drawing. how can i drawing this object
if my question is wrong way plz tell me . i will fix it
i tried this way
first use map function
make like this function renderUser = ({board_SEQ, content, writer,subject}) => { parameter}
const Home = () => {
const initboard = {
board_SEQ: '',
writer: '',
content: '',
subject: ''
};
const [boards, setBoard] = useState([]);
const load = () => {
axios.get('http://www.heon.shop:8080/api/boards')
.then((res) => {
const data = res.data;
setBoard(boards => [...boards, {
board_SEQ: (data[0].board_SEQ),
writer: data[0].writer,
content: data[0].content,
subject: data[0].subject
}]);
})
.catch((error) => {
console.log("error" + error);
}
);
}
useEffect(() => {
load();
console.log("useEffect");
}, []);
const renderUser = ({board_SEQ, content, writer, subject}) => {
return (
<div>
<li>he</li>
<li>{board_SEQ}</li>
<li>{content}</li>
<li>{writer}</li>
<li>{subject}</li>
</div>
);
}
return (
<div>
{boards.map(board => {
<h1> {board.writer}</h1>
})}
</div>
);
}
export default Home;
Maybe you can try like this,
<div>
{boards.map(board => renderUser(board)}
</div>
if you want to render item directly using (add return to the map):
<div>
{boards.map(board => {
return <h1> {board.writer}</h1>;
})}
</div>
I have got series of data that contains some objects in one array(json file) and it will be shown by react.
Here is my code:
class App extends React.Component {
constructor(props){
super(props);
this.state = {
data: [],
library:null,
perPage: 20,
currentPage: 1,
maxPage: null,
filter: ""
};
}
componentDidMount() {
fetch('/json.bc')
// Here I want to get the length of my respose
.then(response => response.text())
.then(text => {
var Maindata = JSON.parse(text.replace(/\'/g, '"'))
this.setState(state => ({
...state,
data: Maindata
}), () => {
this.reorganiseLibrary()
})
}).catch(error => console.error(error))
}
reorganiseLibrary = () => {
const { filter, perPage , data } = this.state;
let library = data;
if (filter !== "") {
library = library.filter(item =>
item.hotelinfo.hotelsearch.realname.toLowerCase().includes(filter)
);
}
library = _.chunk(library, perPage);
this.setState({
library,
currentPage: 1,
maxPage: library.length === 0 ? 1 : library.length
});
};
// Previous Page
previousPage = () =>
this.setState(prevState => ({
currentPage: prevState.currentPage - 1
}));
// Next Page
nextPage = () =>
this.setState(prevState => ({
currentPage: prevState.currentPage + 1
}));
// handle filter
handleFilter = evt =>
this.setState(
{
filter: evt.target.value.toLowerCase()
},
() => {
this.reorganiseLibrary();
}
);
// handle per page
handlePerPage = (evt) =>
this.setState({
perPage: evt.target.value
}, () => this.reorganiseLibrary());
// handle render of library
renderLibrary = () => {
const { library, currentPage } = this.state;
if (!library || (library && library.length === 0)) {
return <div class="tltnodata">no result!</div>;
}
return library[currentPage - 1].map((item, i) => (
<input type="hidden" value={item.hotelinfo.hotelsearch.hotelid} name="hotelid"/>
));
};
render() {
const { library, currentPage, perPage, maxPage } = this.state;
return (
<div className="Main-wrapper">
<div class="filter_hotelname"><input value={this.state.filter} onChange={this.handleFilter} class="hotelName" /></div>
<div class="countHotel"> <span class="numbersearch"></span> // Here I want two show the count of items </div>
<div className="wrapper-data">
{this.renderLibrary()}
</div>
<div id="page-numbers">
<div class="nexprev">
{currentPage !== 1 && (
<button onClick={this.previousPage}><span class="fa-backward"></span></button>
)}
</div>
<div className="data_page-info">
{this.state.currentPage} از {this.state.maxPage}
</div>
<div class="nexprev">
{(currentPage < maxPage) && (
<button onClick={this.nextPage}><span class="fa-forward"></span></button>
)}
</div>
</div>
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('Result'));
I want to find the length of response from a request with fetch. Also I want to know how to find the count of items that will be shown by renderLibrary . For example in json.bc we have 4 objects I want to show 4 in numbersearch span.
Using Fetch API you can find json response item length by running below code snippet. I have also added comment in code as well.
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => {
//below method return promise based response by converting stream object to json
return response.json();
}).then(json => {
//Once succcessful callback return you can find length of number of item
console.log(json);
alert("Number of item:"+json.length)
})
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => {
//below method return promise based response by converting stream object to json
return response.json();
}).then(json => {
//Once succcessful callback return you can find length of number of item
alert(json.length)
})
You can use the length of the data array from the state to distinguish the number of items.
Since arrays start at 0, you will need to increment the count by one. Here's an example snippet below that you can use in your code sample.
<div class="countHotel"><span class="numbersearch">{this.state.data && this.state.data.length + 1}</span></div>
I've created a fixture file to handle my JSON datas used to write tests.
Before each test, I want my data to be filled with seed data.
After each test, I want my data to be empty
Courses.json :
[
{
"id": 1,
"title": "Ma course"
}
]
CoursesFixture.js :
const { courseList } = require('./courses')
mockData = [
{
"id": 1,
"title": "Ma course"
}
]
module.exports = {
up: () => {
courseList.splice(0)
courseList.push.apply(courseList, mockData)
},
down: () => {
courseList.splice(0)
}
}
CoursesTest.js :
const request = require("supertest")
require('chai').should()
const bodyParser = require("body-parser")
const app = require('./../../app')
app.use(bodyParser.json())
const listeDeCourses = require("../fixtures/courses")
const listeDeCoursesFixture = require("../fixtures/coursesFixture")
describe('Courses', () =>{
beforeEach(() => { listeDeCoursesFixture.up() })
afterEach(() => { listeDeCoursesFixture.down() })
describe('Delete course list', ()=>{
it("Should delete a list of course", ()=>{
return request(app).get('/course')
.then((res) => {
res.body.should.have.lengthOf(1)
request(app).delete('/course').send({"id":"1"})
.then((res) => {
res.body.should.have.lengthOf(0)
})
}).catch((err) =>{
throw new Error(err);
})
})
})
describe('Create course list', () =>{
it("Should create a list of courses", () =>{
return request(app).post('/course').send({"id":3,"title":"Première course"}).then((res) => {
res.status.should.be.eq(200)
const listCourses = res.body
const lastCourse = res.body[1]
listCourses.should.be.a('array')
lastCourse.id.should.be.eq(3)
lastCourse.title.should.be.eq("Première course")
listCourses[listCourses.length - 1].should.be.eq(lastCourse)
}).catch((err) => {
throw new Error(err)
})
})
})
describe('Get course list', ()=>{
it("Should get a list of all courses", ()=>{
return request(app).get('/course')
.then((res) => {
res.body.should.have.lengthOf(1)
}).catch((err) =>{
console.log(err)
throw new Error(err);
})
})
})
})
My problem is that when I launch my test I have an error :
TypeError: Cannot read property 'splice' of undefined
I think the problem is in CoursesFixture.js and surely a syntax error somewhere but I can't find where it is.
const { courseList } = require('./courses') should be const courseList = require('./courses')?
When I create an event, I do this:
export const eventCreate = ({ title, time, location }) => {
const newPostKey = firebase.database().ref('/events').push().key;
const update = {};
const postDetails = {
eventId: newPostKey,
title,
...
goingNumber: 1,
...
};
update[`/events/${newPostKey}`] = postDetails;
return (dispatch) => {
firebase.database().ref()
.update(update)
.then(() => {
dispatch({ type: EVENT_CREATE });
})
.then(() => newPostKey);
};
};
in the database:
later when I try to update the goingNumber:
export const eventSave = ({ goingNumber, eventId }) => {
return (dispatch) => {
firebase.database().ref(`/events/${eventId}`)
.set({ goingNumber })
.then(() => {
dispatch({ type: EVENT_SAVE_SUCCESS });
});
};
};
I get this error saying:
You're not passing in a value for goingNumber. My guess is that you're looking for
firebase.database().ref(`/events/${eventId}`)
.child('goingNumber').set(goingNumber )