Git Product home page Git Product logo

cy-api's Introduction

@bahmutov/cy-api

renovate-app badge CircleCI cypress version

Cypress custom command "cy.api" for end-to-end API testing

This command makes HTTP requests to external servers, then renders the input and output where the web application usually is in the Cypress Test Runner. If there are server-side logs using @bahmutov/all-logs, this command fetches them and renders too. Here is typical output:

cy.api in action

Install

npm install --save-dev @bahmutov/cy-api

or

yarn add -D @bahmutov/cy-api

Add the following line to your Cypress support file

// usually cypress/support/index.js
import '@bahmutov/cy-api'

This will add a new command cy.api for making API requests.

Configuration

var env default value description
CYPRESS_API_MESSAGES true Show and make call to api server logs
CYPRESS_API_SHOW_CREDENTIALS false Show authentication password

By default cy.api print response in the browser. To have the same behaviour as cy.request and use cy.visit normally, you need to desactivate apiDisplayRequest :

it('my test without displaying request', { apiDisplayRequest: false }, () => {
  cy.api({
    url: '/',
  })
})

TypeScript

If your using TypeScript with Cypress, you can add type in your tsconfig.json

{
  "compilerOptions": {
    "types": ["cypress", "@bahmutov/cy-api"]
  }
}

Examples

Courses

More info

Small print

Author: Gleb Bahmutov <[email protected]> ยฉ 2019

License: MIT - do anything with the code, but don't blame me if it does not work.

Support: if you find any problems with this module, email / tweet / open issue on Github

MIT License

Copyright (c) 2019 Gleb Bahmutov <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

cy-api's People

Contributors

bahmutov avatar hang-up avatar hitmands avatar lejeanbono avatar nicolas-tf avatar papb avatar renovate-bot avatar renovate[bot] avatar wlsf82 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

cy-api's Issues

Think about API abstraction

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
  })
})

Set `failOnStatusCode` default to false

This commands is helpful to test the low levels of an API, so is common to try case when the response status is a client error but to avoid rejection is necessary to set failOnStatusCode: false in the parameters. By example:

it('should validate the request method', () => {
    cy.api({
      url: '/auth/register',
      failOnStatusCode: false, // Not so necessary, doesn't it?
    }).its('status').should('equal', 405)
})

Combined logs for entire test

It would be nice to have all logs for the entire test in a single list. Then we can diff this list using snapshot matching for simple debugging

Return Request/Response cy-api in headless mode

Good morning.. please, could you create a flag so that the request and response cy-api are returned when the tests are executed in headless mode.

Open mode:

image

  • Expected scenario: Return the response and request when the test is run in headless mode as well, replicating the same behavior in open mode

Test fails when baseUrl in cypress.json in not included

