When using @types/k6
, one of the types http.post()
accepts as a body is StructuredRequestBody
. This type is currently defined the following way:
export interface StructuredRequestBody {
[name: string]: string | FileData;
}
It seems that number
and boolean
return values are not allowed when using the index signature. However when I run the following code:
const body = {
test: 1
};
const loginResponse = http.post('http://localhost', body as any);
console.log(loginResponse.request.body);
I get test=1
as output from the console.log
. The current type definition requires me to toString()
the number value for seemingly no reason other than semantics.
Is there any reason why the type definition for StructuredRequestBody
is defined this way, when it seems that k6
can serialize numbers just fine? Having to toString()
all my data is quite cumbersome.
Hey @octagon,
welcome to the community forum
as you can read from the Response’s doc, Response.request.body
is not the same type as the Request.body. Response.request.body
is a string and it contains the encoded body of the request so if you pass an object to http.post
it will be the www-form-urlencoded
version.
As the example in the doc mentions:
// Using an object as body, the headers will automatically include
// 'Content-Type: application/x-www-form-urlencoded'.
res = http.post(url, data);
console.log(res.json().form.name); // Bert
However, it isn’t clear to me where you’re using toString
. Can you post an example of how you’re using it and what is the unexpected returned value, please?
Hey @codebien
What I’ve written about Response.request.body
was just to demonstrate that k6 seems to handle types other than string
just fine when posting content as x-www-form-urlencoded
. It is not of much significance to my problem.
My current gripe is that the following code is invalid:
const body = {
foo: 1
}
http.post(url, body); // TypeError, since foo is an invalid type (expected string | FileData)
while the following example works:
const body = {
foo: '1'
}
http.post(url, body); // No type errors
Both produce the same result when I ignore the TS type error and read the content from Response.request.body
, that’s why I was wondering why the StructuredRequestBody
type is defined the way it is. Right now I will have to convert foo
to a string before I can pass it to http.post(...)
.