loopbackjsloopback4v4l2loopback

Loopback-4 Mocking injection


i'm using loopback-4, looking for help to mock the @inject declared at class level.

Please find below code.

import { repository } from '@loopback/repository';
import { AddressRepository } from './address.repository';
import { Address } from './address.db.model';

export class AddressService {
    @repository(AddressRepository) private addressRepo: AddressRepository;

    async getAddresses(): Promise<Address[]> {
      return this.addressRepo.find();
    }
}

i am trying to mock through @loopback/testlab.StubbedInstanceWithSinonAccessor but its not working, as i am not using constructor injection. tried with below approach but it wont allow.

let addressRepo: StubbedInstanceWithSinonAccessor<AddressRepository>;
const addressService = new AddressService(addressRepo);

can some one help in mocking @injector which is not declared at constructor level?

thank you in advance.


Solution

  • Since your dependency is declared as a property, you need to provide the stubbed implementation via a property setter.

    1. Make your property public so that it can be changed from outside.

      export class AddressService {
        @repository(AddressRepository) 
        public addressRepo: AddressRepository;
      
        // ...
      }
      
    2. Use a regular property setter in your tests.

      let addressRepo: StubbedInstanceWithSinonAccessor<AddressRepository>;
      const addressService = new AddressService();
      addressService.addressRepo = addressRepo;