I try to test a component with a amount of courses. So I try to do a unit test that there are more then 0 courses available. So I have this:
it('should display only beginner courses', () => {
courseServiceSpy.findAllCourses.and.returnValue(of(beginnerCourses));
fixture.detectChanges();
const tabs = el.queryAll(By.css('.mat-tab-label'));
expect(tabs.length).toBe(1, 'found in tabs found');
});
And this is the template:
<ng-container *ngIf="(beginnerCourses$ | async) as beginnerCourses">
<mat-tab label="Beginners" *ngIf="beginnerCourses?.length > 0">
<courses-card-list (courseEdited)="reloadCourses()"
[courses]="beginnerCourses">
</courses-card-list>
</mat-tab>
</ng-container>
But I still get this error:
Expected 0 to be 1, 'found in tabs found'.
Error: Expected 0 to be 1, 'found in tabs found'.
at <Jasmine>
at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/courses/home/home.component.spec.ts:60:25)
at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:364:1)
at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/proxy.js:117:1)
So what I have to change?
Thank you
This is my total class:
describe('HomeComponent', () => {
let fixture: ComponentFixture<HomeComponent>;
let component: HomeComponent;
let el: DebugElement;
let courseServiceSpy: SpyObj<CoursesService>; // Declare the spy here
const beginnerCourses = setupCourses().filter(course => course.category === 'BEGINNER');
const advancedCourses = setupCourses().filter(course => course.category === 'ADVANCED');
beforeEach(async(() => {
// Initialize the spy here
courseServiceSpy = jasmine.createSpyObj('CoursesService', [
'findAllCourses',
]);
TestBed.configureTestingModule({
imports: [CoursesModule, HttpClientTestingModule, NoopAnimationsModule],
providers: [{provide: CoursesService, usevalue: courseServiceSpy}],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
el = fixture.debugElement;
});
}));
it('should create the component', () => {
expect(component).toBeTruthy();
});
it('should display only beginner courses', () => {
courseServiceSpy.findAllCourses.and.returnValue(of(beginnerCourses));
fixture.detectChanges();
const tabs = el.queryAll(By.css('.mat-tab-label'));
expect(tabs.length).toBe(1, 'found in tabs found');
});
it('should display only advanced courses', () => {
courseServiceSpy.findAllCourses.and.returnValue(of(advancedCourses));
fixture.detectChanges();
const tabs = el.queryAll(By.css('.mat-tab-label'));
expect(tabs.length).toBe(1, 'found in tabs found');
});
});
and this is the method:
findAllCourses(): Observable<Course[]> {
return this.http.get('/api/courses')
.pipe(
map(res => res['payload']), shareReplay()
);
}