简体   繁体   English

在 Nest JS 中模拟 HTTP 拦截器

[英]Mocking HTTP interceptors in Nest JS

I have a core module that provides an authentication interceptor in Nest js.我有一个在 Nest js 中提供身份验证拦截器的核心模块。 Here is the core module.这里是核心模块。

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

This conf module is been imported by the app module.这个 conf 模块是由 app 模块导入的。

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

Here is my LoggerInterceptor class这是我的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();
    }
}

I am currently writing an E2E test and will want to override the logger interceptor.我目前正在编写一个 E2E 测试,并希望覆盖记录器拦截器。 Here is my MockLoggerInterceptor这是我的 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();
    }

}

Here is my test Suite这是我的测试套件

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

    });
});

My test still uses the conf module logger instead of the test logger.我的测试仍然使用 conf 模块记录器而不是测试记录器。 Apparently there are other use cases but this is the best I can give.显然还有其他用例,但这是我能给出的最好的。

您必须使用overrideInterceptor而不是overrideProvider ,因为模块的 providers 数组中没有提供拦截器:

.overrideInterceptor(LoggerInterceptor).useClass(MockLoggerInterceptor)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM