api.controller.ts
@Controller('api')
export class ApiController {
constructor() {}
@Post()
@Transaction()
async root(@Req() req: Request, @Res() res: Response, @TransactionManager() manager: EntityManager): Promise<void> {
res.send(/* anything */);
}
}
api.e2e-spec.ts
describe('API (e2e)', () => {
let app: INestApplication;
let connection: Connection;
beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [],
controllers: [ApiController],
providers: [],
})
.overrideProvider('Connection')
.useValue(/** How to ??? */)
.compile();
app = module.createNestApplication();
await app.init();
});
});
结果是
[Nest] 35181 - 10/30/2018, 5:42:06 PM [ExceptionHandler]
Connection "default" was not found.
ConnectionNotFoundError: Connection "default" was not found.
在这种情况下,我只想通过测试使用 mock 检查请求参数和响应值。 我想通过覆盖它来禁用数据库连接。
最佳答案
假设你有某种模拟连接(例如使用 jest.createMockInstance 见 https://www.npmjs.com/package/jest-create-mock-instance ):
api.e2e-spec.ts
describe('API (e2e)', () => {
let app: INestApplication;
let connection: Mocked<Connection>;
beforeAll(async () => {
connection = createMockInstance(Connection);
const module = await Test.createTestingModule({
imports: [],
controllers: [ApiController],
providers: [],
})
.overrideProvider(Connection)
.useValue(connection)
.compile();
app = module.createNestApplication();
await app.init();
});
});
关于javascript - 如何为 NestJS/TypeORM 覆盖提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53060407/