How can I stub a response of a HTTP request?
Let me explain it with my code I have now:
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) => {
})
})
With this code I am trying to stub the response for the following request:
But it still gives the following error, where I can understand the stub did not work:
We attempted to make an http request to this URL but the request failed without a response.
I've tried already different intercept methods of cypress but I couldn't get worked.
I even can't intercept the /token endpoint with the following:
cy.intercept({
method: 'POST',
url: 'https://login.microsoftonline.com/2ba13024-a5f6-4b30-afa8-d673b5166d23/oauth2/v2.0/token',
}).as('apiCheck')
I'm not sure without seeing the whole test, but are you are issuing the POST to microsoftonline from within the test using cy.request()?
If so, you can't use cy.intercept() to catch it, only requests from the app will be caught.
But you can append 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 in this code req.reply() and req.continue() you are both stubbing (with reply) and continuing to the server (with continue), which are opposite actions. You would only want to do one or the other.
cy.intercept('**/oauth2/v2.0/token', (req) => {
req.reply({
token_type: "Bearer",
expires_in: 3795,
access_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJS"
})
req.continue((res) => {
})
})