Reputation: 11
I am using NextJs routes, Prisma and Postgres. My user route works, but the test does not. I get the error message:
TypeError: Response.json is not a function
For the line in route.ts
return NextResponse.json({data: users}, {status: 200});
But it works in test it manually to a local host web page.
/src/app/api/users/route.ts
import { NextResponse, NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
// routes /api/users
export async function GET(request: NextRequest) {
const users = await prisma.user.findMany({
orderBy: {
last_name: 'asc',
}
})
return NextResponse.json({data: users}, {status: 200});
}
/test/app/api/users/route.test.tsx
import { GET } from '@/app/api/users/route';
import { NextRequest } from 'next/server';
// import { prisma } from '@/lib/prisma';
import { prisma } from '../../../../src/lib/prisma';
// Mock the Prisma module
// jest.mock('@/lib/prisma', () => ({
jest.mock('../../../../src/lib/prisma', () => ({
prisma: {
user: {
findMany: jest.fn(),
},
},
}));
describe('GET /api/users', () => {
it('should return an array of users sorted by last name', async () => {
const mockedRequest = {} as NextRequest;
const mockedUsers = [
{ id: 1, last_name: 'User A' },
{ id: 2, last_name: 'User B' },
];
// Mock the behavior of prisma.user.findMany
(prisma.user.findMany as jest.Mock).mockResolvedValue(mockedUsers);
// Call the GET function with the mocked request
const response = await GET(mockedRequest);
// Assert that prisma.user.findMany has been called with the correct parameters
expect(prisma.user.findMany).toHaveBeenCalledWith({
orderBy: {
last_name: 'asc',
},
});
// Assert the response
expect(response.status).toBe(200);
expect(response.body).toEqual({ data: mockedUsers });
});
});
I was expecting the test to pass. I tried to format the output as
return NextResponse.json({data: bowls}, {status: 200}) as unknown as any;
but I still get the same error
Upvotes: 1
Views: 143