首页 > 解决方案 > 在 Nest JS 中模拟 HTTP 拦截器

问题描述

我有一个在 Nest js 中提供身份验证拦截器的核心模块。这里是核心模块。

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

此 conf 模块由 app 模块导入。

@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 模块记录器而不是测试记录器。显然还有其他用例,但这是我能给出的最好的。

标签: javascriptnode.jstypescriptnestjsnestjs-config

解决方案


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

.overrideInterceptor(LoggerInterceptor).useClass(MockLoggerInterceptor)

推荐阅读