我有一个核心模块,可在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模块记录器,而不是测试记录器。显然还有其他用例,但这是我能提供的最好的用例。
答案 0 :(得分:1)
您必须使用overrideInterceptor
而不是overrideProvider
,因为模块的provider数组中没有提供拦截器:
.overrideInterceptor(LoggerInterceptor).useClass(MockLoggerInterceptor)