如何覆盖 NestJS/TypeORM 的Provider
Posted
技术标签:
【中文标题】如何覆盖 NestJS/TypeORM 的Provider【英文标题】:How to overrideProvider for NestJS/TypeORM 【发布时间】:2019-04-03 06:21:24 【问题描述】: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 by test 来检查请求参数和响应值。 我想通过覆盖来禁用数据库连接。
【问题讨论】:
【参考方案1】:假设您有某种模拟连接(例如,使用 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();
);
);
【讨论】:
以上是关于如何覆盖 NestJS/TypeORM 的Provider的主要内容,如果未能解决你的问题,请参考以下文章
如何创建如何在 typeorm 中创建多对多关系,[NestJS]
TypeError:存储库方法不是函数(NestJS / TypeORM)