Network requests not showing up in cypress command log - cypress

We are trying to write a cypress test that checks one of the xhr requests made from the page. However the requests that we are making are not showing up in the command log. They do however show up in the bash console after running cypress open.
Command log:
Bash console:
We have tried running our simple test against other domains such as cypress.io, and google.com. Requests show up just fine.
We have verified that the requests made are not fetch requests.
We have disabled chomeWebSecurity (not sure if relevant).
Here is the example we are using:
describe('example', () => {
it('visits a page', () => {
cy.server();
cy.route('POST', '**');
cy.visit('https://www.academia.edu/12297791/Open_Access_Meets_Discoverability_Citations_to_Articles_Posted_to_Academia.edu');
});
});
Here is our cypress.json file:
{
"chromeWebSecurity": false
}
We are running cypress version 3.4.1
I would expect the command log to have these post requests show up, like this documentation describes: https://docs.cypress.io/guides/guides/network-requests.html#Requests
Any help is greatly appreciated, as we're unsure how else to debug this.

1.) I would suggest to use a more up-to-date version of Cypress with the cy.intercept().
2.) A typical problem can be the timing - add a cy.wait(X) before it, or add a timeout to replace the default timeout.
3.) Make sure the path of the route/intercept, especially when it differs from the cy.visit() 's url.
4.) Additional hint, use aliases.

Related

How to set headers on every request in Cypress using cy.intercept

I am trying to add a request header to every api request generated in Cypress. I have a version that works using cy.server but this is being depricated, so I am trying to replace it with cy.intercept. I don't see any errors when I run this code, but I don't see the header added to my requests either:
beforeEach(() => {
cy.intercept('*',(req) => {
console.log('MATCHED INTERCEPT')
req.headers['my-test'] = 'TEST'
})
})
I can see the log text 'MATCHED INTERCEPT' in the console, so I know that the intercept is matching something....
Can anyone tell me what is wrong with this code?
I think you will not be able to see the new header after intercepting, as per their documentation :
Hope this was useful

slash command "dispatch_failed"

