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

编写GraphQL路由测试遇类型错误:DocumentNode无法赋值

解决GraphQL测试中的DocumentNode类型不兼容错误

问题详情

为GraphQL路由编写测试时遇到类型错误,路由在GraphQL Playground中运行正常,但测试时报错:

Type 'DocumentNode' is not assignable to type 'string | DocumentNode | undefined'.

测试代码示例(还原截图内容):

import request from 'supertest';
import { gql } from 'apollo-server-express';
import app from '../app';

// 定义GraphQL查询
const GET_USERS = gql`
  query GetUsers {
    users {
      id
      name
    }
  }
`;

describe('GraphQL路由测试', () => {
  it('应成功获取用户列表', async () => {
    const response = await request(app)
      .post('/graphql')
      .send({ query: GET_USERS }); // 此处触发类型错误

    expect(response.status).toBe(200);
    expect(response.body.data.users).toBeDefined();
  });
});

错误信息详情(还原截图内容):

Type 'DocumentNode' is not assignable to type 'string | DocumentNode | undefined'.
Type 'import("/node_modules/@apollo/client/node_modules/graphql/language/ast").DocumentNode' is not assignable to type 'import("/node_modules/graphql/language/ast").DocumentNode'.
Types have separate declarations of a private property 'loc'.

解决方案

1. 统一GraphQL包版本

错误核心原因是项目中存在多个版本的graphql依赖,导致DocumentNode类型来自不同模块,出现类型不兼容。

  • 执行依赖去重命令:
    # npm 用户
    npm dedupe graphql
    
    # yarn 用户
    yarn dedupe graphql
    
  • 如果去重无效,在package.json中强制指定统一版本:
    "resolutions": {
      "graphql": "^16.8.0" // 替换为你项目实际使用的graphql版本
    }
    
    之后重新安装依赖:npm install 或 yarn install

2. 统一gql与类型的导入来源

确保gql函数和DocumentNode类型都来自同一个GraphQL相关包,避免跨包类型冲突:

  • 例如统一从apollo-server-express导入:
    import { gql, DocumentNode } from 'apollo-server-express';
    
  • 或者使用graphql-tag和官方graphql包:
    import gql from 'graphql-tag';
    import { DocumentNode } from 'graphql';
    

3. 临时类型断言(不推荐长期使用)

如果以上方法都无法快速解决,可以临时用类型断言跳过检查:

.send({ query: GET_USERS as unknown as string | DocumentNode });

内容的提问来源于stack exchange,提问作者Brace Sproul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:51:45