How to equal / validate return statusCode jest testing in nest js

Issue

I am writing a test case for my delete controller method and this is my remove controller method.

@Delete(':ccAdminId')
  @HttpCode(200)
  async removeCcAdmin(@Param('ccAdminId') ccAdminId: string) {
    await this.ccAdminService.remove(ccAdminId);
  }
}

In this method, nothing returns except statusCode. So I just need to write a test cast to verify this statusCode. This is my test case.

describe('CcAdminController Unit Tests', () => {
  let ccAdminController: CcAdminController;
  let spyService: CcAdminService;

  beforeAll(async () => {
    const ApiServiceProvider = {
      provide: CcAdminService,
      useFactory: () => ({
        remove: jest.fn().mockImplementation((ccAdminId: string) => Promise.resolve(ccAdminId)),
      }),
    };
    const app: TestingModule = await Test.createTestingModule({
      controllers: [CcAdminController],
      providers: [CcAdminService, ApiServiceProvider],
    }).compile();

    ccAdminController = app.get<CcAdminController>(CcAdminController);
    spyService = app.get<CcAdminService>(CcAdminService);
  });

  it('calling removeCcAdmin method', async () => {
    const ccAdminId = '0001';
    await ccAdminController.removeCcAdmin(ccAdminId).then((result) => {
      expect(result).toEqual(HttpCode(200));
    });
    expect(spyService.remove).toHaveBeenCalled();
  });
});

But my test case is not working.

Solution

In a unit test, there’s no response being sent, just the value returned by the controller’s method. To validate a status code you’d need an integration test and to actually run the request over an HTTP requester like pactum, supertest, axios, or any other http client.

Answered By – Jay McDoniel

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published