I have went through creating the custom slash command configuration via slack and installed it on workspace. However when I run it I get this
/testing failed with the error "dispatch_failed"
I tried multiple workspaces but same issue. Anyone experienced this?
So after a few tests, I found out that this is just a generic message of anything that fails at slack at this point. I have first my endpoint that was unreachable. So it was returning this message. I fixed that, used ngrok for tunnel so that I could debug and that is how I found this issue.
Also, this error can occur due to the following reasons as well.
Errors in code
Unreachable backend or Invalidly configured slash command in the app
While the documentation tells you:
"use the Request URL is your base server link + "/slashcommand" after it"
This is incorrect. The request URL should be: "/slack/events"
Of course the command needs to match whats in the 'edit command' window and in the method '.command' in your app.js:
app.command('/flash-card', async ({ ack, body, client })
If you're using ngrok http <port> to test in your localhost, be aware that a new ngrok public URL is created every time you run this command. So in https://api.slack.com/apps, in your app's Features, you may have to update your Slash Command' request URL with the current ngrok URL generated for you.
You need to set the Method in the Integration Settings to GET, is default to POST
This is also the error for a 404 Not Found.
If you're developing offline with ngrok, the 404 error can be seen in the terminal.
If you're deploying with serverless, ensure that you're handling the new endpoint /slack/command. One solution is to create a separate handler, i.e. /command.js
functions:
slack:
handler: app.handler
events:
- http:
path: slack/events
method: post
command:
handler: command.handler
events:
- http:
path: slack/command
method: post
[If your code is executing and u still have this error]
In my case using Slackbolt with js I forgot to add
await ack();
in called function so Slack api throw error.

Signin request failing due to invalid csrf

I am testing a signin page for keystonejs (http://demo.keystonejs.com/) and cannot get the request to succeed with cypress. A signin request without cypress has the following request headers:
while a request with a cypress test has the following request headers:
The only difference I can see is that the cookie is not set in the cypress test request. And because of that the request gets a 403. I am actually using a local version of that server in which I have the email/password configured as the one in the images. The demo site uses a different set provided in that page.
The test is simply:
describe('The Keystone Admin UI Signin Page', function () {
before(function() {
cy.visit('http://localhost:3000/keystone/signin')
})
it('should signin successfully with valid email/password', function () {
cy.get('#signin-view input[name=email]').clear().type('user#test.e2e');
cy.get('#signin-view input[name=password]').clear().type('test');
cy.get('#signin-view button[type=submit]').click();
cy.get('#react-root').should('be.visible');
})
})
Anyway to get around this?
I know this is an older question but I'll post this in case it helps anyone.
The key to fixing this issue for me was that Cypress clears all cookies before each test (https://docs.cypress.io/api/commands/clearcookies.html#).
So in the example above (and in my experience):
The first test (loading the page) is run and passes fine - at this point the browser has set the csrftoken cookie
The second test (submitting the form) runs but before this happens Cypress has deleted the csrftoken cookie - hence the error
To fix this I had to whitelist the csrftoken cookie in Cypress config which means that it will be exempt from this clearing process:
Cypress.Cookies.defaults({
whitelist: "csrftoken"
})
You can do this inline in your test file but the docs recommend using a support file:
A great place to put this configuration is in your cypress/support/index.js file, since it is loaded before any test files are evaluated.
Hope this helps, Stephen.
Following on from FlatSteve's answer, using with Laravel and updated prop names use;
Cypress.Cookies.defaults({
preserve: ["XSRF-TOKEN", "your_laravel_session_name", "remember_token"]
});

Cache internal routes with sw-precache

I'm creating a SPA using vanilla JavaScript and currently setting up sw-precache to handle the caching of resources. The service worker is generated as part of a gulp build and installed successfully. When I navigate to the root url (http://127.0.0.1:8080/) whilst offline the app shell displays, illustrating that resources are indeed cached.
I'm now attempting to get the SW to handle internal routing without failing. When navigating to http://127.0.0.1:8080/dashboard_index whilst offline I get the message 'Site can't be reached'.
The app handles this routing on the client side via a series of event listeners on the users actions or, in the case of using the back button, the url. When accessing one of these urls, no calls to the server should be made. As such, the service worker should allow these links to 'fall through' to the client side code.
I've tried a few things and expected this Q/A to solve the problem. I've included the current state of the generate-service-worker gulp task, and with this setup I'd expect to be able to access /dashboard_index offine. Once this is working I can adapt the solution to cover other routes.
Any help much appreciated.
gulp.task('generate-service-worker', function(callback) {
var rootDir = './public';
swPrecache.write(path.join(rootDir, 'sw.js'), {
staticFileGlobs: [rootDir + '/*/*.{js,html,png,jpg,gif,svg}',
rootDir + '/*.{js,html,png,jpg,gif,json}'],
stripPrefix: rootDir,
navigateFallback: '/',
navigateFallbackWhitelist: [/\/dashboard_index/],
runtimeCaching: [{
urlPattern: /^http:\/\/127\.0\.0\.1\:8080/getAllData, // Req returns all data the app needs
handler: 'networkFirst'
}],
verbose: true
}, callback);
});
update
The code to the application can be found here.
Removing the option navigateFallbackWhitelist does not chage the result.
Navigating to /dashboard_index whilst offline prints the following to the console.
GET http://127.0.0.1:8080/dashboard_index net::ERR_CONNECTION_REFUSED
sw.js:1 An unknown error occurred when fetching the script.
http://127.0.0.1:8080/sw.js Failed to load resource: net::ERR_CONNECTION_REFUSED
The same An unknown error occurred when fetching the script. is also duplicated in the 'application > service workers' tab of chrome debug tools.
It's also noted that the runtimeCaching option is not caching the json response returned from that route.
For the record, in case anyone else runs into this, I believe this answer from the comments should address the issue:
Can you switch from navigateFallback: '/' to navigateFallback:
'/index.html'? You don't have an entry for '/' in your list of
precached resources, but you do have an entry for '/index.html'.
There's some logic in place to automatically treat '/' and
'/index.html' as being equivalent, but that doesn't apply to what
navigateFallback is doing...

How to manually send HTTP POST requests from Firefox or Chrome browser

I want to test some URLs in a web application I'm working on. For that I would like to manually create HTTP POST requests (meaning I can add whatever parameters I like).
Is there any functionality in Chrome and/or Firefox that I'm missing?
I have been making a Chrome app called Postman for this type of stuff. All the other extensions seemed a bit dated so made my own. It also has a bunch of other features which have been helpful for documenting our own API here.
Postman now also has native apps (i.e. standalone) for Windows, Mac and Linux! It is more preferable now to use native apps, read more here.
CURL is awesome to do what you want! It's a simple, but effective, command line tool.
REST implementation test commands:
curl -i -X GET http://rest-api.io/items
curl -i -X GET http://rest-api.io/items/5069b47aa892630aae059584
curl -i -X DELETE http://rest-api.io/items/5069b47aa892630aae059584
curl -i -X POST -H 'Content-Type: application/json' -d '{"name": "New item", "year": "2009"}' http://rest-api.io/items
curl -i -X PUT -H 'Content-Type: application/json' -d '{"name": "Updated item", "year": "2010"}' http://rest-api.io/items/5069b47aa892630aae059584
Firefox
Open Network panel in Developer Tools by pressing Ctrl+Shift+E or by going Menubar -> Tools -> Web Developer -> Network. Select a row corresponding to a request.
Newer versions
Look for a resend button in the far right. Then a new editing form would open in the left. Edit it.
Older versions
Then Click on small door icon on top-right (in expanded form in the screenshot, you'll find it just left of the highlighted Headers), second row (if you don't see it then reload the page) -> Edit and resend whatever request you want
Forget the browser and try CLI. HTTPie is a great tool!
CLI HTTP clients:
HTTPie
Curlie
HTTP Prompt
Curl
wget
If you insist on a browser extension then:
Chrome:
Postman - REST Client (deprecated, now has a desktop program)
Advanced REST client
Talend API Tester - Free Edition
Firefox:
RESTClient
Having been greatly inspired by Postman for Chrome, I decided to write something similar for Firefox.
REST Easy* is a restartless Firefox add-on that aims to provide as much control as possible over requests. The add-on is still in an experimental state (it hasn't even been reviewed by Mozilla yet) but development is progressing nicely.
The project is open source, so if anyone feels compelled to help with development, that would be awesome: https://github.com/nathan-osman/Rest-Easy
* the add-on available from http://addons.mozilla.org will always be slightly behind the code available on GitHub
You specifically asked for "extension or functionality in Chrome and/or Firefox", which the answers you have already received provide, but I do like the simplicity of oezi's answer to the closed question "How can I send a POST request with a web browser?" for simple parameters. oezi says:
With a form, just set method to "post"
<form action="blah.php" method="post">
<input type="text" name="data" value="mydata" />
<input type="submit" />
</form>
I.e., build yourself a very simple page to test the POST actions.
I think that Benny Neugebauer's comment on the OP question about the Fetch API should be presented here as an answer since the OP was looking for a functionality in Chrome to manually create HTTP POST requests and that is exactly what the fetch command does.
There is a nice simple example of the Fetch API here:
// Make sure you run it from the domain 'https://jsonplaceholder.typicode.com/'. (cross-origin-policy)
fetch('https://jsonplaceholder.typicode.com/posts',{method: 'POST', headers: {'test': 'TestPost'} })
.then(response => response.json())
.then(json => console.log(json))
Some of the advantages of the fetch command are really precious:
It's simple, short, fast, available and even as a console command it stored on your chrome console and can be used later.
The simplicity of pressing F12, write the command in the console tab (or press the up key if you used it before) then press Enter, see it pending and returning the response is what making it really useful for simple POST requests tests.
Of course, the main disadvantage here is that, unlike Postman, this won't pass the cross-origin-policy, but still I find it very useful for testing in local environment or other environments where I can enable CORS manually.
Here's the Advanced REST Client extension for Chrome.
It works great for me -- do remember that you can still use the debugger with it. The Network pane is particularly useful; it'll give you rendered JSON objects and error pages.
For Firefox there is also an extension called RESTClient which is quite nice:
RESTClient, a debugger for RESTful web services
It may not be directly related to browsers, but Fiddler is another good software.
You could also use Watir or WatiN to automate browsers. Watir is written for Ruby and Watin is for .NET languages. I am not sure if it's what you are looking for, though.
http://watin.sourceforge.net/
http://watir.com/
There have been some other clients born since the rise of Postman that is worth mentioning here:
Insomnia: with both desktop application and Chrome plugin
Hoppscotch: previously known as Postwoman, and with a Chrome plugin available as well. You can also make it work locally with docker if you want to get funny
Paw: if you are on Mac
Advanced Rest Client: already mentioned as a Chrome plugin, but it is worth pointing out that it also has a desktop application
soapUI: written in Java and with lots of testing functionality
Boomerang: yet another way to test APIs. It comes with SOAP integration and it also has a Chrome plugin available
Thunder Client: if you use VS Code as your text editor then you should go and check out this awesome extension
Try Runscope. A free tool sampling their service is provided at https://www.hurl.it/.
You can set the method, authentication, headers, parameters, and body. The response shows status code, headers, and body. The response body can be formatted from JSON with a collapsable hierarchy.
Paid accounts can automate test API calls and use return data to build new test calls.
COI disclosure: I have no relationship to Runscope.
Check out http-tool for Firefox...
Aimed at web developers who need to debug HTTP requests and responses.
Can be extremely useful while developing REST based API.
Features:
GET
HEAD
POST
PUT
DELETE
Add header(s) to request.
Add body content to request.
View header(s) in response.
View body content in response.
View status code of response.
View status text of response.
So it occurs to me that you can use the console, create a function, and just easily send requests from the console, which will have the correct cookies, etc.
so I just grabbed this from here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options
// Example POST method implementation:
async function postData(url = '', data = {}, options = {}) {
// Default options are marked with *
let defaultOptions = {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
}
// update the default options with specific options (e.g. { "method": "GET" } )
const requestParams = Object.assign(defaultOptions, options);
const response = await fetch(url, requestParams);
return response.text(); // displays the simplest form of the output in the console. Maybe changed to response.json() if you wish
}
IF YOU WANT TO MAKE GET REQUESTS, you can just put them in your browser address bar!
if you paste that into your console, then you can make POST requests by repeatedly calling your function like this:
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // you might want to use JSON.parse on this
});
and the server output will be printed in the console (as well as all the data available in the network tab)
This function assumes you are sending JSON data. If you are not, you will need to change it to suite your needs
You can post requests directly from the browser with ReqBin.
No plugin or desktop application is required.
I tried to use postman app, had some auth issues.
If you have to do it exclusively using browser, go to network tab, right click on the call, say edit and send response. There is a similar ans on here about Firefox, this right click worked for me on edge and pretty sure it would work for chrome too
Windows CLI solution
In PowerShell you can use Invoke-WebRequest. Example syntax:
Invoke-WebRequest -Uri http://localhost:3000 -Method POST -Body #{ username='clever_name', password='hunter2' } -UseBasicParsing
On systems without Internet Explorer, you need the -UseBasicParsing flag.
The question being 12 years old now, it is easy to understand why the author asked a solution for Firefox or Chrome back then. After 12 years though, there are also other browsers and the best one which does not involve any add-ons or additional tools is Microsoft Edge.
Just open devtools (F12) and then Network Console tab (not the Network or Console tab. Click on + sign and open it, if it is not visible.).
And here is the official guide:
https://learn.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium/network-console/network-console-tool
Have fun!

Resources