我的 API 请求有问题。我尝试使用以下方法发送请求
async createRequest(method: string, endpoint: string, parameters?: object, body?: object) {
let request = null;
const browser = await chromium.launch();
const context = await browser.newContext({});
let bodyRequest = JSON.stringify(body);
try {
request = await context.request[method.toLowerCase()](
endpoint,
{
headers:{
'Content-Type': 'application/json',
},
params: this.convertObjectToKeyValue(parameters),
body: bodyRequest });
} catch (error) {
await browser.close();
throw new Error('Invalid request: /' + method + ' ' + endpoint + ' \n error message: ' + error);
}
const responseBody = await request.json();
await browser.close();
return responseBody;
}
我检查了传递的正文是否可见,但是当我仍然收到错误 400 时。我还在服务器日志中看到请求缺少正文。您知道该代码有什么问题吗?
根据剧作家API-测试文档 您应该使用
data
参数而不是 body
。
示例:
test("should create a bug report", async ({ request }) => {
const newIssue = await request.post(`/repos/${USER}/${REPO}/issues`, {
data: {
title: "[Bug] report 1",
},
});
expect(newIssue.ok()).toBeTruthy();
});