【发布时间】:2020-04-06 18:46:04
【问题描述】:
我主要关注关于 how to create a mutation 的 GraphQL 文档。这是我使用 GraphQL 的第一天。我想为 cmets 创建一个端点。
隔离问题
我在 Mocha 中从我的 supertest 返回 400 "Bad Request",当我尝试运行 GraphiQL 时,它在错误数组中给我一条消息,上面写着“查询根必须提供类型。” ...但我我包括rootValue。
问题可能出在buildSchema。
// imports (...working fine)
// Comment Interface for TypeScript is here ...and working
// ...
// gaphql schema (The problem could be here.)
const schema = buildSchema(`
input CommentInput {
_id: String
author: String
text: String
}
type Comment {
_id: String
author: String
text: String
}
type Mutation {
createOrUpdateComment(input: CommentInput): Comment
}
`);
// rootValue
const root = {
createOrUpdateComment: ({input}: { input: IComment }) => {
return {
_id: "id here",
author: input.author,
text: input.text
}
}
};
export default graphqlHTTP({
graphiql: true,
rootValue: root,
schema
});
这被导入,然后在快递服务器的顶层使用,就像comments这样:
app.use("/comments", comments);
工作原理:GraphiQL 确实会在浏览器中的localhost:8080/comments 处弹出,所以我很确定在 Express 方面没有问题。 (顺便说一句,TypeScript 编译得很好。)我还有一个不同的 GraphQL api 端点,它返回“Hello world!”在我使用 Mocha 测试的服务器的顶层并且它通过了(在它最初失败之后),所以我的测试套件似乎运行良好。没有额外的环境变量。这就是你在这里看到的。
我想通过的测试,给我 404 错误请求是:
// imports (...working fine)
describe("graphQl comments test", () => {
it("should add a comment", (done) => {
const query = `mutation createOrUpdateComment($input: CommentInput) {
_id
author
text
}`;
const variables = {
input: {
author: "Brian",
text: "This is my favorite video of all time."
}
};
request(app)
.post("/comments")
.send(JSON.stringify({ query, variables})) // (The problem could be here.)
.expect(200)
.end((err, res) => {
if (err) { return done(err); }
// tslint:disable-next-line: no-unused-expression
expect(res.body.data.id).to.exist;
expect(res.body.data.author).to.equal("Brian");
expect(res.body.data.text).to.equal("This is my favorite video of all time.");
done();
});
});
});
既然它说的是“bad request”,那么我在测试中处理query 和variables 的方式肯定是问题所在。
问题
我的问题是测试中的查询和变量还是我的buildSchema? ...或者两者兼而有之?我将如何以不同的方式编写以使测试通过?
更新
在我将导出中的 rootValue 注释掉之后,就像这样,因为它在 GraphiQL 中说“必须提供查询根类型”,所以我发现没有区别。好像rootValue 不存在,即使它存在。
export default graphqlHTTP({
graphiql: true,
// rootValue: root,
schema
});
一旦我根据this Github issue 中提到的内容添加了Query 和getComment(),GraphiQL 中的错误消息就消失了。不幸的是,测试仍然给出 400 Bad Request,所以这些问题似乎无关。
更新 2
我使用 GraphiQL 测试了我的端点,当我发布时它按预期/期望运行:
mutation {
createOrUpdateComment(input: {_id: "4", author: "Some Author", text: "some unique text"}) {
_id
author
text
}
}
我正在努力使我的测试查询类似,但它们不是类似物。这清楚地表明问题出在测试本身,当我记录正文的响应时,我得到了这个:
所以我的测试查询字符串有问题。
已解决。
请看下面我的回答。
【问题讨论】:
标签: javascript node.js graphql mocha.js supertest