Cypress - Visit a URL obtained from a 3rd party(email) - javascript

In my test, I want to visit a URL that is sent in an email. I can successfully save the URL in a variable, but am unable to get cypress to go to that URL. I keep getting the below error. I don't fully understand cypress being "promise-like", so I'm not sure how to resolve the issue
Uncaught (in promise) CypressError: Cypress detected that you returned
a promise from a command while also invoking one or more cy commands
in that promise.
The command that returned the promise was:
cy.get()
The cy command you invoked inside the promise was:
cy.request()
Because Cypress commands are already promise-like, you don't need to
wrap them or return your own promise.
Cypress will resolve your command with whatever the final Cypress
command yields.
Cypress.Commands.add("clickForgotPwdLink", (emailaddress) => {
const MailosaurClient = require('mailosaur');
const client = new MailosaurClient('1234');
let latestEmail;
var emailLower = emailaddress.toLowerCase();
client.messages.search('abc', {
sentTo: emailLower
}).then((results) => {
latestEmail = results.items[0];
let email = latestEmail.id;
client.messages.get(email)
.then((newlink) => {
var forgotpwd = newlink.html.links[0].href;
console.log(forgotpwd)
cy.request(''+forgotpwd+'');
})
})
});

I have to face this today.
If you are getting a raw body response (string) you have to get the link in this way:
const links = body.split("href=http://my.url.com");
var activation_link = links[0].match(/\bhttp?:\/\/\S+/);
activation_link= activation_link[0].replace('"','')
cy.visit(activation_link)

Isn't it just as simple as removing all the quotes and plusses from the cy.request? That is how we use a stored url and that works. But that stored url doesn't come from an email but from an element on the page

I also tried like you but Cypress doens't allowed.
You have to do it via cy.request() to Mailosaur API.
Try something like this:
cy.request({
method: 'POST',
url: 'https://mailosaur.com/api/messages/search',
auth: {
username: 'API_key',
},
body: {
sentTo: 'yourEmail',
},
qs: {
server: 'yourServer',
page: 0,
itemsPerPage: 50,
},
});

The easiest way to do this is using Cypress recorder which email testing embedded in it. I like how Preflight generates cypress code and lets you test emails.
I'd recommend checking out https://cypress.preflight.com/
I've dealt with cy.request before. It's a little cumbersome to get the emails

Related

load user.mail from Auth0 with async function

i want load the user.mail from Auth0 and safe there at a const. but I get a arrow. i don't see the error. can somebody help me to find the solution?
const userMailInfo = async () => {
auth0Client = await auth.createClient();
const result = await auth0Client.getUser().then(user => {
console.log('mail', user.email);
user.mail;
});
return result;
}
;(async () => {
const users = await userMailInfo()
console.log(users)
})()
i get follow error:
(node:19676) UnhandledPromiseRejectionWarning: ReferenceError: document is not defined
It looks like these errors are caused by code running on the server-side, where they do not have access to 'document' and the like. In SvelteKit, endpoints always run on the server, and therefore do not have access to all the elements in the 'Client API'.
To guard code from running on the server side, try calling it through OnMount(). I've linked a Sapper issue outlining some similar solutions, e.g., using if(process.browser). I am not sure if this works in SvelteKit, but may be worth checking out.
Note: It seems like the error occured outside of the provided code snippet.
SvelteKit Discord Server contains some discussions on the topic, try searching for 'UnhandledPromiseRejectionWarning ReferenceError'.
(for Sapper) https://github.com/sveltejs/sapper/issues/1226

Js-IPFS Error: cid.toBaseEncodedString() is not a function

