Next.js Discord

Discord Forum

How does next13's /app routing api integrate Jest testing?

Unanswered
Gharial posted this in #help-forum
Open in Discord
GharialOP
The api routing style I use is export async function POST(), but it is not like an endpoint in /page, which makes it difficult for me to simulate this service as usual

6 Replies

GharialOP
My test code looks like this:
describe(...
  it(...
    const mockInput = {...}
    const mockRequest = {
    method: "POST",
    body: mockInput,
    } as unknown as Request;
  
    const mockResponse = {
      status: jest.fn(),
      json: jest.fn(),
    } as unknown as Response;
  
    await POST(mockRequest, mockResponse);
      
    expect(mockResponse.status).toHaveBeenCalledWith(200);
    expect(mockResponse.json).toHaveBeenCalledWith(expect.anything());
  )
)
And the types passed in by my POST are the native Request and Response types.
The result is this error:
expect(jest.fn()).toHaveBeenCalledWith(...expected) Expected: 200 Number of calls: 0
Looks like the request is not being impersonated to run? thus not getting any response.:blob_thonkang:
GharialOP
If someone can give me a complete case then I would really appreciate it:all_the_things: