【发布时间】:2021-11-05 21:50:36
【问题描述】:
我试图在我的 Next.js 应用程序中为端点编写我的第一个 Jest 测试,无论我如何尝试“破坏”它,这个测试总是通过。这让我想,我做错了。这是我的 api/weather.js 端点:
const url = (city) => `https://api.weatherapi.com/v1/current.json?key=${process.env.WEATHER_API_KEY}&q=${city}`;
export default async function handler(req, res) {
const { query: { city } } = req
return fetch(url(city))
.then((response) => {
if(response.ok){
return response.json()
}
throw new Error('Response not OK')
})
.then((data) => res.status(200).json(data))
.catch(() => res.status(400).json({message: 'Currently not avaliable'}))
}
所以基本上我的前端向 api/weather 发出了一个请求,看起来有点像
const fetchCityData = () => {
const options = {
method: `POST`,
};
fetch(`/api/weather?city=${city}`, options)
.then((response) => { ......
我有一个测试端点的任务,我知道它应该测试 api/weather.js,因为这取决于我需要模拟请求的外部 API。我还是有点迷失在这里。另外,我使用查询字符串,我试图将其集成到我的笑话测试中,但不确定我在做什么
import nock from 'nock';
it('should return weather', () => {
nock('https://api.weatherapi.com/v1')
.get(`/current.json?key=123434&q=London`)
.reply(200, { results: [{ temp_c: '18 degrees' }] })
});
基本上,“现实生活”中发生的事情是,我在前端的输入中键入一个城市,该城市被发布到 api/weather.js,然后它将返回该城市的天气。我该如何测试它?我已经读了 3 天关于 nock and jest 的文章,但我真的不明白它背后的概念。另外,如果我将测试中的 .reply 重写为 400 或重写结果,测试仍然会通过。为什么?我做错了什么?
【问题讨论】:
标签: unit-testing jestjs next.js nock