Next.js Discord

Discord Forum

Json parsing issue testing API routes with cypress

Answered
CuriouslyCory posted this in #help-forum
Open in Discord
I have a test that is validating a NextJS pages dir API endpoint.
Testing manually through curl, or posting from a separate website parses the JSON body decoding it and provides an object to the request.body, but when I test through cypress the request stays as a string.

As a workaround I can serialize the object instead of stringifying, but it seems like the test would potentially miss errors that occur during the parsing process:

// cypress/e2e/error-logger.cy.ts

import SuperJSON from "superjson";

const testRequest = {
  message: "Cypress test",
  stack: "Stack trace",
  originalError: new Error("Original error"),
  priority: "critical",
};

describe("Error logger", () => {
  // Slack url is set in the env vars. Please don't run tests against the production slack url.
  it("Should return 200 if valid request", () => {
    cy.request({
      method: "POST",
      url: "/api/error-logger",
      body: SuperJSON.stringify(testRequest),
    })
      .its("status")
      .should("eq", 200);
  });
});


// pages/api/error-logger.tsx
// called by cypress e2e test
console.log(typeof req.body);
// output: string

// called by curl post
console.log(typeof req.body);
// output: object
Answered by Golden-winged Warbler
are you setting the content-type header to application/json in curl and/or cypress?
View full answer

3 Replies

Golden-winged Warbler
are you setting the content-type header to application/json in curl and/or cypress?
Answer
Golden-winged Warbler
I can imagine next making choices based on that
You're right! That totally solved it! Thank you.