I'm currently working on the backend of a website that would work similar to YouTube but only use IPFS for storage, meaning if you want to "upload" videos to the site it would already have to be on the IPFS network. The actual function is more of an Index than anything else but it was something that I wanted to tackle.
The section I'm working on is intended to verify the integrity of the CID hashes by making sure that there are still providers on the network for that specific content. If there aren't any then the CID and any information associated will get removed from my database but I'm currently getting an issue when trying using the ipfs.dhs.findProvs function.
Here is part of my code:
const ipfs = await IPFS.create({
libp2p: { config: { dht: { enabled: true } } },
});
for (var i of integrityData) {
let cid = new CID(i.CID);
console.log(cid);
let providers = ipfs.dht.findProvs(cid, { numProviders: 2 });
for await (const provider of providers) {
console.log(provider);
}
}
Error Log:
C:\Users\...\node_modules\libp2p-kad-dht\src\providers.js:202
this._log('getProviders %s', cid.toBaseEncodedString())
^
TypeError: cid.toBaseEncodedString is not a function
To further explain my code, the for loops is iterating the JSON content received the Database after querying for all the CIDs in it. i.CID does return the correct CID as a string which I then create a CID object from and pass to the function here ipfs.dht.findProvs(cid, { numProviders: 2 });. The nested for loop is there to iterate through the object that is received but I haven't made it to that stage as I keep getting the same error.

How to call a serverless function in Next.js getStaticPaths [duplicate]

This question already has an answer here:
Fetch error when building Next.js static website in production
(1 answer)
Closed 11 months ago.
I am using Next.js with the Vercel deployment workflow, I am following this guide to try and setup page generation at buildtime. The specific section shows the following example to generate pages based on an external API's response:
// This function gets called at build time
export async function getStaticPaths() {
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts')
const posts = await res.json()
// Get the paths we want to pre-render based on posts
const paths = posts.map(post => ({
params: { id: post.id },
}))
// We'll pre-render only these paths at build time.
// { fallback: false } means other routes should 404.
return { paths, fallback: false }
}
// This also gets called at build time
export async function getStaticProps({ params }) {
// params contains the post `id`.
// If the route is like /posts/1, then params.id is 1
const res = await fetch(`https://.../posts/${params.id}`)
const post = await res.json()
// Pass post data to the page via props
return { props: { post } }
}
I want to do this exactly, however I wrote my API as a Node.js serverless function within the same code repository, it is not an external api.
I tried to do the following to call on my api:
// This function gets called at build time
export async function getStaticPaths() {
const res = await fetch('/api/get-designs');
const designs = await res.json();
// Get the paths we want to pre-render based on posts
const paths = designs.map(design => ({
params: { id: design.id },
}))
return {
// Only posts returned by api are generated at build time
paths: paths,
// Enable statically generating additional pages
fallback: true,
}
}
However I get an error that the fetch api url must be absolute. Because of the way Vercel deploys, I won't always have the same deployment URL, so I don't think I can just use a hardcoded value here. Also, I am suspecting that because this function runs at buildtime, that my function is not running yet, therefore can not be called. I am still trying to wrap my head around this Next.js statically generated site workflow, but basically I am confused because they seem to encourage using serverless functions, and this getStaticPaths method for page generation, but they don't seem to work together unless I am missing something.
Is there a way I can run my api to get these results at build time? Any guidance would be much appreciated!
Thanks!
In this case, we can extract the server logic into a function and that function can be used directly inside your api route file. So, for CR we can use /api/whateverRoute and inside getStaticPaths we can use that function itself directly.

Why is my aws step function's execution not started with the ARN I entered?

