在 Jest 中使用 Next.Js 测试 Api [英] Testing Api with Next.Js in Jest

查看:61
本文介绍了在 Jest 中使用 Next.Js 测试 Api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Jest 为我的 Api 文件编写测试用例.这使用 Next.js.我尝试了很多东西,但无法获得任何文件覆盖.

I wanted to write test cases for my Api file using Jest. That uses Next.js. I tried many things but was not able to get any coverage of file.

ApiFile.js

const axios = require('axios');
import getConfig from 'next/config';

export default async (req, res) => {
  const {query: { param }} = req;
  const response = await customerInfo(param);

  if (!response.data || response.data == null) 
    res.status(200).send({ data: [], status: response.status});
  else
    res.status(200).send({ data: response.data.results, status: response.status });
};
async function customerInfo(params) {
    const { serverRuntimeConfig } = getConfig();
    const URL = serverRuntimeConfig.API;
    const config = {
      timeout: 15000,
      headers: {
        'content-type': 'application/json'
      },
    };
    const customer_id = params[0];
    const url = `${URL}/customer/${customer_id}`;
    return await axios
      .get(`${url}`, config)
      .then(response => {
        return response
      })
      .catch(function(error) {
        throw error;
      });
  }

TestFile.js

TestFile.js

import mockAxios from "axios";
import mockData from "./customerMock.json";
import customerInfo from "../[...param]";

describe('fetchData', () => {
  it('fetches successfully data from an API', async () => {
    const data = mockData.data; 
    jest.spyOn(mockAxios, 'default');
    const endpoint = '${URL}/customer/abcdef';
    const method = 'get';
    const params = {
      customer_id : 'abcdef'
    }
    customerInfo(params);
    expect(mockAxios.default).toBeCalledWith(params);
  });
  it('fetches erroneously data from an API', async () => {
    const errorMessage = 'Network Error'; 
    mockAxios.get.mockImplementationOnce(() =>
      Promise.reject(new Error(errorMessage)),
    ); 
    await expect(customerInfo('react')).rejects.toThrow(errorMessage);
  });
});

我尝试了很多方法.任何参考或建议都会起作用.提前致谢

I have tried many ways. Any reference or suggestion will work. Thanks in advance

推荐答案

这是我如何使用 Jest 和 next-test-api-route-handler,一个用于为 Next 编写单元测试的包(我创建的!)API 路由.我的测试结构与您的非常相似.

Here's an example of how I unit tested a flight data API using Jest and next-test-api-route-handler, a package (I created!) for writing unit tests for Next API routes. My tests are structured very similarly to your own.

要通过 Jest 生成覆盖率数据(假设您安装了 Node),我运行以下命令:

To generate coverage data through Jest (assuming you have Node installed), I run the following command:

npx jest --coverage --collectCoverageFrom 'src/**/*.ts' --collectCoverageFrom 'lib/**/*.ts'

具体来说,--coverage 告诉开玩笑收集覆盖率数据,通常到目录 ./coverage 和可选的 --collectCoverageFrom X 告诉 Jest 仅从特定目录(或指定多个目录)收集覆盖范围.

Specifically, --coverage tells Jest to collect coverage data, usually into the directory ./coverage, and the optional --collectCoverageFrom X tells Jest to collect coverage only from a specific directory (or directories if multiple are specified).

这篇关于在 Jest 中使用 Next.Js 测试 Api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