如何在Cypress项目中从mock-server.org获取请求体?
Absolutely! You can totally capture and inspect request bodies sent to your mock-server.org instance right from Cypress, and it’s actually pretty straightforward. Here are a couple of reliable approaches to pull this off:
Mock-server.org maintains a detailed log of every incoming request, which you can access via its REST API. This is perfect if you need to verify requests that might be sent outside of Cypress's direct control (like from your app's frontend code).
- First, before your test runs, consider clearing the existing request log to avoid old requests messing with your assertions. You can do this with a simple DELETE request:
cy.request('DELETE', 'http://your-mock-server:1080/api/requests'); - After triggering the request you want to test (either via app interaction or
cy.request()), fetch the full request log:cy.request('GET', 'http://your-mock-server:1080/api/requests') .then((response) => { // Filter the log to find the specific request you care about const targetRequest = response.body.requests.find(req => req.path === '/your-target-endpoint' && req.method === 'POST' ); // Extract the request body for validation const requestBody = targetRequest.body; // Now validate the structure and content expect(requestBody).to.have.property('userId', 123); expect(requestBody.data).to.be.an('object').that.includes({ name: 'Test User' }); // Add any other assertions you need });
If the request is being sent either via cy.request() or your app's frontend (that's under Cypress's control), you can use Cypress's cy.intercept() to capture the request before it reaches the mock server. This gives you instant access to the request body without needing to hit the mock server's API.
- Set up the intercept first (make sure this runs before the request is triggered):
cy.intercept('POST', '/your-target-endpoint').as('postRequest'); - Trigger the request (either via
cy.request()or by interacting with your app):// Example using cy.request() cy.request('POST', 'http://your-mock-server:1080/your-target-endpoint', { userId: 123, data: { name: 'Test User' } }); // Or trigger via app interaction, e.g.: // cy.get('#submit-button').click(); - Wait for the intercept to catch the request, then validate the body:
cy.wait('@postRequest').then((interception) => { const requestBody = interception.request.body; // Run your validations expect(requestBody.userId).to.equal(123); expect(requestBody.data.name).to.equal('Test User'); });
Quick Notes:
- For
cy.intercept(), always set up the intercept before triggering the request—otherwise, Cypress won't catch it. - If you're testing requests from your app, make sure your app is configured to send requests to the mock server instance that Cypress can reach.
内容的提问来源于stack exchange,提问作者MiklosBalazsi

