I read through and followed Why does a GraphQL query return null?, but I'm still getting an object of null
fields where I should be getting an array of objects.
This is my resolver. My tests pass if I'm looking up a single _id
. If there is no _id
I want it to return everything. The query and mongoDB are working good. I can console.log
the response
and it's exactly what I'm looking for, but once I return the response
for GraphQL, GraphQL messes it up.
comment: ({_id}: {_id: string}) => {
if (_id) {
return Comment.findOne({_id}).exec();
} else {
return Comment.find({}).exec().then((response) => {
console.log("response inside resolver: ", response); // <-- THIS HAS THE ARRAY OF OBJECTS!
return response;
});
}
}
So when it gets to my test, it returns a data object instead of an array and all the fields are null. Here is my test:
it("should retrieve all records from database", (done) => {
const query: string = `query {
comment { _id author text }
}`;
request(app)
.post("/comments")
.send({query})
.expect(200)
.end((err, res) => {
console.log("response inside test: ", res.body.data.comment); // <-- OBJECT WITH NULL FIELDS!
if (err) { return done(err); }
expect(res.body.data.comment).to.have.lengthOf(arrayOfNewElements.length);
res.body.data.comment.sort((a: IComment, b: IComment) => parseInt(a._id, 10) - parseInt(b._id, 10));
expect(res.body.data.comment).to.deep.equal(arrayOfNewElements);
done();
});
});
The console.log output:
What am I doing to mess GraphQL up between the returned promise in the resolver and my test?
NOTE: This is in TypeScript.
Update: Solved
I put my answer below. I hope it helps somebody.