You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用graphql-tools的mockServer模拟Mutation?查询字段报错

解决graphql-tools mockServer模拟Mutation时的"Cannot query field 'Mutation' on type..."错误

我一眼就看出问题所在啦——你把GraphQL的Mutation请求格式写错了!GraphQL里Query和Mutation是两个独立的根操作类型,不能把Mutation当作Query的字段来查询。

先看你出错的代码:

it('should update user name correctly', () => { 
  mockserver 
    .query( 
      `{ Mutation { updateUserName(id: 1, name: "du") { id name } } }` 
    ) 
    .then(res => { 
      console.log(res); 
      expect(1).to.be.equal(1); 
    }); 
});

问题根源

GraphQL的Mutation请求需要用mutation关键字作为开头,而不是嵌套在Query的大括号里。你现在的写法相当于在查询根Query类型下的Mutation字段,而你的Schema里肯定没有定义这个字段,所以才会抛出"Cannot query field 'Mutation' on type..."的错误。

修正后的代码

把请求字符串改成标准的Mutation格式,同时注意mockServer的query方法其实也支持Mutation请求(只要格式正确):

it('should update user name correctly', () => { 
  mockserver 
    .query( 
      `mutation { 
        updateUserName(id: 1, name: "du") { 
          id 
          name 
        } 
      }` 
    ) 
    .then(res => { 
      console.log(res); 
      // 这里可以改成实际的断言,比如检查返回的name是否符合预期
      expect(res.data.updateUserName.name).to.be.equal("du"); 
    }); 
});

额外提示

如果你的mockServer配置了自定义的resolver来处理updateUserName,这个修正后的请求就能正确触发对应的Mutation逻辑;如果是默认的mock resolver,它也会返回符合你Schema定义的模拟数据,帮你完成单元测试。

内容的提问来源于stack exchange,提问作者Lin Du

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:20:49