在 Jest 中使用 Next.Js 测试 Api

arp*_*ech 6 unit-testing reactjs jestjs next.js react-testing-library

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

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;
      });
  }
Run Code Online (Sandbox Code Playgroud)

测试文件.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);
  });
});
Run Code Online (Sandbox Code Playgroud)

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

Xun*_*ius 2

下面是我如何使用 Jest 和一个包(我创建的!)对航班数据 API 进行单元测试的示例next-test-api-route-handler,用于为 Next API 路线编写单元测试。我的测试的结构与您的非常相似。

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

npx jest --coverage --collectCoverageFrom 'src/**/*.ts' --collectCoverageFrom 'lib/**/*.ts'
Run Code Online (Sandbox Code Playgroud)

具体来说,--coverage告诉 Jest 收集覆盖率数据,通常收集到目录中./coverage,并且可选--collectCoverageFrom X告诉 Jest 仅从特定目录(或多个目录,如果指定了多个目录)收集覆盖率。