0

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?

LearnToCode
  • 169
  • 1
  • 5
  • 19

1 Answers1

2

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.createSpyObj('Globals', [/*public methods you want to mock go here as an array of strings */]);
    mockAppService = jasmine.createSpyObj('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.

AliF50
  • 16,947
  • 1
  • 21
  • 37