How to test api route in nextjs with Jest

Viewed 2183

I have a function in my api folder that searches an array of services and returns a single service depending on the slug.

The api function is:

import {services} from '../../../public/data/service.js'

export default async function getSingleService (req, res) {
    const serviceId = req.query.serviceID
    const result = services.filter((each) => each.url === serviceId )
    if(result.length > 0) {
        return res.status(200).json(result[0])
    } else {
        res.status(404).json({message: 'Service not found'})
    }
}

How do I got about to write a test for this function. I just started with jest, any help would be nice.

1 Answers

Not sure if you're still looking for an answer, but this seems to work for me. It works on the default "hello" route. I found it here

import { createMocks } from 'node-mocks-http';
import handler from '../../../pages/api/hello';

describe('/api/hello', () => {
    test('should returna an object with a name', async () => {
        const { req, res } = createMocks({
            method: 'GET'
        });

        await handler(req, res);
        expect(res._getStatusCode()).toBe(
            200
        );
        expect(
            JSON.parse(res._getData())
        ).toHaveProperty('name');
    });
});
Related