简体   繁体   中英

Angular Unit Test: How to create component instance if constructor takes Globals.ts file as an argument

I am trying to write a unit test for the Login Component of my angular 6 application.

The login.component.ts file has the following constructor

constructor(public global: Globals, private appService: AppService ) {
}

Here Globals is a normal ts file that has some global functions that are used across components. AppService is a service.

My current spec.ts file

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      imports:[
        FormsModule,
        ReactiveFormsModule,
      ],
      providers:[
        AppService
      ]
    })
    .compileComponents();
  }));
   beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Here component instance is coming as undefined.

Can anyone guide how to create the TestBed configure module for this case and create an instance of the component?

This is a great resource to learn testing.

For your case, I would mock both Globals 's and AppService 's public methods.

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  let mockGlobals: jasmine.SpyObj<Globals>;
  let mockAppService: jasmine.SpyObj<AppService>;

  beforeEach(async(() => {
    mockGlobals = jasmine.SpyObj('Globals', [/*public methods you want to mock go here as an array of strings */]);
    mockAppService = jasmine.SpyObj('AppService', [/ *public methods you want to mock go here as an array of strings */]);
    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      imports:[
        FormsModule,
        ReactiveFormsModule,
      ],
      providers:[
        // provide mocks when component wants actual services
        { provide: Globals, useValue: mockGlobals },
        { provide: AppService, useValue: mockAppService }
      ]
    })
    .compileComponents();
  }));
   beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

createSpyObj has many signatures and you can do some more research about it. The link I gave also shows other ways on how to mock dependencies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM