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.

Issue while (unit test) mocking container.get service

See original GitHub issue

Hello all,

I have some issues in unit testing container.get(service), checkout the below code.

import * as _ from 'lodash';
import {Service, Inject, Container} from 'typedi';
import OTPService from '../otp/index';

@Service()
export default class DevicechangeService {
  constructor(@Inject('devicechangeModel')private devicechangeModel, @Inject('otpModel')private otpModel, @Inject('logger')private logger,) {}

  /**
   *
   * Service to change the device
   *
   * @method deviceChange
   * @param {number} accountId
   * @param {string} deviceId
   * @param {number} mobile
   * @return {object} resolves after sending otp
   */

  public async deviceChange(accountId : number, deviceId : string, newdeviceId : string, created : number, mobile : number,) : Promise < any > {
    try {
      await this
        .devicechangeModel
        .addDeviceChangeDetails(accountId);

       let OTPServiceInstance = Container.get(OTPService);


      await this
        .otpModel
        .updateOTPtoInactiveForModule('DEVICE_CHANGE', accountId);
      //get the new otp

        //get the user details
        //send the otp
        let result = await OTPServiceInstance.sendOTP(serviceprovider, mobile, otpMessage, isd);
        if (result instanceof Object) {
          return result;
        }
        return true;
      } else {
        return {
          field: 421,
          message: errorCode('account').getMessage(421)
        };
      }
    } catch (e) {
      throw e;
    }
  }
}

Here i am not able to set mock class for OTPService, so not able to alter container.get(OTPService) from the above code.

I have tried below but still it does’nt come inside mocked service.

@Service()
class OTPService {
  public generateOTP : any = jest
    .fn()
    .mockImplementation(async(accountId : number, deviceId : string, status : string) => new Promise((resolve : any) => {
      console.log('calls here')
      resolve({})
    }),);
  public sendOTP : any = jest
    .fn()
    .mockImplementation(async(serviceprovider : string, mobile : number, otpMessage : string, isd : number) => new Promise((resolve : any) => resolve({})),);
}

describe('Account', () => {
  beforeEach(done => {
    Container.set(OTPService, new OTPService());
    done();
  });
  describe('#deviceChange', () => {
    it('check everyting cool', async done => {
      let logger = {};
      let otpModel = {
        updateOTPtoInactiveForModule: jest
          .fn()
          .mockImplementation(async(deviceChange : string, accountId : number) => new Promise((resolve : any) => resolve(true))),
        getUserPhoneService: jest
          .fn()
          .mockResolvedValue(true)
      };
      let devicechangeModel = {
        addDeviceChangeDetails: jest
          .fn()
          .mockResolvedValue(true),
        updateDeviceChangeToInactive: jest
          .fn()
          .mockResolvedValue(true)
      };
      // Container.set('OTPService', new OTPService());
      let DeviceChangeServiceInstance = new DeviceChangeService(devicechangeModel, otpModel, logger);
      let deviceChangeStatus = DeviceChangeServiceInstance.deviceChange(accountId, deviceId, newdeviceId, created, mobile);
    });
  });
});

Guys any input how to solve this…

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
rafalfiguracommented, Dec 16, 2019

I came to know that we should not use Container.get() in service layer instead use dependency injection so its easy to write the unit tests.

Can you give some example code?

0reactions
github-actions[bot]commented, Aug 30, 2020

This issue 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

Auto-mocking Container - ploeh blog
This article describes a unit test pattern called an Auto-mocking Container. It can be used as a solution to the problem: How can...
Read more >
IOC container Or Mock in unit test - Stack Overflow
In short, yes. Mocking services is fine and integration tests should not use mocks. It depends on what you want to test. Both...
Read more >
Unit Test Using Mock Object in Dependency Injection
This article explains how dependency injection helps unit testing in applications.
Read more >
Using Mocks While Unit Testing ASP.NET Core Apps - Telerik
Check out this article on how to easily mock your code with JustMock for successful unit tests on your ASP.NET Core app.
Read more >
How it is supposed to work with unit test? · Issue #45 - GitHub
Mocks are allowed only to 3rd-party services like mail or Amazon S3 and I could be easily done with container.set or at the...
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