1

This is a follow up to a question someone else had asked here How do I return the response from a cy.request through a function

I want to make a function which calls an api, processes the response and returns only a portion of the response. I have the below code which codes not work. I get the compiler error - a function whose type is neither undefined, void or null should return a value. How do I make this work?

Add(someName) : ItemClass {
    cy.request({
        method: 'POST',
        url: someURL,
        body: {
            name: someName
        }
    }).then(function(response) {
       let result = response.body.find((item) => {return item.id === 123})
       return result; // result is of type ItemClass
    })
}
MasterJoe
  • 2,103
  • 5
  • 32
  • 58

1 Answers1

4

The prior linked question shows you need the return cy.request(...) syntax, but since you are also using Typescript you also need to alter the return type.

cy.request() yields a generic Chainable type, so the return type might be

Add(someName) : Chainable<ItemClass> {
  return cy.request({
    ...

But the response is a standard javascript Response type and item looks like an object, so as it stands the return type is

Add(someName) : Chainable<Object> {
  return cy.request({
    ...

If you have a class for ItemClass, and want to return an instance of ItemClass, you will need to instantiate it into the .then() callback.


Type reference

The request command type definition is given here

request<T = any>(url: string, body?: RequestBody): Chainable<Response<T>>