NestJS GraphQL登录接口E2E测试报错:@grpc/proto-loader缺失
解决NestJS E2E测试中@grpc/proto-loader缺失报错问题
问题描述
在为GraphQL登录服务编写E2E测试时,使用NestJS测试模块与Supertest工具,运行login.spec.ts时出现@grpc/proto-loader包缺失的错误,即使已经安装该包,问题仍未解决。
测试代码
import { Test, TestingModule } from '@nestjs/testing'; import * as request from 'supertest'; import AppModule from './app.module'; import { INestApplication } from '@nestjs/common'; const gql = '/graphql'; describe('GraphQL AppResolver (e2e) {Supertest}', () => { let app: INestApplication; beforeAll(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule.forRoot({})], }).compile(); app = moduleFixture.createNestApplication(); await app.init(); }); afterAll(async () => { await app.close(); }); describe(gql, () => { describe('login', () => { it('should login', () => { return request(app.getHttpServer()) .post(gql) .send({ operationName: "Login", query: `mutation Login($data: SigninInput!){ login(dto:$data){ user_type access_token refresh_token exp roles code messages } }`, variables: { "data": { "email": "eh@gmail.com", "password": "12345678" } }, }) .expect(200) .expect((res) => { console.log(res.body.data.login) }); }); }); }); });
报错信息
[Nest] 15826 - 07/31/2023, 6:26:04 PM ERROR [PackageLoader] The "@grpc/proto-loader" package is missing. Please, make sure to install this library ($ npm install @grpc/proto-loader) to take advantage of ClientGrpcProxy. ● process.exit called with "1" 11 | beforeAll(async () => { > 12 | const moduleFixture: TestingModule = await Test.createTestingModule({ | ^ 13 | imports: [AppModule.forRoot({})], 14 | }).compile(); 15 |
解决方案
以下是几种可行的解决方法:
1. 重新安装依赖并清除缓存
依赖安装可能存在缓存或不完整的情况,执行以下步骤重装:
# 卸载包 npm uninstall @grpc/proto-loader # 清除npm缓存 npm cache clean --force # 重新安装(添加--save-dev将其放入开发依赖) npm install @grpc/proto-loader --save-dev
如果使用Yarn,对应命令:
yarn remove @grpc/proto-loader yarn cache clean yarn add @grpc/proto-loader --dev
安装完成后检查package.json,确保@grpc/proto-loader出现在devDependencies或dependencies中。
2. Mock或替换测试中的gRPC依赖
报错提示ClientGrpcProxy需要该包,说明你的AppModule或其导入的模块中包含gRPC客户端。如果E2E测试不需要实际调用gRPC服务,可以通过NestJS测试模块的overrideProvider来mock相关依赖:
beforeAll(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule.forRoot({})], }) // 替换gRPC客户端服务为mock实现 .overrideProvider(GrpcClientService) .useValue({ // 根据实际需求mock必要的方法,例如: someGrpcMethod: jest.fn().mockResolvedValue({}) }) .compile(); app = moduleFixture.createNestApplication(); await app.init(); });
如果是整个模块依赖gRPC,也可以创建一个空的mock模块替代原模块导入。
3. 检查Node版本兼容性
@grpc/proto-loader对Node版本有要求,确保你的Node版本符合包的兼容要求(通常需要Node 14及以上)。可以通过node -v查看当前版本,若版本过低,升级Node后重新安装所有依赖。
4. 彻底清理依赖并重装
如果以上方法无效,尝试清理整个node_modules和锁文件后重新安装所有依赖:
rm -rf node_modules package-lock.json npm install
内容的提问来源于stack exchange,提问作者Ehsan Sepehri
相关产品推荐
相关产品推荐

