I'm having a hard time trying to mock a simple api request from a different port than the frontend.
The code below is returning: Timed out retrying after 5000ms: cy.wait() timed out waiting 5000ms for the 1st request to the route: convos. No request ever occurred.
cy.intercept("GET", "http://localhost:4000/conversations", {
fixture: "conversations.json",
}).as("convos");
cy.visit("http://localhost:3000/conversations");
cy.wait("@convos").then((req) => {
console.log(req);
});
Any idea what I might be doing wrong here?
UPDATE
I found the problem (but not the solution). Since I'm working with Nuxt, this specific api call is made with Nuxt's backend, so Cypress can't intercept it. Now I need to find a way for Cypress to intercept api calls made in Nuxt's backend.
2nd UPDATE
So the "solution" I found on the internet is the one below. But it doesn't work for me. The frontend page I'm visiting is throwing an Internal Server Error 500
.
in cypress.config.ts
inside setupNodeEvents
:
let server: any; // static reference to the mock server
on("task", {
mockServer({
interceptUrl,
fixture,
}: {
interceptUrl: string;
fixture: string;
}) {
const fs = require("fs");
const http = require("http");
const { URL } = require("url");
if (server) server.close(); // close any previous instance
const url = new URL(interceptUrl);
server = http.createServer((req: any, res: any) => {
if (req.url === url.pathname) {
const data = fs.readFileSync(`./cypress/fixtures/${fixture}`);
res.end(data);
} else {
res.end();
}
});
server.listen(url.port);
return null;
},
});
In my test before the visit():
cy.task("mockServer", {
interceptUrl: "http://localhost:4000/conversations",
fixture: "conversations.json",
});