问题描述
我在对控制器进行单元测试时遇到问题,并收到错误Nest 无法解决我的服务的依赖关系".
I am getting issues while unit testing my controller and getting an error "Nest can't resolve dependencies of my service".
为了获得最大的覆盖范围,我想对控制器和相应的服务进行单元测试,并想模拟像猫鼬连接这样的外部依赖项.同样,我已经尝试了以下链接中提到的建议,但没有找到任何运气:
For maximum coverage I wanted to unit test controller and respective services and would like to mock external dependencies like mongoose connection. For the same I already tried suggestions mentioned in the below link but didn't find any luck with that:
https://github.com/nestjs/nest/issues/194#issuecomment-342219043
请在下面找到我的代码:
Please find my code below:
export const deviceProviders = [
{
provide: 'devices',
useFactory: (connection: Connection) => connection.model('devices', DeviceSchema),
inject: ['DbConnectionToken'],
},
];
export class DeviceService extends BaseService {
constructor(@InjectModel('devices') private readonly _deviceModel: Model<Device>) {
super();
}
async getDevices(group): Promise<any> {
try {
return await this._deviceModel.find({ Group: group }).exec();
} catch (error) {
return Promise.reject(error);
}
}
}
@Controller()
export class DeviceController {
constructor(private readonly deviceService: DeviceService) {
}
@Get(':group')
async getDevices(@Res() response, @Param('group') group): Promise<any> {
try {
const result = await this.deviceService.getDevices(group);
return response.send(result);
}
catch (err) {
return response.status(422).send(err);
}
}
}
@Module({
imports: [MongooseModule.forFeature([{ name: 'devices', schema: DeviceSchema }])],
controllers: [DeviceController],
components: [DeviceService, ...deviceProviders],
})
export class DeviceModule { }
单元测试:
describe('DeviceController', () => {
let deviceController: DeviceController;
let deviceService: DeviceService;
const response = {
send: (body?: any) => { },
status: (code: number) => response,
};
beforeEach(async () => {
const module = await Test.createTestingModule({
controllers: [DeviceController],
components: [DeviceService, ...deviceProviders],
}).compile();
deviceService = module.get<DeviceService>(DeviceService);
deviceController = module.get<DeviceController>(DeviceController);
});
describe('getDevices()', () => {
it('should return an array of devices', async () => {
const result = [{
Group: 'group_abc',
DeviceId: 'device_abc',
},
{
Group: 'group_xyz',
DeviceId: 'device_xyz',
}];
jest.spyOn(deviceService, 'getDevices').mockImplementation(() => result);
expect(await deviceController.getDevices(response, null)).toBe(result);
});
});
});
当我运行上面的测试用例时,我收到两个错误:
When I am running my test case above, I am getting two errors:
Nest 无法解析 DeviceService (?) 的依赖关系.请确保索引 [0] 处的参数在当前上下文中可用.
无法窥探原始值;未定义给定
Cannot spyOn on a primitive value; undefined given
推荐答案
示例代码:
import { Test } from '@nestjs/testing';
import { getModelToken } from '@nestjs/mongoose';
describe('auth', () => {
let deviceController: DeviceController;
let deviceService: DeviceService;
const mockRepository = {
find() {
return {};
}
};
beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [DeviceModule]
})
.overrideProvider(getModelToken('Auth'))
.useValue(mockRepository)
.compile();
deviceService = module.get<DeviceService>(DeviceService);
});
// ...
});
这篇关于如何在 Service 构造函数中对 Controller 进行单元测试并模拟 @InjectModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!