NestJS单元测试中注入HttpService失败问题排查
Nest测试中HttpService依赖注入失败问题解决
问题场景
我编写了依赖HttpService的SimpleService:
import { Injectable } from '@nestjs/common'; import { HttpService } from '@nestjs/axios'; @Injectable() export class SimpleService { constructor(private readonly httpService: HttpService) {} method() { console.log('Hello World!'); } }
对应的单元测试代码:
import { Test } from '@nestjs/testing'; import { HttpService } from '@nestjs/axios'; import { SimpleService } from './test.service'; describe('test SimpleService', () => { let simpleService: SimpleService; let httpService: HttpService; beforeEach(async () => { const module = await Test.createTestingModule({ providers: [ { provide: HttpService, useValue: { get: jest.fn(), }, }, SimpleService, ], }).compile(); simpleService = module.get<SimpleService>(SimpleService); httpService = module.get<HttpService>(HttpService); }); it('should be defined', () => { expect(httpService).toBeDefined(); expect(simpleService).toBeDefined(); }); });
运行测试时出现错误:
Error: Nest can't resolve dependencies of the SimpleService (?). Please make sure that the argument dependency at index [0] is available in the RootTestModule context.
问题原因
@nestjs/axios中的HttpService并非直接以类作为注入令牌,Nest内部使用了特定的令牌(HTTP_SERVICE常量)来标识这个服务,直接用HttpService类作为provide的值无法被Nest识别,导致依赖解析失败。
解决方法
方法一:使用正确的注入令牌
从@nestjs/axios导入HTTP_SERVICE常量,替换测试模块中的provide值:
import { Test } from '@nestjs/testing'; import { HttpService, HTTP_SERVICE } from '@nestjs/axios'; import { SimpleService } from './test.service'; describe('test SimpleService', () => { let simpleService: SimpleService; let httpService: HttpService; beforeEach(async () => { const module = await Test.createTestingModule({ providers: [ { provide: HTTP_SERVICE, useValue: { get: jest.fn(), }, }, SimpleService, ], }).compile(); simpleService = module.get<SimpleService>(SimpleService); httpService = module.get<HttpService>(HTTP_SERVICE); }); it('should be defined', () => { expect(httpService).toBeDefined(); expect(simpleService).toBeDefined(); }); });
方法二:Mock整个@nestjs/axios模块
通过jest.mock直接模拟整个模块,让Nest能正确识别HttpService类:
jest.mock('@nestjs/axios', () => ({ HttpService: jest.fn(() => ({ get: jest.fn(), })), })); import { Test } from '@nestjs/testing'; import { HttpService } from '@nestjs/axios'; import { SimpleService } from './test.service'; describe('test SimpleService', () => { let simpleService: SimpleService; let httpService: HttpService; beforeEach(async () => { const module = await Test.createTestingModule({ providers: [SimpleService, HttpService], }).compile(); simpleService = module.get<SimpleService>(SimpleService); httpService = module.get<HttpService>(HttpService); }); it('should be defined', () => { expect(httpService).toBeDefined(); expect(simpleService).toBeDefined(); }); });
内容的提问来源于stack exchange,提问作者Jamshoot
相关产品推荐
相关产品推荐

