Guide on simulating an incoming http request (response) using cypress

Is there a way to mock a response for an HTTP request in Cypress?

Let me demonstrate my current code:

Cypress.Commands.add("FakeLoginWithMsal", (userId) => {
   
    cy.intercept('**/oauth2/v2.0/token', (req) => {
        
        req.reply({
            token_type: "Bearer",
            expires_in: 3795,
            access_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJS"
            })

        req.continue((res) => {

        })
    })

This code attempts to stub the response for the specified request:

However, I encountered the following error which indicates that the stub did not work as intended:

We attempted to make an http request to this URL but the request failed without a response.

I have experimented with various intercept methods in Cypress, but so far, I haven't been able to achieve success.


Even using the following didn't help me intercept the /token endpoint:

   cy.intercept({
    method: 'POST',
    url: 'https://login.microsoftonline.com/xx-xx-xx-xx-/oauth2/v2.0/token',
}).as('apiCheck')


Update: @Fody Thank you very much (again) for your response. My goal is to stub all MSAL endpoints, not for testing purposes, but within a login command.

Below is the revised code snippet:

Cypress.Commands.add("FakeLoginWithMsal", (userId) => {
    cy.intercept('GET', '**/authorize', { fixture: 'authorizeStub.json' })
    cy.intercept('GET', '**/v2.0/.well-known/openid-configuration', { fixture: 'openidConfigurationStub.json' })

cy.request({
    method: 'POST',
    url: 'https://login.microsoftonline.com/xxxxx/oauth2/v2.0/token',
    body: {
        grant_type: "password",
        client_id: "xxxxxxxxxxxxx",
        client_secret: "xxxxxxxxxxx",
        scope: "api://xxxxxxxxxxxxxx/Cp.Use",
        username: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f5757576f57575757014c4042">[email protected]</a>",
        password: "xxxxx",
    },
    form: true,
}).then(response => {
    cy.log(JSON.stringify(response))
    cy.intercept('response', { fixture: 'tokenStub.json' })

    })

The above code involves mocking responses for three endpoints:

GET: /authorize (stubbed using a fixture)

GET: /openid-configuration (stubbed using a fixture)

Post: /token --> This POST request has a response containing the access token. I want to stub this response.

I believe that this response corresponds to an "incoming HTTP request" (refer to attachments). The incoming HTTP response is precisely what I aim to stub using a fixture.

Answer №1

If you are unsure about the test, make sure you issue the POST to microsoftonline using cy.request() within the test.

Remember that cy.intercept() can only catch requests from the app, not those made by cy.request().

You can always add a .then() to the cy.request() to wait for the response.

cy.request({
  method: 'POST',
  url: 'https://login.microsoftonline.com/.../oauth2/v2.0/token',
})
.then(response => {
  // handle response
})

Also, be cautious when using both req.reply() and req.continue() in your code. These actions (replying and continuing) are opposites, so choose one based on your needs.

cy.intercept('**/oauth2/v2.0/token', (req) => {
        
  req.reply({
    token_type: "Bearer",
    expires_in: 3795,
    access_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJS"
  })

  // Choose either reply or continue
  
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying a project in the same location using jQuery

Struggling with jQuery and positioning hidden items that need to be shown? I have two white boxes - the left one is the Client Box (with different names) and the right one is the Project Box (with different projects). My goal is to show the projects of a c ...

Observing a global object's attribute in Angular JS

Imagine you have an object in the global scope (yes, I know it's not ideal but just for demonstration purposes) and you wish to monitor a property of that object using Angular JS. var person = { name: 'John Doe' }; var app = angular.mod ...

The Design and Layout of a MEAN Stack Application

When creating a MEAN Stack app using the express-generator npm, everything worked perfectly but I found myself confused about the purpose of certain files. For instance: The package.json included this code snippet: "script":{"start": "node ./bin/www"} ...

Steps for regularly executing 'npm run build' on the server

My website doesn't require frequent content updates, as users don't always need the latest information. As a result, most pages are generated server-side and served as static pages. There will be occasional database updates that need to be visib ...

What is the proper way to assign an array of objects to an empty array within a Vue component?

I'm currently working on my first Laravel project using Vue components. My setup includes Laravel 8.x and Vue 2.x running on Windows 10. I came across a helpful video tutorial that I'm trying to follow, but some aspects aren't quite working ...

Adjusting the height of the Tinymce Editor in React Grid Layout after the initial initialization

I am facing a challenge with my React Component that displays a tinymce editor. The task is to dynamically adjust the height of the editor after it has been initialized. To achieve this, I am utilizing the "React Grid Layout" package for resizing the compo ...

At what point should the term "function" be included in a ReactJS component?

As a beginner in ReactJS, I have been working through some tutorials and noticed that some code examples use the keyword function while others do not. This got me wondering what the difference is and when I should use each one. Render Example with functi ...

Guide to implementing controllers in vuejs2

Hey there, I recently started using vuejs2 with a project that is based on laravel backend. In my vuejs2 project, I wrote the following code in the file routes.js export default new VueRouter({ routes: [{ path: '/test', component: ...

Any tips for customizing the appearance of a {Switch} component from react-router-dom? I attempted to encase it in a <div> element, but it did

https://i.stack.imgur.com/4piCG.jpg https://i.stack.imgur.com/CyQH3.jpg My code attempts to modify the styling of the map component, but it seems to be influenced by the Switch component. How can I ensure that the screen fits within the 'root' ...

Switch the image displayed on hover over an image using the #map attribute

Recently, I successfully integrated a database connection into this website and made it dynamic. The overall design of the site was already in place, so my main focus was on adding the functionality of the database connection. However, after implementing ...

Adjusting the height of a GAS iframe in WordPress with iframe-resizer: A step-by-step guide

I would like to embed an iframe of my Google Application Script Web into my WordPress site without the scroll bar. Refer to the image below for context. https://i.stack.imgur.com/7L6Tw.png I encountered an error message while attempting to use the iframe ...

After an ajax call in ASP .NET MVC3 using Razor, jQuery may not function properly

When I perform a post back to obtain a partial view using ajax, I utilize the following code to render the partial view within a div named 'DivSearchGrid'. <script type ="text/javascript" > $('#Retrieve').click(function ( ...

Instructions on adding a file path to the package.json file

Is it possible to create a script in the package.json file that allows me to run a file located in the parent folder of the package.json file, rather than the same directory? I would like the syntax to be similar to this: "scripts": { "server": " ...

Encountering an issue with executing Google API Geocode in JavaScript

I'm having trouble printing an address on the console log. Every time I run the code, I encounter an error message that reads: { "error_message" : "Invalid request. Missing the 'address', 'components', 'latlng' or &ap ...

Validating minimum and maximum values with Angular 2 FormBuilder

I am currently developing a form using Angular 2 Formbuilder and I want to ensure that users can only input positive values into the amount field (with a minValue of 0 and maxValue of 100). How can I go about implementing minimum and maximum value validati ...

Accessing a precise div element in a webpage

Currently, I am utilizing Vue.js and Nuxt for my web development. One issue I am facing is related to anchors. Specifically, when I navigate to mysite.com/page1#section1, I want the page to scroll to section1. In my code, I have the following snippet: < ...

Can we maintain an active connection by flushing a node's response to the client?

I am facing a challenge with a large data-set that needs to be converted to CSV for a client. The processing of the entire set at once causes it to time out before completion. To address this issue, I have started loading the data in chunks for more effici ...

Sharing environment variables between a React app and an Express.js server that hosts it as a static site can be achieved by setting

My static site react app is hosted under an express server project in a folder called client/build. The oauth redirect uris point to the express server for token retrieval. The react app redirects users to the oauth endpoint, which is also referenced by th ...

Conceal a div and label after a delay of 5 seconds with a JavaScript/jQuery function in C#

Here is a sample div: <div class="alert alert-success alert-dismissable" runat="server" visible="false" id="lblmsgid"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ...

Unable to handle JQuery POST to PHP in success function

I am struggling with a jQuery post function that is supposed to call a PHP script in order to retrieve a value from the database. Although I can see in Firebug that the PHP file is being called and returning a 200 OK status, the success function in my JS ...