For preflighted requests (e.g., requests with custom headers like Content-Type: application/json), Mentoss automatically sends an OPTIONS request before the actual request.
To mock this successfully, you must:
- Define an
OPTIONS route on your MockServer that returns the appropriate Access-Control-Allow-Origin and Access-Control-Allow-Headers. - Define the actual method route (e.g.,
GET, POST) with the same CORS headers.
If the OPTIONS response lacks the required headers, the original request will fail.
import { MockServer, FetchMocker } from "mentoss";
const BASE_URL = "https://api.example.com";
describe("My API", () => {
const server = new MockServer("https://www.example.com");
const mocker = new FetchMocker({
servers: [server],
baseUrl: BASE_URL,
});
const myFetch = mocker.fetch;
it("should return a 200 status code", async () => {
// Preflight request setup
server.options("/ping", {
status: 200,
headers: {
"Access-Control-Allow-Origin": BASE_URL,
"Access-Control-Allow-Headers": "Content-Type",
},
});
// Actual request setup
server.get("/ping", {
status: 200,
headers: {
"Access-Control-Allow-Origin": BASE_URL,
},
body: { message: "pong" },
});
const response = await myFetch("https://www.example.com/ping", {
headers: {
"Content-Type": "application/json",
},
});
expect(response.status).to.equal(200);
});
});