Callback function is a function which is passed to a function as parameter and is executed when the outer function is completed. Callbacks are a feature of JavaScript not particularly angularjs. Its a way to send a function as a parameter to the callee so that the callee call that function once the task is finished.
Jasmine is a behavior development testing framework. Unit tests are written using Jasmine and are run to see if individual parts of an application are working correctly. As a result, unit tests will either pass or fail depending on if the code is working correctly or has a bug.
Jasmine is a behavior-driven development framework for testing JavaScript code that plays very well with Karma. Similar to Karma, it's also the recommended testing framework within the Angular documentation as it's setup for you with the Angular CLI. Jasmine is also dependency free and doesn't require a DOM.
I have a breadcrumbs component in my Angular project where you pass in a callback function that gets called when the breadcrumb is clicked.
The user passes in an object that contains the info to render a breadcrumb, along with a callback for when the breadcrumb is clicked.
The callback is added to the breadcrumb's onclick
event and called when the user clicks on one.
<li *ngFor="let breadcrumb of breadcrumbs">
<span (click)="breadcrumb.callback()">{{breadcrumb.title}}</span>
</li>
This is what I've tried:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [BreadcrumbsTestComponent, Breadcrumbs]
});
}));
it('should call given callback when breadcrumb is clicked', async(() => {
const fixture = TestBed.createComponent(BreadcrumbComponent);
fixture.detectChanges();
const breadcrumbElements = fixture.nativeElement.querySelectorAll('.breadcrumb');
breadcrumbElements.forEach(breadcrumb => {
breadcrumb.click();
fixture.whenStable().then(() => {
expect(breadcrumb.callback).toHaveBeenCalled();
});
});
}));
const breadcrumbs = [
{
title: 'First Page',
path: '/first',
current: false,
callback: jasmine.createSpy('callback')
}, {
title: 'Second Page',
path: '/second',
current: true,
callback: jasmine.createSpy('callback')
}
];
@Component({
template: `<breadcrumbs [breadcrumbs]="breadcrumbs"></breadcrumbs>`
})
class BreadcrumbsTestComponent {
breadcrumbs = breadcrumbs;
}
How do I test that the callback was called in my Jasmine testing?
Thanks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With