【问题标题】:Testing a controller API that refirects测试一个重新触发的控制器 API
【发布时间】:2020-06-06 21:32:11
【问题描述】:

我在 Nest.JS 中有一个控制器可以重定向:

    @Get('route/:value')
    async route(@Param('value') value: string) {
      const result = await this.someService.doSomethingWithValue(value);
      if (result) {
        return { url: 'http://example.com/success.html' };
      } else {
        return { url: 'http://example.com/fail.html' };
      }
    } 

如何在 controller.spec.ts 中测试正确的重定向响应? 即:

describe('test', () => {
    it('should show success page', async() => {
      service.doSomethingWithValue = jest.fn(() => Promise.resolve(true));
      expect(controller.route('value')).toBe(?????);
    });
  });

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    它应该完全符合您的预期。您正在返回值,应该是那些值,对吗?实际上是那些对象,所以你应该使用toEqual 而不是toBe。在这种情况下,您将返回true,因此您应该拥有expect(controller.route('value')).toEqual({ url: 'http://example.com/success.html' })。开始尽可能使用返回类型,从长远来看,它会对您有所帮助。

    【讨论】:

    • 经过验证,稍作改动即可工作:const response = await controller.route('value'); expect(response).toEqual({ url: 'http://example.com/success.html'});
    猜你喜欢
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2012-02-15
    • 1970-01-01
    • 2019-04-18
    • 2019-12-12
    相关资源
    最近更新 更多