gpt4 book ai didi

node.js - 如何在Service构造函数中对Controller和模拟@InjectModel进行单元测试

转载 作者:行者123 更新时间:2023-12-01 08:46:12 26 4
gpt4 key购买 nike

我在对 Controller 进行单元测试时遇到问题,并收到错误消息“嵌套无法解决我的服务依赖性”。
为了获得最大的覆盖范围,我想对 Controller 和相应的服务进行单元测试,并希望模拟像 Mongoose 连接之类的外部依赖项。同样,我已经尝试了以下链接中提到的建议,但没有发现任何运气:
https://github.com/nestjs/nest/issues/194#issuecomment-342219043
请在下面找到我的代码:

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);
});
});
});
当我在上面运行测试用例时,出现两个错误:

Nest can't resolve dependencies of the DeviceService (?). Please make sure that the argument at index [0] is available in the current context.

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);
});

// ...


});

关于node.js - 如何在Service构造函数中对Controller和模拟@InjectModel进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52878055/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com