node.jstestingfastify

Using fastify.inject() with a POST method


When writing a test for my Fastify app, I'm trying to call the fastify.inject() with a POST method:

const response = await server.inject({
  method: "POST",
  url: "/agents",
  headers: {
    "content-type": "application/json",
  },
  payload: {
    name: "Bla",
    description: "Bol",
  },
});

This is the endpoint definitions:

// POST /agents - Create a new agent
fastify.post("/", { schema: agentCreateSchema }, async (request, reply) => {
  const agentData = request.body as AgentCreateDto;
  const newAgent = await request.agentController.create(agentData);
  return reply.code(201).send(newAgent);
});

And here are the related definitions:

export const agentCreateSchema: FastifySchema = {
  body: AgentCreateDtoSchema,
  response: {
    201: AgentDtoSchema,
    400: ErrorResponseDtoSchema,
  },
};

export const AgentCreateDtoSchema = Type.Object({
  name: Type.String(),
  description: Type.Optional(Type.String()),
  maxEngineIterations: Type.Optional(Type.Number()),
  compositionMode: Type.Optional(Type.Enum(CompositionModeDto)),
  tags: Type.Optional(Type.Array(Type.String())),
});
export type AgentCreateDto = Static<typeof AgentCreateDtoSchema>;

However, I see the request is getting to the server, but my route code is not called... When doing the same with a GET or DELETE method (which have no body), I'm able to hit my route code.

All the routes are configured correctly and the url is as specified in the code example above. When running the server (not in test) and calling it with a regular HTTP call (not using inject()) everything works as expected.

Using body instead of payload produced the same results.

I also tried to JSON.stringify() the payload but getting the same result.

How can I call the inject() function with a POST method?

Edit: Sample repository


Solution

  • The issue was due to using Vitest's fake timers, which conflict with fastify.inject() behaviour. See here:

    My discussion on Fastify's GitHub

    My discussion on Vitest's GitHub