【问题标题】:Testing GraphQL resolvers with Jest用 Jest 测试 GraphQL 解析器
【发布时间】:2018-11-03 04:59:20
【问题描述】:

我正在寻找使用 Jest 为 GraphQL 解析器编写测试,但我真的不知道从哪里开始。解析器是简单的 CRUD 函数,用于在 NodeJS 上使用 mongoose 写入 MongoDB 数据库。

类型:

type Article {
  _id: ID!
  title: String
  authors: [User]
}

查询

extend type Query {
  articles: [Article]
  article(_id: ID!): Article
}

解析器(只读)

Query: {
  articles: () => new Promise((resolve, reject) => {
    Article.find({}, (err, articles) => {
      if (err) reject(err);
      else resolve(articles);
    });
  }),
  article: (root, {
    _id,
  }) => new Promise((resolve, reject) => {
    Article.findById(_id, (err, article) => {
      if (err) reject(err);
      else resolve(article);
    });
  }),
},

如何在不与数据库交互的情况下进行测试?

【问题讨论】:

标签: node.js mongodb mongoose graphql jestjs


【解决方案1】:

按照这些步骤进行

  • 使用环境变量根据模式(生产、测试​​、开发)更改数据库
  • 导入架构
  • 像这样编写测试并使用 graphql

    const query=`mutation name($id:String!)  //dummy example query
       {
            user(id:$id)
            {
             //fields goes here
              }
       }` 
    const result = await graphql(schema, query, {}, {}, data);
    if (result.data) {
        return result.data.addEventTag
    } else {
        throw new Error(...result.errors.map(err => ` \n${err.message}`));
    }  
    

所以不需要直接导入resolver,graphQl会用到,一定要按照模式连接数据库。

【讨论】:

    猜你喜欢
    • 2017-02-24
    • 2018-03-14
    • 1970-01-01
    • 2019-02-22
    • 2020-09-25
    • 1970-01-01
    • 2017-07-22
    • 2018-09-30
    • 1970-01-01
    相关资源
    最近更新 更多