【问题标题】:How to expect result in test of controller in Nest.js?如何期望在 Nestjs 中测试控制器的结果?
【发布时间】:2021-11-22 00:18:36
【问题描述】:

test.controller.ts

import { Controller, Get, Res } from '@nestjs/common';

@Controller('test')
export class TestController {
  @Get()
  check(@Res() response) {
    response.status(200).send();
  }
}

test.controller.spec.ts

import { Test, TestingModule } from '@nestjs/testing';
import { TestController } from './test.controller';

describe('TestController', () => {
  let controller: TestController;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [TestController],
    }).compile();

    controller = module.get<TestController>(TestController);
  });
  
  describe('check', () => {
    it('should return status 200', async () => {
      const result = 'test'

      expect(await controller.check()).toBe(result);
    });
  )
});

当前代码是这样的。 我想要 200 的状态,但我不知道在这种情况下如何预期结果。

【问题讨论】:

    标签: typescript jestjs nestjs


    【解决方案1】:

    首先,返回响应码“nestJS方式”更容易:

    @Get()
    @HttpCode(200)
    check(@Res() response) {
        // My Result
    }
    

    在测试中你可以链式期望:

    expect(200).expect(...MoreChecks)
    

    或者在 Fastify 中:

    expect(result.statusCode).toEqual(200)
    

    但是与 Fastify 不同的 expressJS 有很多 请参考:https://docs.nestjs.com/fundamentals/testing

    【讨论】:

    • 谢谢!如果我添加@HttpCode(200),我不需要response.status(200).send();
    • @Take 是的,你不需要它
    • 我明白了,谢谢。那么,我还应该写什么?
    • @Take 对不起,你还想要什么?或者你希望做什么?
    • 对不起。我只想重新运行状态 200。那我应该写什么而不是 response.status(200).send();
    猜你喜欢
    • 1970-01-01
    • 2020-01-27
    • 2021-02-03
    • 2021-02-11
    • 2019-05-17
    • 1970-01-01
    • 2016-11-18
    • 2019-12-19
    • 2023-03-15
    相关资源
    最近更新 更多