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:

https://i.sstatic.net/JKX2h.png

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

https://i.sstatic.net/6wQE5.png


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.

https://i.sstatic.net/dhieU.png

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

Encountering an issue with a Discord bot causing it to malfunction and deviate from its intended

Initially, everything appears to be functioning properly with the bot. When I execute the ?listen command, it responds correctly with bot is collecting messages now.... However, the ?stop command does not seem to have any effect. Furthermore, when I try th ...

When attempting to post data using jQuery, an object is encountered that does not have a parameterless constructor

Here is the code snippet I am using with jQuery to post data and register a band: var formData = new FormData(); var file = document.getElementById("CoverPicture").files[0]; formData.append("file", file); var Name = $('#Name').val(); var Genre = ...

Create a feature in three.js that allows users to click on an object to display information about the

After loading an object using the GLTF loader into my scene, I want to create a point on this object to display popup info. Is there a way to add a point to a specific location on the object? ...

How can I transfer Gmail message using express rendering parameters?

Using passport-google-oauth for authentication and the node-gmail-api for fetching gmail, I aim to display gmail message after authentication. In order to achieve this, I have written the following code in routes.js: app.get('/profile', isLogged ...

Issue with react-router-dom: <Route> elements are strictly meant for configuring the router and should not be rendered on their own

I've been grappling with this issue for quite some time now, but none of my attempts have succeeded and I keep encountering the same error: < Route> elements are for router configuration only and should not be rendered Here's the snippet ...

Express framework in NodeJS encounters an undefined header error

Utilizing Microsoft Flow to dispatch an HTTP POST request to my server, the request body includes a custom header known as "Email-To" with a string value. Here is the body: { "$content-type": "multipart/form-data", "$multipart": [ { "headers ...

The function of modal in JavaScript is not working properly

I am encountering a problem with my web page that is running on Wildfly 12. It is a simple Java EE project that I developed in Eclipse Neon. The issue arises when I try to use Bootstrap modals, as every time I attempt to open or use the methods in a JavaSc ...

The componentDidMount function is not initializing the state

I am trying to access the references from the render function and then set them to the state. Below is my code snippet: class App extends Component { constructor(props) { super(); this.arr = this.generateTimelineArray(); ...

Module for Npm that includes unique code for both proxy support and non-proxy support configurations

Is there a way to develop a javascript library (available as a module on npm) with multiple implementations based on the level of proxy support in the environment where it is executed (transpiled to)? From my understanding, babel may not easily transpile ...

The 'name' property of Axios and Vuex is not defined and cannot be read

When making a call to axios in my mounted function to retrieve profile data, I send the payload to the 'set_account' Vuex store upon success. To access this data, I utilize MapGetters (currentAccount) in computed properties. However, when tryin ...

Executing a function on the window object in JavaScript

I have come across the following code and am seeking guidance on how to get the last line to function correctly. The API I am using currently employs _view appended as its namespacing convention, but I would prefer to switch to something like arc.view.$f ...

"An issue arises when using req.body and res.render as the values retrieved are

Encountering an unusual problem - when using req.body to transmit form input to another page, the data is properly displayed when a single word is used in the input field (e.g. "FullName"). However, when there is a space, such as in the example "Full Name" ...

ng-class does not seem to be functioning properly when used within a file that is included via ng-include in

My question pertains to the menu I am loading using ng-include from the index file. <span ng-include="'app/components/common/menu.html'"></span> The content of menu.html is as follows: <li ng-class="active" > <a hr ...

Are elements in React Native PanResponder capable of being clicked?

While I have movable panresponders, I also require the ability to click on one for an onPress event. Is it achievable? At present, they are <View> elements. If I attempt to switch them to <TouchableOpacity> or a similar element, it results in ...

Alter the Default Visibility on an HTML Page from Visible to Hidden with JavaScript

I found this code snippet on a website and made some modifications. On my webpage, I have implemented links that toggle the visibility of hidden text. The functionality is working fine, but the issue is that the hidden text is initially visible when the p ...

What is the best way to include additional columns in a multiselect dropdown using jQuery select2?

I have implemented a multiselect dropdown feature using the jQuery select2 JavaScript library. The list items in this dropdown pertain to various medical drugs. I am looking to enhance this feature by adding a new column next to each selected drug, where ...

What is preventing my AJAX response from being ETag-cached without the If-None-Match header?

Below is the AJAX function I am using: function ajax(url, data) { return new Promise((resolve, reject) => { $.ajax({ url: "https://xxx", data: data, method: 'POST', timeout: 50000, ...

The spread operator in Vuex is causing compilation errors with babel, as it continuously results in a module build failure

Currently, I am utilizing a spread operator within my mapGetters object. It is crucial to use a specific babel-preset-stage for proper ES6 compilation. Even after installing babel-preset-stage-2 via npm, I encountered the following error: ERROR in ./~/bab ...

The concept of setTimeout and how it affects binding in JavaScript

I have limited experience with jquery, mainly using it for toggling classes. However, I will do my best to explain my issue clearly. I have three div elements and when one is clicked, the other two should rotate 90 degrees and then collapse to a height of ...

Vue is set up to monitor changes in two connected input fields for user input exclusively

Two input fields are available, where the value of one can affect the other. If a value between 1 and 200 is entered in the level field, Vue will look up the corresponding points for that level and populate the points field with them. Conversely, if a us ...