I am trying to insert value to URL which I want to visit. I use this (for example):
const idp = '10'
cy.visit('=${idp}')
but when I run this, it will ends on this =$%7Bidp%7D
instead of id=10
.
Also I am interested how can I get value from URL to variable.
For example I have URL and I want to create variable idc which will have value 5.
I am trying to insert value to URL which I want to visit. I use this (for example):
const idp = '10'
cy.visit('http://test./aaa/bbb?id=${idp}')
but when I run this, it will ends on this http://test./aaa/bbb?id=$%7Bidp%7D
instead of id=10
.
Also I am interested how can I get value from URL to variable.
For example I have URL http://test./aaa/bbb?id=5
and I want to create variable idc which will have value 5.
2 Answers
Reset to default 5I think you are using the wrong quotes, you need to use backticks to use Template Literals:
cy.visit(`http://test./aaa/bbb?id=${idp}`)
You can then use cy.url()
to get the current URL as a string and use JavaScript to parse the string as normal.
For the first part of your question you need to use backticks(also called grave accents) as outlined in the Template Literals docs instead of regular quotes. Your line would then look like -
cy.visit(`http://test./aaa/bbb?id=${idp}`)
For the second part of your question, you can use URLSearchParams (Note this DOES NOT work in IE). An example would be -
var url = new URL("http://test./aaa/bbb?id=5");
var searchParams = new URLSearchParams(url.search);
const urlParams = new URLSearchParams(searchParams );
const myParam = urlParams .get('id');