Home > Mobile >  Using the angular 14 inject() and how to run this in a test
Using the angular 14 inject() and how to run this in a test

Time:11-30

Doing some changes to my code as I wanted to try out some new features so I switched from using a constructor() to using inject() to import services. Now my test is failing and I cant seem to find any documentation about this on how to test this.

How can I change my test to use the inject() way.

old code

export ResetService {
   constructor(private serviceOne: ServiceOne) 
   {}
}

// updated 

export ResetService {
   #serviceOne = inject(ServiceOne) 
}

// old testing code
describe('ResetService', () => {
  let service: ResetService;
  let serviceOne: jasmine.SpyObj<OrderRepository> = jasmine.createSpyObj(OrderRepository, [
    'clearOrders',
  ]);

  beforeEach(() => {
    service = new ResetService(serviceOne);// giving an error with inject()
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});

CodePudding user response:

By using inject inside your service, You explicitly couple your service to the Angular DI system. To make Angular DI work in your test, you will have to use Angular's TestBed. Using TestBed, you can configure a module and provide services that can be injected during testing:

describe('ResetService', () => {
  let resetService: ResetService;

  beforeEach(() => {
     // Create a spy for your dependency
     let serviceSpy: jasmine.SpyObj<OrderRepository> = 
          jasmine.createSpyObj(OrderRepository, [
          'clearOrders',
      ]);
      // Provide both the service-to-test and its (spy) dependency in the testing module
      TestBed.configureTestingModule({
        providers: [
          ResetService
          { provide: OrderRepository, useValue: serviceSpy}
        ]
      });

      // Get a reference to your service-to-test
      resetService= TestBed.inject(ResetService);
   });


  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});


  • Related