6

我有一个带有查询和突变的 Express-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
    }
  }
}

产生相同的结果。

在我的 API 单元测试中(使用来自 'supertest-as-promised' 的请求),查询返回 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 的这个单元测试通过?

4

1 回答 1

10

可以同时使用GETPOST请求进行查询,而只能使用请求进行突变POST

像这样修改您的代码,它应该可以工作:

const req = request(app)
  .post('/graphql')
  .set('Content-Type', 'application/json')
  .set('Accept', 'application/json')
  .send({
    query: "mutation {addSubjectCategory(subjectType: \"categorized\" categoryName: \"Politics\" ) { subject {type } categories {name} } }"
  });
const res = await req;
expect(res.statusCode).toBe(200);
于 2017-10-22T12:27:56.470 回答