oakserver / oak

A middleware framework for handling HTTP with Deno, Node, Bun and Cloudflare Workers 🐿️ 🦕

Home Page:https://oakserver.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How can i mock a `ctx.request.body` with oak

jbuendia1y opened this issue · comments

I build a api rest with oak and it's great but i found a problem, i don't now how mock the ctx.request.body with testing.createMockContext.

Please help

This is my code :

// animes.test.ts
import { assertEquals, testing } from "../../test.deps.ts";

Deno.test({
    name: "Animes routes",
    async fn(){
        // ... code
        const ctx = testing.createMockContext<"/">({
            path: API_PREFIX_V1 + "/animes",
       });

        // createAnime needs a ctx.request.body to works
        await controller.createAnime(ctx);
        console.log(ctx.response.body);
    }
})

// anime.controller.ts
class AnimeController{
// ... code
    public async createAnime(ctx: RouterContext<"/">) {
        if (!ctx.request.hasBody) {
          ctx.response.status = Status.BadRequest;
          return;
        }

        const result = ctx.request.body({ type: "json" });
        const data = new CreateAnime(await result.value);

        await this.repository.save(data);
        ctx.response.status = Status.Created;
    }
}

Use example:

// ... code
const ctxWithBody = mockRequestBody(ctx, {
      type: "json",
      value: Promise.resolve(mockCreateAnime),
})

await controller.createAnime(ctxWithBody);
assert(ctx.response.status, STATUS_TEXT.get(Status.Created));