Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test function calls in constructor in Angular

I am working on writing a unit test for the service(refer to code block below) in Angular 2+. How can I achieve this using Jasmine framework ?

declare var window: any;

@Injectable
export class Somename {

   constructor() {
     if (window.cordova) {
       function1();
     } else {
       function2();
     }
   }

   private function1() {
   }

   private function2() {
   }
}  
like image 534
Chetan Khilare Avatar asked Feb 24 '26 22:02

Chetan Khilare


1 Answers

Something like this could be the skeleton:

describe('ComponentExample', () => {
  let component: ComponentExample;
  let fixture: ComponentFixture<ComponentExample>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ComponentExample ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ComponentExample);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    // Lunch cordova here
    expect(component).toBeTruthy();
    // Not lunch cordova here 
    expect(component).toBeTruthy();
  });
});

This should works to check constructor, I do not know how to lunch cordova because i did not work with it. But you need to expect component after open or not open the window.

I read some things about ngOnInit, and I think it is not necessary to test the constructor. If you initialize the component you will test the constructor, the problem here is about open cordova. Some way to check if you covered the constructor is using ng test --code-coverage. This will generate a directory coverage with a index.html file that resumes all lines of your code. And says if you covered certain lines or not.

ngOnInit is most using to execute code when you are routting in your application. Is useful if you needs to do something when a component is charged, or a service. But this not differ with this test.

like image 65
JoseJimRin Avatar answered Feb 26 '26 13:02

JoseJimRin