【发布时间】:2022-08-09 18:58:45
【问题描述】:
我正在为一个名为promotions.controller.ts 的API 的控制器文件执行单元测试脚本。但是,我不确定为什么我的控制器文件没有实例化我在其构造函数中使用 jest 模拟的服务文件并抛出以下错误:
类型错误:无法读取未定义的属性 \'findOne\'。
findOne 是我的promotions.service.ts 中存在的功能之一,它也是从作为该服务的父类的CrudService 扩展而来的。
我已经尝试模拟一个类和 spyOn 来模拟 PromotionService,但它仍然无法正常工作。
这是代码促销.controller.spec.ts:
import { PromotionsService } from \"../promotions.service\";
import {PromotionsController} from \"../promotions.controller\"
import { Test, TestingModule } from \"@nestjs/testing\"
import {OrganizationsService} from \"../../organizations/organizations.service\"
describe(\'PromotionsController\', () => {
let promotionsController: PromotionsController;
let promotionsService: PromotionsService;
jest.mock(\"../promotions.service\");
const mockOrganizationsService = {
}
const mockPromotionsService = {
};
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
controllers: [PromotionsController],
providers:[PromotionsService,OrganizationsService]
}).overrideProvider(PromotionsService).useValue(mockPromotionsService)
.overrideProvider(OrganizationsService).useValue(mockOrganizationsService)
.compile();
promotionsService = moduleRef.get<PromotionsService>(PromotionsService);
promotionsController = moduleRef.get<PromotionsController>(PromotionsController);
const promotions = await promotionsController.performDelete({id:\'1234\'});
});
describe(\'promotionsController\', () => {
it(\'controller should be defined\', async () => {
expect(promotionsController).toBeDefined();
});
it(\'service should be defined\', async () => {
expect(promotionsService).toBeDefined();
});
it(\'promotionsController should be calling performDelete\', async () => {
expect(promotionsController.performDelete({id:\'1234\'})).not.toEqual(null);
expect(promotionsService.find).toHaveBeenCalled();
})
});
});
这是我的代码促销.controller.ts:
import { Controller } from \'@nestjs/common\';
import {ApiBearerAuth} from \"@nestjs/swagger\";
import {Crud} from \"../ms-common/utils/crud/crud.decorator\";
import {Promotion} from \"./promotions.model\";
import {PromotionsDto} from \"./dto/promotions.dto\";
import {CrudController} from \"../ms-common/utils/crud/crud.controller\";
import {PromotionsService} from \"./promotions.service\";
import {OrganizationsService} from \"../organizations/organizations.service\";
@ApiBearerAuth()
@Crud({
model: Promotion,
routes: {
create: {dto: PromotionsDto},
update: {dto: PromotionsDto},
},
})
@Controller(\'promotions\')
export class PromotionsController extends CrudController {
constructor(public model: PromotionsService, private organization: OrganizationsService) {
super(model);
}
async performDelete(id) {
const instance = await this.model.findOne({id});
await this.organization.sbQueue({
type: \"promotion\",
ids: [id],
delete: true,
organization: instance.organization,
});
return super.performDelete(id);
}
}
任何人都知道我应该如何解决这个问题?
-
请修剪您的代码,以便更容易找到您的问题。请按照以下指南创建minimal reproducible example。
标签: typescript unit-testing nestjs