I am writing a simple test case for a get API.
Created service spy return the mockObj and then called the actual function
test.component.ts
export class TestComponent implements OnInit {
courses = <any>[];
constructor(private testService: TestService) { }
ngOnInit(): void {
this.getAllCourses();
}
getAllCourses() {
this.testService.getAllCourses().subscribe((res: any) => {
this.courses = res['data'];
console.log(this.courses);
});
}
}
test.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
@Injectable({
providedIn: 'root'
})
export class TestService {
constructor(private http: HttpClient) { }
getAllCourses() {
return this.http.get('assets/dummy_data.json');
}
saveCourse() {
let url = '';
let body = {}
this.http.post(url, body);
}
updateCourse() {
let url = '';
let body = {}
this.http.put(url, body);
}
}
test.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TestService } from './test.service';
import { ComponentFixture, TestBed, tick } from '@angular/core/testing';
import { TestComponent } from './test.component';
import { of } from 'rxjs';
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let testServiceSpy: any;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [TestComponent],
imports: [HttpClientTestingModule],
providers: [TestService]
})
.compileComponents();
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
testServiceSpy = jasmine.createSpyObj('TestService', ['getAllCourses']);
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should get all courses', () => {
let mockObj = <any>{
data: [
{
"title": "title 1"
},
{
"title": "title 2"
}
]
};
testServiceSpy.getAllCourses.and.returnValue(of(mockObj));
component.getAllCourses();
expect(component.courses).toEqual(mockObj.data);
});
});
How to complete getAllCourses method and then match the expectations of subscribe method?
Expectation: mock should match the result
Result: [] does not match data