Take
Take

Reputation: 87

How to expect result in test of controller in Nest.js?

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);
    });
  )
});

Current code is like this. I want status of 200 but I don't know how to expect result in this case.

Upvotes: 0

Views: 1678

Answers (1)

Ahmed AlSaeed
Ahmed AlSaeed

Reputation: 138

Firstly, it is easier to return response code "nestJS way":

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

In the testing You can chain expect :

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

Or in Fastify:

expect(result.statusCode).toEqual(200)

But there are alot more expressJS different than Fastify Please Refer To : https://docs.nestjs.com/fundamentals/testing

Upvotes: 1

Related Questions