Open
Description
I want to test my server api endpoint and mock useRequireSession but I cannot get it to work
I am trying something like this
// @vitest-environment nuxt
import { describe, it, expect, vi } from "vitest";
import { createEvent } from "h3";
import { IncomingMessage, ServerResponse } from "http";
import { Socket } from "net";
import userHandler from "~/server/api/profile/index.get";
// Mock the module
vi.mock("nuxt-auth-utils", () => ({
requireUserSession: vi.fn()
}));
describe("API - /api/profile", () => {
it("should return user data if session exists", async () => {
// TypeScript may not recognize this, so use @ts-ignore if necessary
// @ts-ignore
const { requireUserSession } = await import("nuxt-auth-utils");
requireUserSession.mockResolvedValue({
user: {
id: 1,
username: "name",
roles: ["ROLE_1", "ROLE_2"]
}
});
// Create a mock socket and request/response objects
const socket = new Socket();
const req = new IncomingMessage(socket);
const res = new ServerResponse(req);
req.url = "/api/profile";
req.method = "GET";
const event = createEvent(req, res);
const response = await userHandler(event);
console.log(response, "res");
expect(requireUserSession).toHaveBeenCalledTimes(1);
});
But it is not working as in my endpoint the problem is
ReferenceError: requireUserSession is not defined
❯ Module.default server/api/profile/index.get.ts:6:19
and I cannot import requireUserSession in my endpoint as when I type
import requireUserSession it says that it need a second argument of type Nuxt?
Can someone please help me?