feat(types): can specify the ResponseBody type of cy.request (#16743)

This commit is contained in:
Kukhyeon Heo
2021-06-02 23:27:15 +09:00
committed by GitHub
parent 97e7a524d4
commit 49990480bd
2 changed files with 30 additions and 6 deletions
+5 -5
View File
@@ -1470,7 +1470,7 @@ declare namespace Cypress {
* @example
* cy.request('http://dev.local/seed')
*/
request(url: string, body?: RequestBody): Chainable<Response>
request<T = any>(url: string, body?: RequestBody): Chainable<Response<T>>
/**
* Make an HTTP request with specific method.
*
@@ -1478,7 +1478,7 @@ declare namespace Cypress {
* @example
* cy.request('POST', 'http://localhost:8888/users', {name: 'Jane'})
*/
request(method: HttpMethod, url: string, body?: RequestBody): Chainable<Response>
request<T = any>(method: HttpMethod, url: string, body?: RequestBody): Chainable<Response<T>>
/**
* Make an HTTP request with specific behavior.
*
@@ -1489,7 +1489,7 @@ declare namespace Cypress {
* followRedirect: false // turn off following redirects
* })
*/
request(options: Partial<RequestOptions>): Chainable<Response>
request<T = any>(options: Partial<RequestOptions>): Chainable<Response<T>>
/**
* Get the root DOM element.
@@ -5502,9 +5502,9 @@ declare namespace Cypress {
consoleProps(): ObjectLike
}
interface Response {
interface Response<T> {
allRequestResponses: any[]
body: any
body: T
duration: number
headers: { [key: string]: string | string[] }
isOkStatusCode: boolean
+25 -1
View File
@@ -85,7 +85,7 @@ cy.request({
method: "POST",
body: {}
}).then((resp) => {
resp // $ExpectType Response
resp // $ExpectType Response<any>
resp.redirectedToUrl // $ExpectType string | undefined
resp.redirects // $ExpectType string[] | undefined
resp.headers // $ExpectType { [key: string]: string | string[]; }
@@ -100,6 +100,30 @@ cy.request({
}
})
// Users can specify body type.
// https://github.com/cypress-io/cypress/issues/9109
interface ResBody {
x: number
y: string
}
cy.request<ResBody>('http://goooooogle.com', {})
.then((resp) => {
resp // $ExpectType Response<ResBody>
})
cy.request<ResBody>('post', 'http://goooooogle.com', {})
.then((resp) => {
resp // $ExpectType Response<ResBody>
})
cy.request<ResBody>({
url: 'http://goooooogle.com',
body: {}
}).then((resp) => {
resp // $ExpectType Response<ResBody>
})
// if you want a separate variable, you need specify its type
// otherwise TSC does not cast string "POST" as HttpMethod
// https://github.com/cypress-io/cypress/issues/2093