Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/422.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用Jest测试API端点及其响应_Javascript_Json_Jestjs_Fetch - Fatal编程技术网

Javascript 使用Jest测试API端点及其响应

Javascript 使用Jest测试API端点及其响应,javascript,json,jestjs,fetch,Javascript,Json,Jestjs,Fetch,我想使用jest测试API端点,以检查它是否返回响应,以及JSON是否包含我需要的参数键 我的函数如下所示: export function getFiveDayWeatherByCoordinates(id) { let url = FORECAST_ID_URL(id); return fetch(url) .then(response => response.json()) .then(data => { return data;

我想使用jest测试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。

我建议使用来测试API响应。这是一个很好的API测试框架,可以开玩笑地运行。我已经多次使用它来编写API和后端集成测试。尽管如此,我通常将这些测试套件与UI单元测试分开

下面是一个例子:

it('should return weather coords',async()=>{
返回飞盘
.get(`${global.apirl}/my weather endpoint`)
.expect('status',200)
.expect('jsonTypes',Joi.object({
cnt:Joi.number().required(),
cod:Joi.string().required(),
城市:Joi.object({
坐标:Joi.object({
lat:Joi.number().required(),
lon:Joi.number().required()
}),
国家/地区:Joi.string().required(),
id:Joi.number().required(),
名称:Joi.string().required(),
填充:Joi.number().required(),
时区:Joi.number().required()
}).required()
});
});

Frisby还鼓励使用验证框架(它已经包含在npm包中).

你想在服务器端本身测试api吗?它是express吗?我想测试openweathermap api,这不是我的问题。你想测试什么以及为什么要测试?你也不能测试响应,你可以验证。是的,我想验证响应。我想测试api响应,看看它是否不会破坏我的应用程序。因为任何响应nge会破坏应用程序。你可以使用Jest来测试你的react应用程序。谢谢你的建议,我会看看Frisby.js,它看起来做了我需要的事情。你不能为你的应用程序没有包含的东西编写单元测试。@AZ_z-它不是单元测试。它更像是一个集成测试。你当然可以编写一个测试,对resp进行断言使用API,即使API不是您的。很高兴@DiogoPeres成功。祝您的项目好运。