如何单元测试express-graphql突变?

时间:2017-10-22 09:06:23

标签: graphql jestjs graphql-js express-graphql

我有一个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传递进行单元测试呢?

1 个答案:

答案 0 :(得分:4)

可以使用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);