我正在测试this使用 postman 的公共(public) API。
当我向此端点发送请求时:
POST: https://reqres.in/api/users
具有以下请求正文:
{
"name": "Rose Thompson",
"job": "Senior Markets Agent"
}
我收到以下回复:
{
"name": "Rose Thompson",
"job": "Senior Markets Agent",
"id": "818",
"createdAt": "2022-05-09T09:30:43.839Z"
}
然后我正在编写一些自定义 API 测试,以确保实际响应和预期响应相同。
这是我在 Postman 中的测试代码:
pm.test("Successful POST request", function () {
pm.expect(pm.response.code).to.be.oneOf([201, 202]);
});
const response = pm.response.json();
pm.test("Should Have Right Name", () => {
const actual = response.name;
const expected = "Rose Thompson";
pm.expect(actual).to.eq(expected);
})
pm.test("Should Have Right Job", () => {
const actual = response.job;
const expected = "Senior Markets Agent";
pm.expect(actual).to.eq(expected);
})
现在我想为 createdAt
编写一个测试来自响应主体的字段。我知道如何从响应本身获取实际值(我会像这样 response.createdAt
),但是,我很难获得 createdAt
的预期值字段。
你能告诉我如何获得 createdAt
的期望值吗?领域?
最佳答案
我会测试该字段是否存在,并且不为空。如果您确实想验证实际的日期/时间,我会尽量避免时间部分,并测试日期。
pm.test("Validate createdAt is present", function () {
const jsonData = pm.response.json();
pm.expect(jsonData.createdAt).not.to.be.null;
});
pm.test("Validate createdAt Date", function () {
const jsonData = pm.response.json();
const createdAt = jsonData.createdAt;
const Today = new Date();
const TodayISO = Today.toISOString().split('T')[0]
// Compare createdAt format for date (substring first 10 characters?)
pm.expect(createdAt.substr(0,10)).to.equal(TodayISO);
});
这里的问题是基于时间的。如果您的测试连续运行,则请求/响应以及运行测试的机器可能会跨越日期边界,因此从技术上讲,请求的日期是测试代码运行时的昨天。
与 Lucas Nguyen 的评论类似,如果可能的话,我会尽量避免测试实际日期,而只需检查提供的字段,并且不为空。
关于postman - 如何在 Postman 中获取回复的日期/时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72170111/