Make an HTTP request. Show Syntaxcy.request(url) cy.request(url, body) cy.request(method, url) cy.request(method, url, body) cy.request(options) UsageCorrect Usage cy.request('http://dev.local/seed') Argumentsurl (String) The URL to make the request to. If you do not provide a fully qualified domain name (FQDN) URL, Cypress will make its best guess as to which host you want cy.request() to use in the URL.
cy.visit('http://localhost:8080/app') cy.request('users/1.json')
const { defineConfig } = require('cypress') module.exports = defineConfig({ e2e: { baseUrl: 'http://localhost:1234' } })
import { defineConfig } from 'cypress' export default defineConfig({ e2e: { baseUrl: 'http://localhost:1234' } })
The cypress.json file has been replaced by cypress.config.js or cypress.config.ts in Cypress version 10.0.0. We recommend that you update your configuration accordingly. Please see the new configuration guide and the migration guide for more information. { "e2e": { "baseUrl": "http://localhost:1234" } }
body (String, Object) A request body to be sent in the request. Cypress sets the Accepts request header and serializes the response body by the encoding option. method (String) Make a request using a specific method. If no method is defined, Cypress uses the GET method by default. Supported methods include:
options (Object) Pass in an options object to change the default behavior of cy.request(). You can also set options for cy.request()'s baseUrl and responseTimeout globally in configuration.
You can also set options for cy.request()'s baseUrl and responseTimeout globally in the Cypress configuration. Yieldscy.request() yields the response as an object literal containing properties such as:
ExamplesURLMake a GET requestcy.request() is great for talking to an external endpoint before your tests to seed a database. beforeEach(() => { cy.request('http://localhost:8080/db/seed') }) Issue an HTTP requestSometimes it's quicker to test the contents of a page rather than cy.visit() and wait for the entire page and all of its resources to load. cy.request('/admin').its('body').should('include', '<h1>Admin</h1>') Method and URLSend a DELETE requestcy.request('DELETE', 'http://localhost:8888/users/827') Alias the request using .as()cy.request('https://jsonplaceholder.cypress.io/comments').as('comments') cy.get('@comments').should((response) => { expect(response.body).to.have.length(500) expect(response).to.have.property('headers') expect(response).to.have.property('duration') }) Method, URL, and BodySend a POST request with a JSON bodycy.request('POST', 'http://localhost:8888/users/admin', { name: 'Jane' }).then( (response) => { expect(response.body).to.have.property('name', 'Jane') } ) OptionsRequest a page while disabling auto redirectTo test the redirection behavior of a login without a session, cy.request can be used to check the status and redirectedToUrl property. The redirectedToUrl property is a special Cypress property that normalizes the URL the browser would normally follow during a redirect. cy.request({ url: '/dashboard', followRedirect: false, }).then((resp) => { expect(resp.status).to.eq(302) expect(resp.redirectedToUrl).to.eq('http://localhost:8082/unauthorized') }) Download a PDF fileBy passing the encoding: binary option, the response.body will be serialized binary content of the file. You can use this to access various file types via .request() like .pdf, .zip, or .doc files. cy.request({ url: 'http://localhost:8080/some-document.pdf', encoding: 'binary', }).then((response) => { cy.writeFile('path/to/save/document.pdf', response.body, 'binary') }) Get Data URL of an imageBy passing the encoding: base64 option, the response.body will be base64-encoded content of the image. You can use this to construct a Data URI for use elsewhere. cy.request({ url: 'https://docs.cypress.io/img/logo.png', encoding: 'base64', }).then((response) => { const base64Content = response.body const mime = response.headers['content-type'] const imageDataUrl = `data:${mime};base64,${base64Content}` }) Oftentimes, once you have a proper e2e test around logging in, there's no reason to continue to cy.visit() the login and wait for the entire page to load all associated resources before running any other commands. Doing so can slow down our entire test suite. Using cy.request(), we can bypass all of this because it automatically gets and sets cookies as if the requests had come from the browser. cy.request({ method: 'POST', url: '/login_with_form', form: true, body: { username: 'jane.lane', password: 'password123', }, }) cy.getCookie('cypress-session-cookie').should('exist') Using cy.request() for HTML FormsRequest PollingCall cy.request() over and over againThis is useful when you're polling a server for a response that may take awhile to complete. All we're really doing here is creating a recursive function. Nothing more complicated than that. function req () { cy .request(...) .then((resp) => { if (resp.status === 200 && resp.body.ok === true) return req() }) } cy .get('button').click() .then(req) NotesDebuggingCypress does not actually make an XHR request from the browser. We are actually making the HTTP request from Cypress (in Node). So, you won't see the request inside of your Developer Tools. CORSCORS is bypassedNormally when the browser detects a cross-origin HTTP request, it will send an OPTIONS preflight check to ensure the server allows cross-origin requests, but cy.request() bypasses CORS entirely. cy.request('https://www.google.com/webhp?#q=cypress.io+cors') .its('body') .should('include', 'Testing, the way it should be') CookiesCookies are automatically sent and receivedBefore sending the HTTP request, we automatically attach cookies that would have otherwise been attached had the request come from the browser. Additionally, if a response has a Set-Cookie header, these are automatically set back on the browser cookies. In other words, cy.request() transparently performs all of the underlying functions as if it came from the browser. cy.intercept(), cy.server(), and cy.route()cy.request() sends requests to actual endpoints, bypassing those defined using cy.route() or cy.intercept()cy.server() and any configuration passed to cy.server() has no effect on cy.request(). The intention of cy.request() is to be used for checking endpoints on an actual, running server without having to start the front end application. RulesRequirements
Assertions
Timeouts
Command LogRequest comments endpoint and test response cy.request('https://jsonplaceholder.typicode.com/comments').then((response) => { expect(response.status).to.eq(200) expect(response.body).to.have.length(500) expect(response).to.have.property('headers') expect(response).to.have.property('duration') }) The commands above will display in the Command Log as: When clicking on request within the command log, the console outputs the following: History
See also |