我正在用Jest测试rest API。我知道我们使用toEqual
通过递归比较所有属性来检查两个对象是否相等。
对于原始值,toEqual
使用Object.is
进行比较。
我遇到的问题是在测试/register
端点时。用户成功注册后,端点将返回用户详细信息。使用详细信息包含电话,姓名,电子邮件等信息,在这种情况下,更重要的是 user_id 。
现在,我正在尝试的是这样:
const data = {
sponsor_id: 'ROOT_SPONSOR_ID',
phone: '9999999999',
name: 'Joe',
password: 'shhhhh'
};
// Some API call goes here which returns `body`
expect(body).toEqual({
user_id, // <-- How to test value of this?
sponsor_id: data.sponsor_id,
phone: data.phone,
name: data.name
});
我事先不知道user_id
字段的返回值是什么。我所知道的将是一个数字。现在它可以是任何数值,那么在这种情况下如何测试具有任何值或任何数值的对象属性?
我还想检查一下我是否发送了超出预期的任何额外数据(属性)。使用toEqual
可以解决这一问题已经。
如果我的测试方法存在缺陷,请为我提供更好的解释。
答案 0 :(得分:2)
使用expect.any(Number)
确保user_id
是Number
:
test('matches', () => {
const data = {
sponsor_id: 'ROOT_SPONSOR_ID',
phone: '9999999999',
name: 'Joe',
password: 'shhhhh'
};
const user_id = Math.floor(Math.random() * 1000);
const body = Object.assign(data, { user_id });
expect(body).toEqual({
user_id: expect.any(Number), // user_id must be a Number
sponsor_id: data.sponsor_id,
phone: data.phone,
name: data.name,
password: data.password
}); // SUCCESS
});
请注意,如果您想要更具体的匹配器,可以使用expect.extends
create your own。