question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Cannot write or execute Unit test case for Controller. Need Help Quick [HIGH PRIORITY]

See original GitHub issue

I’m submitting a…


[ ] Regression 
[ ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[x] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

I am trying to build and run unit test cases. Inside documentation there is limited help. I am going to use NESTJS in my production app for next release before I do I am writing unit test cases for my code before my next revision. My api is functional and throughly tested using postman and also integrated with my app. However my I having hard time writing test cases or creating instances of controller in my test cases and execute it’s method. I did however tried docs https://www.docs.nestjs.com/fundamentals/unit-testing it does not work for me login.controller.ts


@Controller('login')
export class LoginController {
       constructor(private readonly loginService: LoginService,
                private readonly usersService: UsersService,
                private readonly authService: AuthService,
                private readonly userDetailsService: UserDetailsService) {

    }
@Post('send')
    @HttpCode(HttpStatus.OK)
sendOtp(@Body() requestBody){
// some functional action that works goes here

const data = requestBody;
//this is working fine as api and in app too
this.saveUserVerificationData(data);

}

saveUserVerificationData = async (data) => {
        try {
            return await this.loginService.create(data);
        } catch (e) {
            Logger.error('Error at saveUserVerificationData' + e);
        }

    }
}

login.spec.ts


describe('test otp positive test cases', async () => {
    it('hello', async () => {
    let loginController: LoginController;
    const module = await Test.createTestingModule({
            controllers: [LoginController],
        }).compile();
    Logger.log('helloooooooooo');
    loginController = module.get<LoginController>(OtpController);

    const loginCodeObject = Utils.getOtpObject(AppConstants.OTP_SMS_INDIA);
    const smsObj = {route: 'otp', phoneNo: '7710004852', c_code: '+91', msg: otpCodeObject.message};


    const loginSendRequest = { phoneNumber: '7710004852', countryCode: '+91', country: 'IN' };
    const loginSendResult = await loginController.sendOtp(loginSendRequest);
    expect(loginSendResult.status).to.equal(1);
});
});

command to run existing unit test case:

env-cmd …/.env nyc --require ts-node/register mocha src/modules/otp/otp.spec.ts --reporter spec

Expected behavior

I want to be able to create instance of otpController and be able to call sendOtp

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Error: Nest can’t resolve dependencies of the LoginController (?, +, +, +). Please verify whether [0] argument is available in the current context. at Injector.<anonymous> (node_modules/@nestjs/core/injector/injector.js:160:23) at Generator.next (<anonymous>) at fulfilled (node_modules/@nestjs/core/injector/injector.js:4:58) at <anonymous>

Environment


Nest version: 4.6.6

 
For Tooling issues:
- Node version: 9.11.1  
- Platform:  MAC OSX 10.13.4 

Others:

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:10

github_iconTop GitHub Comments

2reactions
nileshdattatraykedarecommented, May 12, 2018

Thanks for you replies and support @adrien2p

I finally got it worked:


let loginController: LoginController;
const getModule = async () => {
        const module = await Test.createTestingModule({
            imports: [DatabaseModule],
            controllers: [LoginController],
            components: [
                LoginService,
                ...loginProviders,
                UsersService,
                ...usersProviders,
                AuthService,
                ...authProviders,
                UserDetailsService,
                ...usersProviders,
            ],
        }).compile();
        return module;
    };
const testOne = async () => {
    const module = await getModule();

    otpController = await module.get<LoginController>(LoginController);
    const result = await loginController.sendOtp({
        phoneNumber: '9892480425',
        countryCode: '+91', country: 'IN'});
    return result;
};

describe('started testing fresh', () => {
    it('send otp', async () => {
        const result = await testOne();
        expect(result.status).to.equal(1);
    });
});

command:


env-cmd ../.env nyc --require ts-node/register mocha --timeout 15000 src/modules/login/login.spec.ts --reporter spec

result

started testing fresh ✓ send otp

1 passing (26ms)

0reactions
lock[bot]commented, Sep 25, 2019

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unit Tests, How to Write Testable Code, and Why It Matters
In this article, I will show that unit testing itself is quite easy; the real problems that complicate unit testing, and introduce expensive...
Read more >
Unit Testing of Spring MVC Controllers: "Normal" Controllers
Every unit test which we write to test the behavior of a controller method consists of these steps: We send a request to...
Read more >
Unit testing vs integration testing | CircleCI
While writing unit tests is often faster, the reliability of integration tests tends to build more confidence for key stakeholders. Use both ...
Read more >
Do I need unit test if I already have integration test?
I've decided to write integration tests for my controller method (because without them I can't trust that my API endpoint works). There are...
Read more >
Unit Testing Controllers in ASP.NET Web API 2 - Microsoft Learn
NET 4.5 and later versions. A common pattern in unit tests is "arrange-act-assert": Arrange: Set up any prerequisites for the test to run...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found