如何解决在Jest中使用Next.Js测试Api
我想使用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;
});
}
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);
});
});
我尝试了很多方法。任何参考或建议都可以。 预先感谢
解决方法
以下是我如何unit tested a flight data API 使用 Jest 和 next-test-api-route-handler
的示例,这是一个(我创建的!)用于为 Next API 路由编写单元测试的包。我的测试结构与您的非常相似。
为了通过 Jest 生成覆盖数据(假设您安装了 Node),我运行以下命令:
npx jest --coverage --collectCoverageFrom 'src/**/*.ts' --collectCoverageFrom 'lib/**/*.ts'
具体来说,--coverage
告诉 Jest 收集覆盖率数据,通常在目录 ./coverage
中,可选的 --collectCoverageFrom X
告诉 Jest 仅从特定目录(或多个目录)收集覆盖率指定)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。