编写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
相关产品推荐
相关产品推荐

