admin管理员组

文章数量:1416631

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 ??? */)
    pile();
    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.

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 ??? */)
    .pile();
    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.

Share Improve this question edited Dec 10, 2021 at 15:44 Mario Petrovic 8,36215 gold badges43 silver badges66 bronze badges asked Oct 30, 2018 at 8:46 jnstjnst 911 silver badge5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

Well assuming you have some kind of a mocked Connection (e.g. use jest.createMockInstance see https://www.npmjs./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)
    .pile();
    app = module.createNestApplication();
    await app.init();
  });
});

本文标签: javascriptHow to overrideProvider for NestJSTypeORMStack Overflow