TestBed trong Angular là gì?
TestBed trong Angular là gì?
TestBed là công cụ chính để viết unit test cho Angular (package @angular/core/testing). Nó tạo một môi trường Angular thu nhỏ cho mỗi test: cấu hình dependency injection, biên dịch component, tạo component và cho phép kiểm tra DOM, change detection.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
describe('UserService', () => {
let service: UserService;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [UserService, provideHttpClient(), provideHttpClientTesting()],
});
service = TestBed.inject(UserService);
http = TestBed.inject(HttpTestingController);
});
it('gọi đúng API', () => {
service.getUser(1).subscribe(u => expect(u.name).toBe('An'));
http.expectOne('/api/users/1').flush({ id: 1, name: 'An' });
http.verify(); // không còn request nào chưa xử lý
});
});
describe('CounterComponent', () => {
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.