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.