JavaScript gurus, what am I missing here?
Simple test scenario as follows:
import * as request from "request-promise-native";
export class Publisher {
name : string = "IRocking Publisher";
async publishAsync(): Promise<PublisherResponse> {
var publisherResponse : PublisherResponse = PublisherResponse.EmptyResponse;
try {
let response = await request.get("https://jsonplaceholder.typicode.com/todos/1");
console.debug("Promise has been resolved. Result is:")
console.debug(response)
console.debug(response.userId)
publisherResponse = new PublisherResponse(file, this.name, true, "");
}
catch (error) {
publisherResponse = new PublisherResponse(file, this.name, false, error);
}
return Promise.resolve<PublisherResponse>(publisherResponse);
}
}
With accompanying Jest test as follows:
test('Should publish a valid single document asynchronously', async () => {
// Arrange
let sut = new Publisher();
let expectedResponse = new PublisherResponse(documentToPublish, sut.name, true, "");
// Act
let actualResponse = await sut.publishAsync(new PublicationContext(), documentToPublish);
// Assert
expect(actualResponse).toEqual(expectedResponse);
});
When I run the test, I see the data being returned from the service as
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
But if I attempt to access a property of the data such as "userId" I get undefined. What am I missing?
Also, how do I get other status codes besides a 200 from this request?
I needed to deserialize the JSON string returned from the service using
var todo = JSON.parse(response);
For some reason, I was assuming that the response to
let response = await request.get("https://jsonplaceholder.typicode.com/todos/1");
was an object but the underlying type is a string . I found this out with the following code:
let propertyNames = Object.keys(response);
console.debug(propertyNames);
propertyNames.forEach((p, i) => {
console.debug(response[p])
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.