cy-api icon indicating copy to clipboard operation
cy-api copied to clipboard

Think about API abstraction

Open bahmutov opened this issue 5 years ago • 0 comments

Common use case: need to login, then perform authorized API calls

  it('user cannot follow themselves', () => {
    const user = Cypress.env('user')
    cy.getLoginToken(user).then(token => {
      const apiUrl = Cypress.env('apiUrl')
      cy.api({
        method: 'POST',
        url: `${apiUrl}/api/profiles/${user.username}/follow`,
        headers: {
          authorization: `Token ${token}`
        },
        failOnStatusCode: false // we expect failure
      })

It would be nice if we could create the API client once (using before) and then could make the calls. Something like

let apiClient
before(() => {
  const user = Cypress.env('user')
  cy.getLoginToken(user).then(token => {
    const apiUrl = Cypress.env('apiUrl')
    apiClient = cy.apiClient({
      baseUrl: `${apiUrl}/api`,
      headers: {
        authorization: `Token ${token}`
      }
    })
  })
})

it('user cannot follow themselves', () => {
  apiClient({
    method: 'POST',
    url: `/profiles/${user.username}/follow`,
    failOnStatusCode: false // we expect failure
  })
})

bahmutov avatar Jul 29 '19 14:07 bahmutov