我想用玩笑来测试API端点,以检查它是否返回响应以及JSON是否包含我需要的参数键。
我的功能如下:
export function getFiveDayWeatherByCoordinates(id) {
let url = FORECAST_ID_URL(id);
return fetch(url)
.then(response => response.json())
.then(data => {
return data;
})
.catch(err => console.log(err));
}
它返回带有一组参数的JSON,我将仅发布快照:
{
cnt: 14,
cod: "200",
city: {
coord: {lat: 38.7169, lon: -9.1333},
country: "PT",
id: 8012502,
name: "Socorro",
population: 0,
timezone: 3600,
}
到目前为止,我看到的每个教程都说要模拟响应,但是我想测试实际的API。
答案 0 :(得分:0)
我建议使用Frisby.js测试API响应。这是在Jest中运行的API测试的出色测试框架。我已经多次使用它来编写API和后端集成测试。虽然,我通常将这些测试套件与UI单元测试分开。
这是一个例子:
it('should return weather coords', async () => {
return frisby
.get(`${global.apiUrl}/my-weather-endpoint`)
.expect('status', 200)
.expect('jsonTypes', Joi.object({
cnt: Joi.number().required(),
cod: Joi.string().required(),
city: Joi.object({
coord: Joi.object({
lat: Joi.number().required(),
lon: Joi.number().required()
}),
country: Joi.string().required(),
id: Joi.number().required(),
name: Joi.string().required(),
population: Joi.number().required(),
timezone: Joi.number().required()
}).required()
});
});
Frisby还鼓励使用Joi验证框架(它已包含在npm软件包中)。