Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
Method unit testing failing in nestjs

I have below only method in my controller.

@Controller()
export class AppController {
  
  @Get('whoami')
    @Roles(Role.All)
    @ApiResponse({ status: 200, type: User })
    currentUser(@Req() request: Request) {
        return request.user;
    }
}

I am writing below test case for the same.

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

    beforeAll(async () => {
        const app: TestingModule = await Test.createTestingModule({
            controllers: [AppController],
        }).compile();

        controller = app.get<AppController>(AppController);
    });

    it('should be defined', () => {
        expect(controller).toBeDefined();
    });

    it('currentUser should be called', () => {
        expect(controller.currentUser).toBeDefined();
        expect(controller.currentUser).toEqual("shruti");
    });
});

not only this is failing but also return request.user; not getting covered in coverage. below is the error.

enter image description here

what wrong I am doing?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

controller.currentUser is a function. It takes in the Request object and returns request.user. Your test should look something like

    it('currentUser should be called', () => {
        expect(controller.currentUser).toBeDefined();
        expect(controller.currentUser({ user: "shruti" } as any)).toEqual("shruti");
    });

The as any is necessary here because Request has way more properties than just user but all your test and code care about is that user is there to be returned.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!