|
| 1 | +import { TestBed } from "@angular/core/testing"; |
| 2 | +import { CoursesService } from "./courses.service"; |
| 3 | +import { |
| 4 | + HttpClientTestingModule, |
| 5 | + HttpTestingController, |
| 6 | +} from "@angular/common/http/testing"; |
| 7 | +import { COURSES } from "../../../../server/db-data"; |
| 8 | + |
| 9 | +describe("CoursesService", () => { |
| 10 | + let coursesService: CoursesService; |
| 11 | + let httpTestingController: HttpTestingController; |
| 12 | + |
| 13 | + beforeEach(() => { |
| 14 | + // TestBed creates a angular module that will contain the instance of our service |
| 15 | + TestBed.configureTestingModule({ |
| 16 | + // HttpClientTestingModule has a mock implementation of the http service |
| 17 | + // This mock implementation will have all the same actions at the http service |
| 18 | + imports: [HttpClientTestingModule], |
| 19 | + providers: [CoursesService], |
| 20 | + }); |
| 21 | + coursesService = TestBed.inject(CoursesService); |
| 22 | + httpTestingController = TestBed.inject(HttpTestingController); |
| 23 | + }); |
| 24 | + |
| 25 | + it("should retrieve all courses", () => { |
| 26 | + coursesService.findAllCourses().subscribe({ |
| 27 | + next: (courses) => { |
| 28 | + // First we expect to get some data back |
| 29 | + expect(courses).toBeTruthy("No courses returned"); |
| 30 | + // Check the number of courses |
| 31 | + expect(courses.length).toBe(12, "Incorrect number of courses"); |
| 32 | + // Check if this course instance exists |
| 33 | + const course = courses.find((course) => course.id == 12); |
| 34 | + expect(course.titles.description).toBe("Angular Testing Course"); |
| 35 | + }, |
| 36 | + }); |
| 37 | + // We expect one request to be sent at this endpoint |
| 38 | + const request = httpTestingController.expectOne("/api/courses"); |
| 39 | + // We expect the request to be a GET request |
| 40 | + expect(request.request.method).toEqual("GET"); |
| 41 | + |
| 42 | + // We should specify which data should be returned |
| 43 | + // This is some test data |
| 44 | + request.flush({ payload: Object.values(COURSES) }); |
| 45 | + }); |
| 46 | +}); |
0 commit comments