I use config files to switch between environment URL's. I have multiple URL's I need to initiate with as well on my different test suites. Hence, I am not using a specific baseUrl. However, if baseUrl is not present in cypress.json, my tests fail. I had to include this variable with an actual value (e.g. https://loginsite.com) but will never use it.
I understand it is not best practice, but switching between environments would require me with one environment 'http' and another having 'https' and multiple other reasons. Example:

"baseUrls":
{
"protocol": "https://",
"domain": "test.com",
"subDomain": "login"
}

2020-03-28_0-35-43

This is just a minor issue but I would like a cleaner code and not include parameters/variables that are not being used.

cy.visit() loads blank page on an app using the hash router

Inspired from cypress-io/cypress#27050

Current behavior

If my Web app uses the hash router, I cannot seem to be able to visit the same url twice.

If I have Cypress.env("baseUrl") = "https://my-example-app.com/"

I cannot have cy.visit("#/login") or cy.visit("https://my-example-app.com/#/login") in the first and the second it().
I cannot have it in a beforeEach() hook with two tests either.

However cy.visit("") and cy.visit("https://my-example-app.com/") work well, even though I am redirected by the page to #/login immediately.

image

Desired behavior

The cy.visit("#/login") in the second it() or second trigger of beforeEach() should load the page correctly.

Test code to reproduce

describe("Visit login page", () => {
  it("Working", () => {
    cy.visit("#/login"); // loads page correctly
    cy.get("img.logo").should("be.visible"); // finds the logo image 
  });
  it("Page is blank", () => {
    cy.visit("#/login"); // loads a blank page
    cy.get("img.logo").should("be.visible"); // does not find the logo image 
  });
});

Pivot point

I have this behaviour when cypress\support\e2e.(ts|js) contains import "@bahmutov/cy-api";.

This problem is gone when I comment it out.

Cypress Version

v12.14.0

Node version

v18.16.0

Operating System

Windows 11 Pro 22H2 Build 22621.1702

Debug Logs

No response

Other

No response

Using cy.api command in UI tests also displays API request/response

I am trying to use the cy.api command in a base class like this:

protected post(request: ApiRequest): Cypress.Chainable<Cypress.Response> {
    return cy.api({
      method: HttpMethod.POST,
      url: this.buildUrl(request),
      failOnStatusCode: false,
      auth: this.setAuth(request.token),
      body: request.payload
    }).as(API_RESPONSE_ID);

  }

But I am using the same base class both for API and UI testing.
Is there a way to hide the request/response details in the test runner?

API req & res in mochawesome (not entirely redundant)

Pretty similar to #165 I guess, but this is a request for advice.

I am using nasty functions in order to store and reuse data between requests.

In order to compensate with the fact that the logs give only the content of the it(), I added a conditional screenshot upon failure of the test. (see code and screenshot below and maybe this helps @kivysyar with his own problem)

I made it conditional because otherwise it requires more disk space and time to execute, but the downside is, I only have the content of the failing request, not that of the couple of previous requests.

I would love to replace the content of the it() with the actual request and the actual response, just like it shows in the html.

My question is: should I look into modifying my code, cy-api or the mochasome reporter instead?


// in the test file
afterEach(() => {
  cy.takeScreenshotIfAutomatedTests();
});
// my custom command
import addContext from "mochawesome/addContext";

Cypress.Commands.add("takeScreenshotIfAutomatedTests", (capture) => {
  let screenshot;
  if (Cypress.env("CI") && Cypress.state().ctx.currentTest.state === "failed") {
    cy.screenshot("screenshot", {
      capture: capture, // Captures "fullpage" if undefined
      overwrite: true,
      onAfterScreenshot($el, props) {
        screenshot = props.path;
      },
    }).then(() => {
      cy.once("test:after:run", (test) => {
        addContext({ test }, screenshot);
      });
    });
  }
});

image

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/badges.yml
npm
package.json
  • @types/common-tags 1.8.2
  • common-tags 1.8.2
  • @bahmutov/all-logs 1.8.1
  • cypress 13.3.1
  • semantic-release 21.1.2
  • start-server-and-test 2.0.1
  • cypress >=3

  • Check this box to trigger a request for Renovate to run again on this repository

Display request and response of only a single api call

Hi,

While running tests in the Cypress test runner, when I hover over the command logs, the requests/responses are added to the frame gradually. Eventually, I end up with a frame full of requests and responses (of several API calls that I sent using cy-api).

Is there an option to display the request and response of only one API call? (for example, the API call that i currently hover over in the command log).

Screen Shot 2022-05-03 at 11 47 29

Thanks!

hide auth headers on output of cy-api logs on the test runner

On the output of request logs, we are also displaying the authentication header values like username and password. Is there a way we can hide these headers and not display them?
How can i adjust the logs to select the type contents i want to be displayed on the test runner?

Screen Shot 2022-01-31 at 5 10 40 PM

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Checkmarx high severity risk for cy.api's yauzl dep

We are running Cypress 12.8 (planning to upgrade sooner than later) and using this plugin... since a couple of weeks ago our Checkmarx validation started to yell due to a high severity security risk for the "yauzl" package (among others) which is a dependency of cy-api.

What would be the approach to try to solve this? (For cy-api or any other packages.. we are getting high severity risk for other dependencies, most of them are Cypress' deps, but also some of other packages). Try asking Cypress and every npm package developer that has this issues to try to upgrade their dependencies?

I guess that just bypassing or ignoring these kind of warnings in Checkmarx is not an option.

cypress / yauzl @ 2.10.0
cypress / debug @ 3.2.7
cypress-grep / debug @ 4.3.1
cypress / debug @ 4.3.4
cypress / inflight @ 1.0.6

image

Thanks

Weird behavior when sending more than one request

I was trying to implement cy.api for an API testing suite.

For one scenario I have let's say 3 requests that happen. The first one returns some value that the second one needs for its body. So I went something like this:

cy.api("Req1", () => {
  do the request
  get the response
  Cypress.env("value", response.value)
})

cy.api("Req2", () => {
  do the request using "Cypress.env("value")" in body payload
  get the response  
})

I noticed that the second request was failing due to "Cypress.env("value")" was undefined... I tried different things, and then ended up changing "cy.api" for "cy.request", and magically, everything works as expected

It's as if cy.api is not waiting for the first request to complete before continuing with the second one, causing the env. varialbe to not be populated before the second request happens

Is this a known issue with cy.api? or some configuration problem?

Thanks

Potential stack trace improvement

Hi! First of all, thank you for the plugin! It works really well.

I have a question/suggestion.

If I use default cy.request(), on failure I get this behaviour:
image
So I could explore stack trace and click on link to go to test scenario.

Using cy.api(), seems I miss this opportunity:
image

Could it be improved somehow?

Best,
Vitali

RFC | Pretty print json

Request and Response are hard to read / analyse.
I propose this print format :
image
Can make a PR !

README Link Typo

There is a typo in the URL for one of the links in the README for this project.

Line 70 is missing the "r" in "server" in https://glebbahmutov.com/blog/api-testing-with-sever-logs/. The link goes to a GitHub Pages 404 error.

It should be https://glebbahmutov.com/blog/api-testing-with-server-logs/, I think.

  68 |  ## More info
  69 |  
- 70 |  - Read [Black box API testing with server logs](https://glebbahmutov.com/blog/api-testing-with-sever-logs/)
+ 70 |  - Read [Black box API testing with server logs](https://glebbahmutov.com/blog/api-testing-with-server-logs/)
  71 |  - Read [Capture all the logs](https://glebbahmutov.com/blog/capture-all-the-logs/) and [@bahmutov/all-logs][all-logs] module.
  72 |  - Read [You Should Test More Using APIs](https://glebbahmutov.com/blog/test-using-apis/)

P.S. Thank you for all your writing on the Cypress ecosystem!

Disabling GET/POST on absent /__messages__ endpoint

Good day,

I have commented out the following bunch of lines from support.js in order to avoid 401 errors on the server, where the person responsible for it is not willing to implement _ yet_ the @bahmutov/all-logs tool at this stage.

Lines 35-40, lines 100-163 and line 189

Result before commenting:
401__messages__

Could there be another way to make it an option, available before loading the cypress script?

I would rather leave cy-api's files untouched ๐Ÿ˜„

Thanks for any piece of advice

Respectfully

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.