0

It seems that most people I read about experence zero trouble with this. I, on the other hand, have a test suite which someone else wrote, in which I'm trying to replace route() with intercept(). The API intercepts are done to handle button clicks etc., and about 99.9% percent of them fails if I just replace it. So, there's obviously some syntax in/use of intercept() I've not found a description for.

Example:

This works:

cy.route('POST', getApiPrefix() + '/prosjektfinansiering/'+ pfId +'/eiendom', result);

This does not work. The button click is not executed:

cy.intercept('POST', getApiPrefix() + '/prosjektfinansiering/'+ pfId +'/eiendom', result);

I've tried adding '**' in front of "/prosjekt...", and I've tried removing 'POST', with no luck.

Any ideas? I'll gladly post more info if necessary.

UPDATE:

Futher attempts:

Getting some hints here and there, it seems that this is a more correct way of using intercept():

return cy.intercept('POST', getApiPrefix() + '/prosjektfinansiering/'+ pfId +'/eiendom', {
    body: result
});    

This doesn't work, either.

The variables result in these examples is an object describing what is sent back to the frontend of the POST-request in the route matches the api path.

For troubleshooting, I can see that when using intercept(), there is ONE route that is not working when using intercept (the bottom one in the picture). However, I cannot for the life of me see why, and how the route match can be written differently?

enter image description here

2 Answers2

3

Most likely, you're mixing the old use of cy.route() and cy.server(). In my experience, those two won't work well together. It's easier when you're starting fresh with just cy.intercept().

Your update is correct too; You have to encapsulate the return value you want mocked in {body: value}.

Frank H.
  • 1
  • 1
  • 11
  • 25
2

from what I am seeing in your circled screenshot, the API is not called after you try to intercept it. (the count under # column is -)

You need to track when the API is to be called and ensure you intercept before the call is made. Cypres can help you with this. You can go through the run steps in the cypress window.

You could also share this if you don't mind.

If you are 100% certain the button makes the call. Steps should be:

cy.intercept() cy.get('button').click()

In the cypress window, right after the click, you should see the API being called.

psychowhiz
  • 131
  • 3
  • I've been digging, and you're right. Or, that's part of the answer. Actually, the call is made two times, first by a route() and then by an intercept(). Since it's already made, the second call will not be made, but it will still be the one that "counts". So, it seems I'm mixing route() and intercept() here. –  Jan 28 '22 at 17:45
  • It is advisable to stick to intercept(). The stub in the cy.route() is it different from the cy.intercept() for that specific endpoint? – psychowhiz Jan 28 '22 at 20:54