我有一个用于测试控制器的集成装置。在我的服务中,我将EntityManager
作为依赖项注入,以便可以运行自定义查询。但是,当我在测试中通过EntityManager
作为提供者时,出现以下错误TypeError: Cannot read property 'query' of undefined
。
test.controller.spec.ts
describe('Test Controller', () => {
let module: TestingModule;
let controller: TestController;
let dbConnection: Connection;
beforeAll(async () => {
module = await Test.createTestingModule({
controllers: [TestController],
providers: [TestService, EntityManager],
}).compile();
controller = module.get<TestController>(TestController);
let connectionOptions: any = await getConnectionOptions();
connectionOptions = { ...connectionOptions, name: 'default', database: 'test' };
dbConnection = await createConnection(connectionOptions);
});
afterAll(async () => {
await dbConnection.close();
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
it('should get an array', async () => {
const expectResult: any = [];
const result: any = await controller.findAll();
expect(result).toEqual(expectResult);
});
});
test.controller.ts
@Controller()
export class AlarmCountController {
constructor(private readonly testService: TestService) {}
@Get()
async findAll(): Promise<any> {
return this.testService.getAll();
}
}
test.service.ts
@Injectable()
export class TestService {
constructor(private manager: EntityManager) {}
async getAll(): Promise<any> {
const baseQuery: string `
SELECT *
FROM Test
`;
return await this.manager.query(baseQuery);
}
}