我有一个带有查询和变异的快速GraphQL API,它在GraphiQL中工作,查询的单元测试工作,但变异的单元测试返回405个错误。
我的GraphQL模式如下:
type Subject {
type: String
}
type Category {
name: String
}
type SubjectCategories {
subject: Subject
categories: [Category]
}
type Query {
subjectCategories(subjectType: String!): SubjectCategories
}
type Mutation {
addSubjectCategory(subjectType: String! categoryName: String!): SubjectCategories
}
为了简化这个问题,这些方法的实现只是回应:
echoGetSubjectCategory({subjectType}, context) {
const subject = new Subject(subjectType);
const category = new Category("blah");
const retval = {
subject,
categories: [category],
};
return retval;
}
echoMutateSubjectCategory({subjectType, categoryName}, context) {
const subject = new Subject(subjectType);
const category = new Category(categoryName);
const retval = {
subject,
categories: [category],
};
return retval;
}
通过Graphiql,一切正常:
mutation {
addSubjectCategory(subjectType: "s1" categoryName: "c1"){
subject {
type
}
categories {
name
}
}
}
产量
{
"data": {
"addSubjectCategory": {
"subject": {
"type": "s1"
},
"categories": [
{
"name": "c1"
}
]
}
}
}
和
{
subjectCategories(subjectType: "s1"){
subject {
type
}
categories {
name
}
}
}
结果相同。
查询返回200
const req = request(app)
.get('/graphql')
.set('Content-Type', 'application/json')
.set('Accept', 'application/json')
.send(JSON.stringify({
query: "query {subjectCategories(subjectType: \"categorized\" ) { subject {type } categories {name} } }",
}));
const res = await req;
expect(res.statusCode).toBe(200);
但是这次测试
失败
:
const req = request(app)
.get('/graphql')
.set('Content-Type', 'application/json')
.set('Accept', 'application/json')
.send(JSON.stringify({
query: "mutation {addSubjectCategory(subjectType: \"categorized\" categoryName: \"Politics\" ) { subject {type } categories {name} } }",
}));
const res = await req;
expect(res.statusCode).toBe(200);
突变返回405
错误消息非常不透明:
Expected value to be (using ===):
200
Received:
405
at Object.<anonymous> (test/api.test.js:171:28)
at Generator.next (<anonymous>)
at step (test/api.test.js:7:368)
at test/api.test.js:7:528
at <anonymous>
那么,我如何形成这个json负载来通过express graphql的单元测试呢?