问题
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!
回答1:
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');
回答2:
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.
来源:https://stackoverflow.com/questions/58033402/different-cypress-baseurl-for-cy-visit-and-cy-request