【问题标题】:How to test api route in nextjs with Jest如何使用 Jest 在 nextjs 中测试 api 路由
【发布时间】:2021-07-04 03:27:07
【问题描述】:

我的 api 文件夹中有一个函数,它可以搜索一组服务并根据 slug 返回一个服务。

api函数为:

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'})
    }
}

我如何开始为这个函数编写一个测试。我刚开始开玩笑,任何帮助都会很好。

【问题讨论】:

标签: jestjs next.js react-testing-library


【解决方案1】:

不确定您是否仍在寻找答案,但这似乎对我有用。它适用于默认的“hello”路由。我找到了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');
    });
});

【讨论】:

    猜你喜欢
    • 2020-09-25
    • 2021-06-14
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多