Problem: I would like to extract text from an element and would like to use that text to append in a validation message. How do i achieve that?
What i tried so far?
My validation message has an unique ID appended to the message. For example ( 'Story ID: 123 has been Created'). So, i would like to get the story id and then append it to my validation message.
Please find the below code snippets:
Locator to get the text:
element(by.css('.story-id'))
Method which is used to assert the validation message( From Card PO):
async validateMessage(message) {
await expect(element(by.css('.ng-star-inserted')).getText()).toEqual(message);
}
Here, message would contain something like 'Story ID has been created'.
My spec file will have something like this,
await card.validateMessage('Story ID has been created') where Story ID changes everytime.
Not sure why you need to pass the message as a parameter if you know how it should look like...But in case your message is changing (but it always contains story id) you can write a couple of different expects to test each message.
Something like this:
async validateSuccessMessage(id) {
let messageElement = element(element(by.cssContainingText(".story-id", id)))
let messageText = await messageElement.getText()
expect(await messageText).toMatch(`Story ID: ${id} has been Created`)
}
and
async validateFailMessage(id) {
let messageElement = element(element(by.cssContainingText(".story-id", id)))
let messageText = await messageElement.getText()
expect(await messageText).toMatch(`Oops! Story ID: ${id} was not created`)
}
p.s. If cssContainingText does not work use Xpath (you did not include the HTML so I'm guessing here).
Sorry in advance if I got your idea wrong
expect() doesn't need await before it. But I did see it fail when you don't pass it to the parameter it takes. So it should be expect(await element.getText()).toBe("string")
Don't wrap expect to a function! Why? Because if it fails it'll point to the line number where if failed and ease the process of debugging. Just as a best practice
If you want to extract just the number from a string 'Story ID: 123 has been Created' use regex
let str = 'Story ID: 123 has been Created',
regex = /(Story ID:\s+)(\d+)/;
let result = str.match(regex);
console.log(result[2]); // 123 or any other integer that is there
I didn't get your question 100%, but I think you can take from here
Thanks everyone for suggestions and ideas. I was able the achieve with the below code snippet. Apologize if my question wasn't clear, but couple of answers were truly helpful in achieving the below.
/* Store the story id in messageText variable */
const messageElement = element(by.css('.story-id');
const messageText = messageElement.getText();
/* Since messageText returns a promise, i'm printing it to 'message' variable */
messageText.then(async function(message) {
console.log(message)
/* Verifying the text from message with actual text */
await expect(element(by.css('.ng-star-inserted').getText()).toEqual('"'+message+' sucessfully deleted.');
})
}
Related
How do I get my bot to send a random picture/meme in discord. I'm using discord.js and this is as far as I got.
if (msg.content === '-meme');
var randommeme = ({files:["https://cdn.discordapp.com/attachments/757397429107556422/757524795452686426/GBoat_Watermark.png"]} , {files:["https://cdn.discordapp.com/attachments/815040456244985947/816225078969892864/A_good_fluffy_goat.png"]});
var fact = Math.floor(Math.random() * randommeme.length);
msg.channel.send('goat meme', randommeme[fact]);
});
This should send a random picture but when I run the command it only says "goat meme". I tried this code before and it worked.
client.on('message', msg => {
if (msg.content === '+meme') {
msg.channel.send("This is a good fluffy goat", {files: ["https://cdn.discordapp.com/attachments/757397429107556422/816234172737126430/A_good_fluffy_goat.png","https://cdn.discordapp.com/attachments/757397429107556422/757524795452686426/GBoat_Watermark.png"]});
}
});
I really don't know what Im doing wrong here?
First create an array of links, and then use the random function to get a random link from the array.
const meme = ['link_1','link_2','link_3','link_4'];
const index = Math.floor(Math.random() * meme.length);
message.channel.send('Goat meme',{files:[meme[index]]});
where link_1, link_2 etc. are attachment file URL.
There's a typo in line two, the right code should be this:
var randommeme = ({files:["https://cdn.discordapp.com/attachments/757397429107556422/757524795452686426/GBoat_Watermark.png", "https://cdn.discordapp.com/attachments/815040456244985947/816225078969892864/A_good_fluffy_goat.png"]});
I want to return assignments in Google Classrom using
service().courseWork().studentSubmissions().return_(courseId=PASS_HERE_THE_COURSEID, courseWorkId=PASS_HERE_THE_COURSEWORDID, id=PASS_HERE_THE_SUBMISSION_ID)
I have the courseId and the courseWorkId, but don´t know how to get the id=PASS_HERE_THE_SUBMISSION_ID for each student.
Hope someone can help me.
You can use courses.courseWork.studentSubmissions.list to get a list of student submissions. You just need to provide the courseId and courseWorkId as a path parameter. You may also include additional query parameters in your request.
For example, you want to restrict returned student work to those owned by the student with the specified identifier. You need to set a specific identifier to userId as part of your query parameters
Note: You may also loop all the list of student submission to process each submission before returing it using courses.courseWork.studentSubmissions.return
The numeric identifier for the user
The email address of the user
The string literal "me", indicating the requesting user
Sample Response Body (JSON):
{
"studentSubmissions": [
{
object (StudentSubmission)
}
],
"nextPageToken": string
}
StudentSubmission contains all the information related to the student submission for the course work including the courseId, courseWorkId, id and userId.
StudentSubmission Resource (JSON):
{
"courseId": string,
"courseWorkId": string,
"id": string,
"userId": string,
"creationTime": string,
"updateTime": string,
"state": enum (SubmissionState),
"late": boolean,
"draftGrade": number,
"assignedGrade": number,
"alternateLink": string,
"courseWorkType": enum (CourseWorkType),
"associatedWithDeveloper": boolean,
"submissionHistory": [
{
object (SubmissionHistory)
}
],
// Union field content can be only one of the following:
"assignmentSubmission": {
object (AssignmentSubmission)
},
"shortAnswerSubmission": {
object (ShortAnswerSubmission)
},
"multipleChoiceSubmission": {
object (MultipleChoiceSubmission)
}
// End of list of possible types for union field content.
}
(UPDATE)
Regarding the error you have encountered when using courses.courseWork.studentSubmissions.return in Apps Script,
GoogleJsonResponseException: API call to classroom.courses.courseWork.studentSubmissions.return failed with error: #ProjectPermissionDenied The Developer Console project is not permitted to make this request.
It occurred because you are trying to modify a course work which is not created on a Developer Console project. Please refer here.
Sample Code:
var courseId = '2491255xxxxxx';
var courseWorkId = '2524434xxxxx'; // manually created in classroom.google.com
//1st TRY with error
var studentSubmissions = Classroom.Courses.CourseWork.StudentSubmissions.list(courseId, courseWorkId);
Logger.log(studentSubmissions.studentSubmissions[0].id);
//var ret = Classroom.Courses.CourseWork.StudentSubmissions.return({},courseId, courseWorkId, studentSubmissions.studentSubmissions[0].id);
//Logger.log(ret);
var assignment = {
title: "Test Assignment 3",
state: "DRAFT",
assigneeMode: "ALL_STUDENTS",
workType: "ASSIGNMENT"
};
//var newCourseWork = Classroom.Courses.CourseWork.create(assignment, courseId);
//2nd TRY without error
var newCourseWorkId = '2618921xxxxx';
var studentSubmissions2 = Classroom.Courses.CourseWork.StudentSubmissions.list(courseId, newCourseWorkId);
var ret = Classroom.Courses.CourseWork.StudentSubmissions.return({},courseId, newCourseWorkId, studentSubmissions2.studentSubmissions[0].id);
Logger.log(studentSubmissions2);
Logger.log(ret);
Logger.log(Classroom.Courses.CourseWork.get(courseId,newCourseWorkId));
Explanation:
During the first try, I tried to return a student submission course work which was created in https://classroom.google.com/. This case will encounter an error, since I am trying to modify a course work that is not associated with a developer console project. You can check if a course work has an associated developer console project using Classroom.Courses.CourseWork.get(), associatedWithDeveloper property should be true.
On the 2nd try, I created a draft course work first, then modify the created course work in https://classroom.google.com/. Once I finalized the changes and published the course work. I tried to return the student submission course work and it was successful (return should be null/empty). The reason why it succeed is because a developer console project is associated with the course work since I created the course work using Apps Script, hence I could also modify the student submission using Apps Script.
Message= await webhook.send("Test message to pin")
await Message.pin()
But I get a str in return from webhook.send. How can I get a message type so I'm able to pin it?
Thank you in advance.
If you read the documentation. You will see that you need to add the following parameter: wait=True (when sending through a webhook). This will return the message. If you dont do this it will return None as explained in the doc.
Thus what you need to do:
Message = await webhook.send("Test message to pin", wait=True)
await Message.pin()
In the test in QnA portal like the below screenshot, those buttons are created by the follow-up prompts from QnA, and when click those buttons, the next Http request contains all the prompts information like text and qnaid. Those the next response will be the answer of the specific qnaid.
But in the Bot -qnamaker-prompting Sampleenter link description here, when click the button, the Http request just contain the text as questions, thus the QnA will not get the answer bind with the qnaid. The answer may will not bind with qnaid and just context.
enter image description here
So anyone have ideas on how to create a bot like QnA test?
Generally, this is how you can get the same returned results generated from the getAnswers() API call as you get from QnA.
First, pass the current context into getAnswers() (which contains the user's message: "help", "Where did trees come from", "Why is the sky blue?", etc.) and then map the result to a variable:
const stepResults = turnContext.context;
let qnaResults = await this.qnaMaker.getAnswers(stepResults);
After validating a response is returned, you can pass the result text into an activity:
await innerDc.prompt('ConfirmPrompt', qnaResults[0].context.prompts[0].displayText);
Logging the above qnaResults[0].context.prompts shows the returned prompt values align with request payload seen in devtools:
With regards to the sample you linked, the prompt value is the returned QnAPrompts[] results (i.e. the follow-up prompt). If a prompt is present in the overall QnA results, it is parsed and displayed as a button. The displayText is coming from that prompt.
public static Activity GetHeroCard(string cardTitle, QnAPrompts[] prompts)
{
var chatActivity = Activity.CreateMessageActivity();
var buttons = new List<CardAction>();
var sortedPrompts = prompts.OrderBy(r => r.DisplayOrder);
foreach (var prompt in sortedPrompts)
{
buttons.Add(
new CardAction()
{
Value = prompt.DisplayText,
Type = ActionTypes.ImBack,
Title = prompt.DisplayText,
});
}
var plCard = new HeroCard()
{
Title = cardTitle,
Subtitle = string.Empty,
Buttons = buttons
};
var attachment = plCard.ToAttachment();
chatActivity.Attachments.Add(attachment);
return (Activity)chatActivity;
}
Hope of help!
In my hyperledger-composer app, I have a transaction processor:
async function doSomething(transaction) {
//some code
// the following line results in error message:
const connection = new BusinessNetworkConnection();
await connection.connect('admin#tmy-network');
const result = await connection.query(selectPatientByEmail, { inputValue: email });
//some more code
}
However, the line
const connection = new BusinessNetworkConnection();
causes the following error messsage:
ReferenceError: BusinessNetworkConnection is not defined
How can I define the BusinessNetworkConnection?
*******************************UPDATE**************************************
Following the comment by Paul O'Mahony, I used the following line of code in my transaction processor function (in order to get the patient with the email address 'adam#gmail.com'):
let result = await query('selectPatientByEmail', {
"email": "adam#gmail.com"
});
The query is defined in the queries.qry file as follows:
query selectPatientByEmail {
description: "Select the patient with the given email address"
statement:
SELECT org.comp.app.Patient
WHERE (email == _$email)
}
However, the query returns "undefined" (i.e. variable "result" is undefined) .
What for god's sake is wrong with the code? I just can't see what might be the causing this behaviour.
***************************Update2*****************************************
I have to correct myself ... the query returns something ... but when I want to access the id of the returned patient, this is not possible. That is,
result.id is "undefined"
How can I access the id of the patient returned?
this is because you are (above) writing client code inside a native transaction function - you don't need to set these. Transaction processor functions are automatically invoked by the runtime when transactions are submitted (eg using the BusinessNetworkConnection API under the covers, but it is already part of the transaction - you don't need to specify) . See https://hyperledger.github.io/composer/latest/reference/js_scripts for more info - and the sample networks for common use cases and examples -> https://github.com/hyperledger/composer-sample-networks/tree/master/packages/