Our application under test locally has a frontend and backend that run on localhost:4200 and 127.0.0.1:8000, respectively.
When calling cy.visit('/somepage')
we would like this to have a different baseUrl
than for cy.request('/someapi')
as cy.visit()
will visit a page hosted on the frontend, while cy.request()
will make a request to an API endpoint on the backend.
We can use the default baseUrl
config from cypress.json
for cy.visit()
, but is there a way to have cy.request()
default to a different config setting than the default baseUrl
it uses out of the box? Trying to avoid having to specify this all over the place like cy.request(<fully qualified domain name> + '/someapi')
. Thanks!
cy. intercept does not make a request, but rather "listens" to requests that occur on the network layer. If we "ask" Cypress to name a certain request that we expect to occur after some action, we can also "ask" it to wait for it before moving on when it notices that such a request occurred. That is, cy.
Because Cypress changes its own host URL to match that of your applications, it requires that the URLs navigated to have the same superdomain for the entirety of a single test. If you attempt to visit two different superdomains, Cypress will error. Visiting subdomains works fine.
cy. visit() can time out waiting for the page to fire its load event. cy. visit() can time out waiting for assertions you've added to pass.
I think you can use config file cypress.env.json to store your API url and get it from each test case.
In your cypress.env.json
"apiUrl": "http://api"
In your test case
describe('get the api variable from config file', () => {
//set up the variables
const apiUrl = Cypress.env('apiUrl');
cy.request(apiUrl + '/someapi');
I do not know about a feature in cypress that allows configuring different baseUrl
s for visit
resp. request
.
Since you want to get rid of the boilerplate of setting up the correct API uri per test you could also write a custom command around cy.request
:
cypress/support/commands.js
import { API_URI } from '../constants';
// you may want to add a more suitable wrapper depending on the params/options you need to support.
Cypress.Commands.add('api', uri => cy.request(API_URI + uri));
your_spec.js
describe('Foor', () => {
it('Baar', () => {
cy.api('/someapi')...
});
});
BONUS HINT: Be aware that in case no fully qualified domain name (FQDN) is given to cy.request()
it behaves stateful by either using the uri of the last cy.visit
call or as a fallback baseUrl
from cypress config. The approach of this answer is not effected from it, because it always sets the FQDN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With