我正在尝试使用NestJs框架创建一个Jest测试。
该测试应检查控制器和服务,但是1)控制器未定义,2)服务未定义。
这是我的 home-cards.controller.spec.ts 中的代码:
ObjectMapper
错误:
作为控制器询问用户的新错误:
describe('HomeCardsController', () => {
let homeCardsController: HomeCardsController;
let homeCardsService: HomeCardsService;
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [TypeOrmModule.forFeature([HomeCard])],
controllers: [HomeCardsController],
providers: [HomeCardsService]
}).compile();
homeCardsController = module.get<HomeCardsController>(HomeCardsController);
homeCardsService = module.get<HomeCardsService>(HomeCardsService);
});
describe('findall', () => {
it('should return an array of home cards', async () => {
expect( await homeCardsController.findAll(1000)).toBeInstanceOf(Array);
});
});
});
答案 0 :(得分:0)
您必须模拟调用HomeCardsController的HomeCardsService方法
import { HomeCardService } from './home-cards.service.ts'; // your path to service
jest.mock('./home-cards.service.ts'); // your path to service
describe('HomeCardsController', () => {
let homeCardsController: HomeCardsController;
let homeCardsService: HomeCardsService;
beforeEach(async () => {
const module = await Test.createTestingModule({
// imports: [TypeOrmModule.forFeature([HomeCard])], <- unit test don't need database, mock all
controllers: [HomeCardsController],
providers: [HomeCardsService]
}).compile();
homeCardsController = module.get<HomeCardsController>(HomeCardsController);
homeCardsService = module.get<HomeCardsService>(HomeCardsService);
});
describe('findall', () => {
it('should return an array of home cards', async () => {
const result = []; // some result for mock method
jest.spyOn(homeCardsService, 'findAll').mockImplementation(() => result);
const request = {user: {clientId: 1000}}
expect( await homeCardsController.findAll(request)).toBeInstanceOf(Array);
});
});
});
答案 1 :(得分:0)
在这种情况下:
expect( await homeCardsController.findAll(1000)).toBeInstanceOf(Array);
您输入的值是 1000 ,而不是请求@Req,后者应为以下对象:
const request = {
user: {
clientId: 1000
}
}
expect( await homeCardsController.findAll(request)).toBeInstanceOf(Array);
如果您愿意,可以像这样模拟存储库(HomeCardsService下方大括号中的语法):
beforeEach(async () => {
const module = await Test.createTestingModule({
controllers: [HomeCardsController],
providers: [
HomeCardsService,
{
provide: getRepositoryToken(HomeCard),
useValue: jest.fn(() => ({
save: jest.fn().mockReturnThis(),
createQueryBuilder: jest.fn(() => ({
select: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
getOne: jest.fn().mockReturnValueOnce(someMockedValue),
})),
}))(),
},
]
}).compile();