我刚刚开始在Angular中编写书写单元测试。首先,我想为我的服务编写测试以从外部服务器获取数据。我试图检查方法的类型。我使用了一些教程,但是无法连接服务器。下面是我的代码。
import { GitHubService} from './github.service';
import { TestBed, inject } from '@angular/core/testing';
import {
HttpClientTestingModule,
HttpTestingController
} from '@angular/common/http/testing';
describe('GitHubService', () => {
let service: GitHubService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [GitHubService]
});
service = TestBed.get(GitHubService);
httpMock = TestBed.get(HttpTestingController);
});
it('should create GitHubService', inject(
[GitHubService],
(service: GitHubService) => {
expect(service).toBeTruthy();
}
));
it('service url should be a GET method', () => {
const req = httpMock.expectOne(`${service.API_URL}/users`);
expect(req.request.method).toBe('GET');
});
afterEach(() => {
httpMock.verify();
});
});
运行ng test
后,结果为1 FAILED, 1 SUCCESS
并产生错误:Error: Expected one matching request for criteria "Match URL: https://api.github.com/users", found none.
。我一直在寻找答案,但解决方案无法正常工作。我的代码有什么问题,我应该纠正什么?感谢您的建议。