import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed, inject } from '@angular/core/testing'; import { AuthService } from './auth.service'; import { Router } from '@angular/router'; describe('AuthService', () => { const routerSpy = () => jasmine.createSpyObj('Router', ['navigate']); beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ AuthService, { provide: Router, useValue: routerSpy } ] }); }); it('should be created', inject([AuthService, HttpTestingController], (service: AuthService, httpMock: HttpTestingController) => { expect(service).toBeTruthy(); const submitForm = { username: 'cwq', password: '123456', rememberMe: true }; service.login(submitForm).subscribe(data => { console.log(data); }); const mockReq = httpMock.expectOne(req => { console.log(req); return req.method === 'POST' && req.url === '/login'; } ); expect(mockReq.cancelled).toBeFalsy(); expect(mockReq.request.responseType).toEqual('json'); // 伪造返回值,此时才开始模拟请求 mockReq.flush({code: 203}); })); });