Пересмешные HTTP перехватчики в Nest JS - PullRequest
1 голос
/ 12 февраля 2020

У меня есть основной модуль, который обеспечивает перехватчик аутентификации в Nest js. Вот основной модуль.

@Module({
    imports: [
    providers: [{
        provide: APP_INTERCEPTOR,
        useClass: LoggerInterceptor
    }
  ]
})
export class ConfModule {
}

Этот модуль conf был импортирован модулем приложения.

@Module({
    imports: [
        ConfModule
    ]
})
export class AppModule {
}

Вот мой LoggerInterceptor класс

@Injectable()
export class LoggerInterceptor implements NestInterceptor {
    constructor(private readonly reflector: Reflector, private readonly connection: Connection) {
    }

    async intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        // tslint:disable-next-line:no-console
        console.log(context.switchToHttp().getRequest().body);
        await this.connection.createEntityManager().save(context.switchToHttp().getRequest().body);
        return next.handle();
    }
}

Я сейчас пишу тест E2E и хочу переопределить перехватчик регистратора. Вот мой MockLoggerInterceptor

export class MockLoggerInterceptor extends LoggerInterceptor {
    reflex: Reflector;
    conn: Connection;

    constructor(reflector: Reflector, connection: Connection) {
        super(reflector, connection);
        this.reflex = reflector;
        this.conn = connection;
    }

    // @ts-ignore
    async intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        // tslint:disable-next-line:no-console
        console.log(context.switchToHttp().getRequest().body);
        await this.conn.createEntityManager().save(context.switchToHttp().getRequest().body);
        return next.handle();
    }

}

Вот мой набор тестов

describe('PermissionController', () => {
    let applicationContext: INestApplication;
    let connection: Connection;
    let testUtils: TestUtils;
    let appHeader: App;

    beforeAll(async () => {
        const moduleRef: TestingModule = await Test.createTestingModule({
            imports: [AppModule]
        }).overrideInterceptor(LoggerInterceptor).useClass(MockLoggerInterceptor).compile();

        applicationContext = moduleRef.createNestApplication();
        connection = getConnection();
        await applicationContext.init();
        testUtils = new TestUtils(connection);
        appHeader = await testUtils.getAuthorisedApp();

    });
    it('Test of permission can be created', async () => {
        await request(applicationContext.getHttpServer())
            .post('/permissions')
            .set({
                'X-APP-CODE': appHeader.code,
                'X-APP-TOKEN': appHeader.token,
                'Authorisation': appHeader.token
            })
            .send(
                {
                    permissionName: 'newPermission'

                }
            ).expect(201);
    });

    afterAll(async () => {
        await connection.close();
        await applicationContext.close();

    });
});

Мой тест все еще использует регистратор модуля conf вместо регистратора тестов. Очевидно, есть и другие варианты использования, но это лучшее, что я могу дать.

1 Ответ

1 голос
/ 12 февраля 2020

Вы должны использовать overrideInterceptor вместо overrideProvider, так как перехватчик не предусмотрен в массиве поставщиков модуля:

.overrideInterceptor(LoggerInterceptor).useClass(MockLoggerInterceptor)
...