Bigdragon
Bigdragon

Reputation: 362

Where to store API URL in Cypress?

I'm new to Cypress and want to know where's the place I should put all of my external URLs in?

In my website, we have separated URLs for the web, and another one for APIs.

Let's say they're:

I know I can put my app URL in baseUrl in cypress.json, and I've put all my subdirectory e.g. /products /users in the env variables session. Because cy.visit() automatically utilize this baseUrl, it's good for me now.

What I struck now is where to place my API URLs properly. I don't feel like put the fullpath like:

is not a good idea, since I repeated the API baseUrl everywhere. And if I split it into apiBaseUrl and the sub part /products, I'm now have to build up the URL myself every time I want to watch it like

cy.route(`${Cypress.env('apiBaseUrl')}${Cypress.env('apiUrl').getProducts}`);

because my apiBaseUrl is not baseUrl. This make it even harder than the above method.

Any suggestion?

Upvotes: 3

Views: 4508

Answers (2)

Robert
Robert

Reputation: 1789

I found a quite simple solution. Just simply put your API backend URL right next to the (web frontend) cypress 'baseUrl'. My cypress.json looks like this:

{
  "baseUrl": "http://localhost:3001/",
  "backendBaseURL": "http://localhost:8080/api/v2",
  "env": {
    "someDummyEnvironemntVar": "fooBar"
  }, 
  "testFiles": "**/*.*",
  "watchForFileChanges": true
}

Both can be accessed anywhere in Cypress tests:

Cypress.env('someDummyEnvironemntVar')   => "fooBar"
Cypress.config('backendBaseURL')   => "http://localhost:8080/api/v2"

Upvotes: 2

Mr. J.
Mr. J.

Reputation: 3741

We have a separate file called settings.js (cypress/settings.js). Which holds the configuration for the API:

export const apiUri = 'APIURL'
export const apiOauthSecret = 'TOKEN'

To actually use the variable apiUri we import it in the file where we want to use it:

import {apiUri, apiOauthSecret} from '../settings'

Cypress.Commands.add('apiRequest', (endPoint, options) => {
  const token = options.token || JSON.parse(window.sessionStorage.getItem('oauth-token') || '{}').accessToken
  if (token) {
    return cy.request({
      failOnStatusCode: false,
      ...requestOptions({
        ...options,
        token
      }),
      url: `${apiUri}/${endPoint}`
    })
  }
  return cy
})

This results in being able to use apiUri and baseUrl next to eachother

Upvotes: 0

Related Questions