How to inject a ts-mockito mock object in the controller

1k Views Asked by At

My background is PHP (Laravel base) So forgive me if I'm not 100% how Typescript/Nodejs suppose to work off the bat.

I am trying to test a controller with supertest and my project is made using restify and inversify for DI.

Using Mocha/Chai and ts-mockito for mocking - my goal is to reject a promise

when(mockedService.getRates(anything())).thenReject();

My controller has the following for constructor:

  constructor(
    @inject('Service') @named('Rates') protected ratesService: RatesService,
  ) {
    super();
  }

then for testing:

describe('Rates Controller', () => {
    const mockedRatesService: RatesService = mock(RatesService);
    when(mockedRatesService.getRates(anything())).thenResolve();

    // Getting instance from mock
    let ratesService: RatesService = instance(mockedRatesService);

    it('returns 200', async () => {
        const res = await supertest(
            app.get<Server>('Server')
        ).get('/rates')
         .set('Accept', 'application/json');

        expect(res.status).to.be.equal(200);
        console.log(res.body);
    });
});

I'm trying to swap out the protected ratesService with the mockedService

In Laravel the controller would be type hinted via constructor or I would have $this->app['my_service']; that would resolve the binding and during unit test I can create a mock and swap out.

I cannot find the information needed to achieve the same in typescript. Any guidance please?

0

There are 0 best solutions below