getVisibleText() from value=test - intern

I have this problem, i need to get text from value=test to compare it with exact text:
.setFindTimeout(2000)
.findDisplayedByCss('firstname')
.getVisibleText()
.then(function (text) {
assert.strictEqual(text, 'test');
})
.end()
AssertionError: expected ' ' to equal 'test'

I have found a solution :
.setFindTimeout(2000)
.findDisplayedByCssSelector('input[name="firstname"]')
.getAttribute("placeholder")
.then(function (text) {
assert.strictEqual('First name', text);
})
.getAttribute("value")
.then(function (text) {
assert.strictEqual('test2', text);

Related

How to get a specific data from object of array in angular

I wanna know that how to get the data
HERE IS MY node.js
app.post('/pathname', function (req, res){
fs.readfile('filepath', 'utf8', function(err, data){
if(data){
let valueofdata = JSON.parse(data);
let anothervalue = JSON.stringify(valueofdata[0]);
res.send(anothervalue);
}
My JSON file is
[{
"number":[{
"data":"one",
"data":"two",
"data":"three"
}],
"number1":[{
"data":"four",
"data":"five",
"data":"six"
}],
}]
My ANGULAR file
numberval:any;
ngOnInit(): void {
this.numberval = this.service.numbervalueall; --> the value (number) is stored in service
console.log(this.numberval)
}
numberall(data:any){
this.http.post('http://localhost:4001/pathname', data, {responseType : "text"} )
.subscribe(res => {
console.log(res)
this.numbersname = JSON.parse(res) --> Data from node.js is stored in here
console.log(this.numbersname )
})
}
numbersname!:any;
numberdata(){
this.numberall(this.service.numbervalueall)
}
sampledata(){
console.log(this.service.citydata)
setTimeout(() => {
this.numberall(this.service.citydata)
console.log(this.hotelvalue)
},100);
}
How can I get the specific value from object data stored in res I used res.this.service.numbervalueall but can't get the value. Please Help me with this.
In your ANGULAR file
create new variable as datavalue or your choice
datavalue:any;
numberall(data:any){
this.http.post('http://localhost:4001/pathname', data, {responseType : "text"} )
.subscribe(res => {
console.log(res)
this.numbersname = JSON.parse(res)
this.datavalue = this.numbersname[numbervalueall] --> here u get the specific data in datavalue
})
}

Jasmine: Expected object not to have properties

I write tests for models using Jasmine and receive the following error stack:
$ yarn test
yarn run v1.22.10
$ ENV=test db-migrate --env test up && jasmine-ts && db-migrate db:drop test
received data: /* Replace with your SQL commands */
CREATE TABLE books (
id SERIAL PRIMARY KEY,
title VARCHAR(150),
total_pages INTEGER,
author VARCHAR(255),
summary text
);
[INFO] Processed migration 20210804043247-books-table
[INFO] Done
test
Randomized with seed 85003
Started
......F.
Failures:
1) Book Model create method should add a book
Message:
Expected object to have properties
totalPages: 250
Expected object not to have properties
total_pages: 250
Stack:
Error: Expected object to have properties
totalPages: 250
Expected object not to have properties
total_pages: 250
at <Jasmine>
at UserContext.<anonymous> (/Users/chaklader/Documents/Education/Udacity/Udacity_Nano_Degree/Full_Stack_JavaScript_Developer/C_3/L_3/E_4/src/models/tests/book_spec.ts:36:24)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
8 specs, 1 failure
Finished in 0.04 seconds
Randomized with seed 85003 (jasmine --random=true --seed=85003)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
The book.ts provided below:
import client from "../database";
export type Book = {
id: number;
title: string;
author: string;
totalPages: number;
summary: string;
}
export class BookStore{
async index(): Promise<Book[]> {
try {
// #ts-ignore
const conn = await client.connect();
const sql = 'SELECT * FROM books';
const result = await conn.query(sql);
conn.release();
return result.rows;
} catch (err) {
throw new Error(`Could not get books. Error: ${err}`);
}
}
async show(id: string): Promise<Book> {
try {
const sql = 'SELECT * FROM books WHERE id=($1)'
// #ts-ignore
const conn = await client.connect()
const result = await conn.query(sql, [id])
conn.release()
return result.rows[0]
} catch (err) {
throw new Error(`Could not find book ${id}. Error: ${err}`)
}
}
async create(b: Book): Promise<Book> {
try {
const sql = 'INSERT INTO books (title, author, total_pages, summary) VALUES($1, $2, $3, $4) RETURNING *'
// #ts-ignore
const conn = await client.connect()
const result = await conn
.query(sql, [b.title, b.author, b.totalPages, b.summary])
const book = result.rows[0]
conn.release()
return book
} catch (err) {
throw new Error(`Could not add new book ${b.title}. Error: ${err}`)
}
}
}
The test file book_spec.ts is below:
import { Book, BookStore } from '../book';
const store = new BookStore();
describe('Book Model', () => {
it('should have an index method', () => {
expect(store.index).toBeDefined();
});
it('should have a show method', () => {
expect(store.show).toBeDefined();
});
it('should have a create method', () => {
expect(store.create).toBeDefined();
});
it('should have a update method', () => {
expect(store.create).toBeDefined();
});
it('should have a delete method', () => {
expect(store.delete).toBeDefined();
});
it('create method should add a book', async () => {
const result = await store.create({
id: 1,
title: 'Bridge to Terabithia',
author: 'Katherine Paterson',
totalPages: 250,
summary: 'Childrens',
});
expect(result).toEqual({
id: 1,
title: 'Bridge to Terabithia',
totalPages: 250,
author: 'Katherine Paterson',
summary: 'Childrens',
});
});
});
The data is populated properly in the bd:
The SQL statement in the bd migration is provided:
CREATE TABLE books (
id SERIAL PRIMARY KEY,
title VARCHAR(150),
total_pages INTEGER,
author VARCHAR(255),
summary text
);
What's the issue here and how do I correct it?
Your Book has camelCase properties but your books table has snake_case properties. You either need to pick one type of casing for both or when you get the result from the database create a new object that is of type Book.
const book = {
id: result.rows[0].id,
title: result.rows[0].title,
author: result.rows[0].author,
totalPages: result.rows[0].total_pages,
summary: result.rows[0].summary
}
Another option is to use something like lodash.camelcase and map the object keys to convert them.

How can I retrieve a SharePoint list items attachments using spfx?

I've managed to figure out how to submit multiple attachments to a sharepoint list item.
I now need to retrieve the item and display these items in the same form that was submitted.
Here's the submit code:
private _onSubmit() {
this.setState({
FormStatus: 'Submitted',
SubmittedLblVis: true,
}, () => {
pnp.sp.web.lists.getByTitle("My List").items.add({
State: this.state.State,
State1: this.state.State1,
}).then((iar: ItemAddResult) => {
var attachments: AttachmentFileInfo[] = [];
attachments.push({
name: this.state.FileUpload[0].name,
content: this.state.FileUpload[0]
});
attachments.push({
name: this.state.FileUpload2[0].name,
content: this.state.FileUpload2[0]
});
attachments.push({
name: this.state.FileUpload3[0].name,
content: this.state.FileUpload3[0]
});
iar.item.attachmentFiles.addMultiple(attachments);
This works great.
I have a button the form that allows the user to read an item and populate all the fields in the form. This works fine. But it's not working for the attachments. First thing is I don't know what the Attachments column is called!
Here's the retrieval function:
private _editItem = (ev: React.MouseEvent<HTMLElement>) => {
const sid = Number(ev.currentTarget.id);
let _item = this.state.Items.filter((item) => { return item.Id === sid; });
if (_item && _item.length > 0) {
this._getListItems();
this.setState({
State etc...with a few examples
FormStatus: _item[0].FormStatus,
showModal: true
//The below callback function
}, () => {
if (_item[0].PanelMember) {
this.PanelMemberGetPeoplePicker(Number(_item[0].PanelMemberId));
}
});
}
}
And the _getListItems() function within the above:
public _getListItems() {
sp.web.lists.getByTitle("MyList").items.get().then((items: any[]) => {
let returnedItems: MyDataModel[] = items.map((item) => { return new MyDataModel(item); });
this.setState({ Items: returnedItems });
});
}
I understand that I'll have to update the MyDataModel interface with whatever the attachment column is but what is the attachment column? And how would I implement it within the above to retrieve all 3 attached documents?
Get the item first, then get item attachment files.
let item=sp.web.lists.getByTitle("TestList").items.getById(13);
item.attachmentFiles.get().then((files)=>{
console.log(files);
})

converting excel(.xlsx) file to JSON

I have excel sheet called sampledata.xlsx which i converted into json and console.log to print this data.
server.js
var xlsx2json = require('xlsx2json')
xlsx2json(
'sampledata.xlsx',
{
dataStartingRow: 2,
mapping: {
'name': 'B',//name
'sku': 'C',//unit price //sku
'quantity': 'D',//quantity
}
}).then(jsonArray => {
// [
// {"col_1": "Barton LCC", "col_2": "30", "col_3": "86.69"}
// ]
//console.log(jsonArray);
});
with the help of this doc.
What i want to do here is,in my sampledata.xlsx file i have more data like flat,address,price,etc here i already don't know which fields are present in my excel sheet but i want all that to be console.log.How could i do this is there any way to do this.
import xlsx2json from 'xlsx2json';
OR
const xlsx2json = require('xlsx2json');
const excel2json = [
(req, res, next) => {
xlsx2json(req.body.file.path)
.then(result => result[0])
.reduce((object, item, index) => {
if (index === 0) {
object.mapper = item; // eslint-disable-line no-param-reassign
return object;
}
const data = {};
Object.keys(item).forEach((key) => {
data[object.mapper[key]] = item[key];
});
object.data.push(data);
return object;
}, { mapper: {}, data: [] })
.then(excel => console.log(excel)) // this gives json as output
.catch(err => next(err));
},
];
npm install xlsx-to-json-lc --save
npm install xls-to-json-lc --save
var exceltojson = require("xls-to-json-lc");
exceltojson({
input: "pass the input excel file here (.xls format)"
output: "if you want output to be stored in a file"
sheet: "sheetname", // specific sheetname inside excel file (if you have multiple sheets)
lowerCaseHeaders:true //to convert all excel headers to lowr case in json
}, function(err, result) {
if(err) {
console.error(err);
} else {
console.log(result);
//result will contain the overted json data
}
});

fetch not returning data in react

I'm new to react, i'm having difficulty getting data for a single book out of list, be passed through via axios' get method.
I think it has something to do with the url, but I have been unable to get fix it.
Here's my code:
export function loadBook(book){
return dispatch => {
return axios.get('http://localhost:3000/api/books/book/:id').then(book => {
dispatch(loadBookSuccess(book.data));
console.log('through!');
}).catch(error => {
console.log('error');
});
};
}
//also tried this
export function loadBook(id){
return dispatch => {
return axios.get('http://localhost:3000/api/books/book/' + {id}).then(book => {
dispatch(loadBookSuccess(book.data));
console.log('through!');
}).catch(error => {
console.log('error');
});
};
}
Html code that contains a variable link to each individual book
<div className="container">
<h3><Link to={'/book/' + book._id}> {book.title}</Link></h3>
<h5>Author: {book.author.first_name + ' ' + book.author.family_name}</h5>
<h4>Summary: {book.summary}</h4>
<BookGenre genre={genre} />
</div>
link in Route:
<Route path="/book/:id" component={BookPage} />
Edit: code for the book component
class BookPage extends React.Component{
render(){
const book = this.props;
const genre = book.genre;
console.log(book);
return(
<div>
<div>
<h3> {book.title}</h3>
<h5>Author: {book.author.first_name + ' ' + book.author.family_name}</h5>
<h4>Summary: {book.summary}</h4>
<BookGenre genre={genre} />
</div>
</div>
);
}
}
BookPage.propTypes = {
book: PropTypes.object.isRequired
};
//setting the book with mapStateToProps
function mapStateToProps (state, ownProps){
let book = {title: '', author: '', summary: '', isbn: '', genre: []};
const bookid = ownProps.params._id;
if(state.books.length > 0){
book = Object.assign({}, state.books.find(book => book.id));
}
return {
book: book
};
}
function mapDispatchToProps (dispatch) {
return {
actions: bindActionCreators(loadBook, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(BookPage);
Instead of doing this:-
axios.get('http://localhost:3000/api/books/book/' + {id})
You should do like this:-
axios.get(`http://localhost:3000/api/books/book/${id}`)
So your action.js might look like this:-
export function loadBook(id){
const request = axios.get(`http://localhost:3000/api/books/book/${id}`);
return dispatch => {
request.then(book => {
dispatch(loadBookSuccess(book.data));
}).catch(error => {
console.log('error');
})
};
}
Since the id, you have passed it seems to be a string so it can be concatenated using ES6 template strings and make sure you wrap your strings in backtick . or you can do it by + operator, also make sure you pass id as a parameter in your loadbook function so that you can join it to your URL.
Figured out the solution to this problem.
My mistake was that I failed to send the id of the item I along with the api call.
Using componentDidMount and sending the dynamic id from the url params solved this problem for me.
Thank you, #Vinit Raj, I guess I was too much of a rookie then.

Resources