如何测试Nestjs拦截器?

时间:2019-08-30 16:11:33

标签: typescript unit-testing jestjs interceptor nestjs

我找不到有关如何在NestJS中测试拦截器的任何解释

这个简单的示例拦截了POST查询,以向实体中提供的示例模型添加属性。

Products.find({}).then(a => console.log(a.map(p => p.toJSON())))

我想测试拦截函数中发生的事情。

到目前为止:

@Injectable()
export class SubscriberInterceptor implements NestInterceptor {
  async intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Promise<Observable<ExampleModel>> {
    let body: ExampleModel = context.switchToHttp().getRequest().body;
    body = {
      ...body,
      addedAttribute: 'example',
    };
    context.switchToHttp().getRequest().body = body;
    return next.handle();
  }
}

我的问题:我应该只嘲笑const interceptor = new SubscriberInterceptor(); describe('SubscriberInterceptor', () => { it('should be defined', () => { expect(interceptor).toBeDefined(); }); describe('#intercept', () => { it('should add the addedAttribute to the body', async () => { expect(await interceptor.intercept(arg1, arg2)).toBe({ ...bodyMock, addedAttribute: 'example' }); }); }); }); arg1: ExecutionContext吗?如果是这样,如何模拟arg2: CallHandlerarg1?其他我应该如何进行?

1 个答案:

答案 0 :(得分:2)

是的,您应该模拟arg1arg2,然后将它们传递给intercept方法,这是解决方法:

SubscriberInterceptor.ts

interface ExecutionContext {
  switchToHttp(): any;
}
interface CallHandler {
  handle(): any;
}
interface Observable<T> {}
interface ExampleModel {}

interface NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<ExampleModel>>;
}

export class SubscriberInterceptor implements NestInterceptor {
  public async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<ExampleModel>> {
    let body: ExampleModel = context.switchToHttp().getRequest().body;
    body = {
      ...body,
      addedAttribute: 'example'
    };
    context.switchToHttp().getRequest().body = body;
    return next.handle();
  }
}

单元测试,executionContext的模拟链接方法

import { SubscriberInterceptor } from './';

const interceptor = new SubscriberInterceptor();

const executionContext = {
  switchToHttp: jest.fn().mockReturnThis(),
  getRequest: jest.fn().mockReturnThis()
};

const callHandler = {
  handle: jest.fn()
};

describe('SubscriberInterceptor', () => {
  it('should be defined', () => {
    expect(interceptor).toBeDefined();
  });
  describe('#intercept', () => {
    it('t1', async () => {
      (executionContext.switchToHttp().getRequest as jest.Mock<any, any>).mockReturnValueOnce({
        body: { data: 'mocked data' }
      });
      callHandler.handle.mockResolvedValueOnce('next handle');
      const actualValue = await interceptor.intercept(executionContext, callHandler);
      expect(actualValue).toBe('next handle');
      expect(executionContext.switchToHttp().getRequest().body).toEqual({
        data: 'mocked data',
        addedAttribute: 'example'
      });
      expect(callHandler.handle).toBeCalledTimes(1);
    });
  });
});

单元测试结果:

 PASS  src/mock-function/57730120/index.spec.ts
  SubscriberInterceptor
    ✓ should be defined (10ms)
    #intercept
      ✓ t1 (11ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        1.235s, estimated 3s