Mimic Ajax requests with Supertest
This might be more of a Superagent question but thought I would start here.
I'm using Supertest (and thus Superagent) for some API testing on a Node.js project. I have a particular route that returns different content based on the type of request. Using expressJS's req.xhr, the code will return JSON if true or issue a redirect if false. I want to account for this in my tests but I'm struggling to get Superagent to mimic an XHR GET request.
According to ExpressJS documentation, it's looking for the X-Requested-With header in the request to be set to the value XMLHttpRequest. When I try to set this header using .set('X-Requested-With', 'XMLHttpRequest') I get
Unhandled rejection Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
Odd thing is, I can set other headers, even before this one, just fine
.set('Accept', 'application/json'). If the headers have already been written, this should fail too, but it doesn't. Also, checking res.request.req._headers, it appears nothing else is setting X-Requested-With so it's not like something else gave it a value either.
Yes SuperAgent says this is more likely an issue with SuperTest
Try using res.headersSent. A possibility is your request is being responding to prematurely somewhere before control actually reaches your intended response point.