Skip to content

Instantly share code, notes, and snippets.

@night-fury-rider
Last active May 31, 2020 04:29
Show Gist options
  • Save night-fury-rider/756b1e3df4ed73b1b5f94da001d9e799 to your computer and use it in GitHub Desktop.
Save night-fury-rider/756b1e3df4ed73b1b5f94da001d9e799 to your computer and use it in GitHub Desktop.
Unit testing Angular Application using Jasmine - Home Component Spec
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HomeComponent } from './home.component';
import { HomeService } from './home.service';
import * as globalmocks from '../globalmocks'; // import everything which is present in globalmocks
// Function to reset to globalmocks.
const resetToGlobalMocks = () => {
globalmocks.HomeService.searchSubscriber$ = {
subscribe: (callback) => {
callback('Yuvraj');
}
};
};
// Function to reset to initial mocks.
const resetToInitialMocks = () => {
globalmocks.HomeService.searchSubscriber$.subscribe = (callback) => {
callback('Yuvraj Patil');
};
};
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
HomeComponent,
globalmocks.UvCardStubComponent
],
providers: [
{
provide: HomeService,
useValue: globalmocks.HomeService
}
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HomeComponent);
fixture.detectChanges();
component = fixture.componentInstance;
component.appData = globalmocks.appData;
});
it('should be created', () => {
expect(component).toBeTruthy();
});
describe('ngOnInit', () => {
beforeEach( async () => {
resetToInitialMocks(); // Reset globalmocks to initial mocks before each test case is executed.
fixture.detectChanges();
component.ngOnInit();
});
it('searchBoxSubscription should init search Box Subscription', () => {
expect(component.uvActiveCards.length).toEqual(5);
globalmocks.HomeService.searchSubscriber$ = {
subscribe: (callback) => {
callback('Yuvraj');
}
};
component.ngOnInit();
expect(component.uvActiveCards.length).toEqual(2);
});
afterAll( () => {
resetToGlobalMocks(); // Reset globalmocks when all test cases are executed.
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment