Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overrideProvider for NestJS/TypeORM

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();
  });
});

Result is

[Nest] 35181   - 10/30/2018, 5:42:06 PM   [ExceptionHandler] 
Connection "default" was not found.
ConnectionNotFoundError: Connection "default" was not found.

In this case, I just want to check request parameters and response values using mock by test. I'd like to disable the DB connection by override it.

like image 999
jnst Avatar asked Oct 30 '18 08:10

jnst


1 Answers

Well assuming you have some kind of a mocked Connection (e.g. use jest.createMockInstance see 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();
  });
});
like image 68
Ralf Waldvogel Avatar answered Sep 30 '22 00:09

Ralf Waldvogel