javascript - 如何使用 jest 动态匹配对象值

标签 javascript testing jestjs

我正在测试一个 API,它将返回客户数据对象(ID、姓名、年龄等)。

这些对象将具有一些共享数据,具体取决于我的查询参数(例如位置等),其余数据是动态的。如何才能最好地测试返回的数据是否是我想要的?

示例数据 - 假设我搜索了特定城镇的所有客户:

{
  "location": "some town",
  "data": [
    { "id": "123", "name": "Bob" },
    { "id": "234", "name": "Jane" }
  ]
}

当然,对于我输入的每个不同的查询参数城镇,data 数组中会有不同的数据且长度不同。

我正在使用 Jest,想知道最好的测试方法是什么?

到目前为止,我有以下内容:

test('customer data location', async () => {
  const expect = require('./customer-obj.json');
  const response = await getcustomersin('some town');

  expect(response.body).toMatchObject(expected);
  expect(response.body.data).toHaveLength(2);
});

其中 customer-obj.json 是 JSON 文件:

{
  "location": "some town",
}

我使用了 toMatchObject 来实现这一点,但我觉得我错过了不包含 data 值的要点...

我确实在官方文档中看到了 expect.arrayContaining(array) ,但我不知道要包含在其中的数据,因为它似乎只有在您提供的子集时才有效整体数据数组。

最佳答案

您可以忘记期待确切的值,而只需检查基础对象是否包含一组属性,如下所示:

test('Contains object with location and data properties', async () => {
  const expect = require('./customer-obj.json');
  const response = await getcustomersin('some town');

  expect(typeof response.body).toBe('object');
  expect(response.body.hasOwnProperty('location')).toBe(true);
  expect(response.body.hasOwnProperty('data')).toBe(true);
});

关于javascript - 如何使用 jest 动态匹配对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57389051/

相关文章:

javascript - ajaxStart 不适用于 onclick

Android -- OpenGL 不显示 w/模拟器?

node.js - 使用 Jest 测试 Express 时,有办法修复此 "TypeError: express.json is not a function"吗?

vue.js - Jest 找不到模块 Vue/Vite

php - 弹出窗口不起作用

javascript - 如何通过 webpack 将版本哈希附加到样式文件?

javascript - 当我单击两个单选按钮之一时,如何附加文本字段并将文本字段替换为另一个?

Java Mockito 无法模拟方法的结果

selenium - 有没有办法在 Selenium Webdriver 或 Katalon Studio 中测试 Web 表的排序功能?

javascript - react-scripts 测试引发与被测组件无关的 TypeError