I'm creating a new state machine with AWS Step functions in the project I'm working on. But when I try to start the execution of the step function with the aws-sdk, I get a "StateMachineDoesNotExist" error. It seems like the stateMachineArn I pass as input is not the same used by the startExecution function.
Here is how I'm trying to start the execution:
const AWS = require('aws-sdk')
const stepfunctions = new AWS.StepFunctions()
const params = {
stateMachineArn: process.env.ORDER_ACCEPTED_MACHINE_ARN,
name: `${orderId}-${moment().unix()}`,
input: JSON.stringify({
orderAcceptedTimestamp: moment(createdAt).add(1, 'minutes').toISOString(),
orderId,
}),
}
const success = await stepfunctions.startExecution(params).promise()
return success.executionArn
My stateMachineArn is defined this way :
process.env.ORDER_ACCEPTED_MACHINE_ARN = 'arn:aws:states:eu-central-1:935080471983:stateMachine:orderAcceptedMachine-dev'
And here is the error message I get when running the code:
State Machine Does Not Exist: 'arn:aws:states:us-east-1:935080471983:stateMachine:orderAcceptedMachine-dev'
What I don't understand here is that the Arn from the input and the Arn from the error are not the same. To me it seems like the startExecution modified the input stateMachineArn and changed its region somehow (even though the Arn is passed as a string?!).
I already have a similar step functions in the project that I start the same way:
const params = {
stateMachineArn: process.env.ORDER_TIMEOUT_MACHINE_ARN,
name: `${orderId}-${moment().unix()}`,
input: JSON.stringify({
orderTimeoutTimestamp: timeout.toISOString(),
orderId,
}),
}
const success = await stepfunctions.startExecution(params).promise()
return success.executionArn
The Arn definition is in the same file as the other one, and is defined like this:
process.env.ORDER_TIMEOUT_MACHINE_ARN = 'arn:aws:states:eu-central-1:935080471983:stateMachine:orderTimeoutMachine-dev'
This step functions is started with no problem and correctly return the Arn of the execution.
By debugging I found out that AWS.config.region returns us-east-1 in both files where I call startExecution. Since my existing state machine is already working with this configuration, I'm thinking it's not related to the error, but I tried to 'force' the AWS Region to eu-central-1 anyway just before the call like this:
AWS.config.update({ region: 'eu-central-1' })
const success = await stepfunctions.startExecution(params).promise()
But this doesn't solve the issue. I am fairly new to AWS so there is probably something that I'm missing out here (Let me know if I forgot to put any important code/info), but I'm really confused by the facts that the Arn in the error message doesn't match the one in the input, and that an almost identical state machine is working fine while my newly created one doesn't want to start.
So how can I fix this issue ?
After further investigation I found out that the step functions's region and endpoint can be different from AWS. Adding the following code solved the issue:
const stepfunctions = new AWS.StepFunctions({
endpoint: 'https://states.eu-central-1.amazonaws.com',
region: 'eu-central-1',
})

sails.js how to call a REST API from a script using restler or not?

I haven't figured out how to get a response from restler in sails.js script. The goal is to import some data each day from a REST API to my database. So I chose to use sails.js script to be able to crontab the call.
When I search what I could use to contact the API. I saw a topic about restler which seem pretty easy to use.
Sadly when I try it I cannot catch the response from the API, I use this basic example
module.exports = {
friendlyName: 'test',
description: 'this is a test',
fn: async function () {
sails.log('Running custom shell script... (`sails run test`)');
var rest = require('restler');
rest.get('http://google.com').on('complete', function(result) {
sails.log("In callback")
if (result instanceof Error) {
sails.log('Error:', result.message);
this.retry(5000); // try again after 5 sec
} else {
sails.log(result);
}
});
sails.log('finished');
}
};
When I run the script this is what I get
info: Initializing hook... (`api/hooks/custom`)
info: Initializing `apianalytics` hook... (requests to monitored routes will be logged!)
info: ·• Auto-migrating... (alter)
info: Hold tight, this could take a moment.
info: ✓ Auto-migration complete.
debug: Running custom shell script... (`sails run test`)
debug: finished
I try other method and other URL too, but apparently I never get in the callback.
So I assume that the script doesn't "wait" the .on('complete') before continuing his execution.
I know, and use, on the database call .then to avoiding that, I think this is called a 'promise'. So from what I understand the problem is around that but sadly after searching, I don't find any answer to solve my issue.
I am not married to restler, and if another and better solution exists don't hesitate, the goal is again to get the content from a REST API from sails.js script.
Thank you for the time you take to answer my question.

Categories