我正在开发测试驱动的角度应用程序。 (别问为什么,这就是客户想要的)
以下是我无法
modify
或edit
的规格。
it('should get results', fakeAsync(
inject(
[XHRBackend, NewsService ],
(mockBackend: MockBackend, newsService: NewsService) => {
const expectedUrl = 'https://api.nytimes.com/svc/topstories/v2/home.json?api-key=315a5a51483b469a918246dc2753b339';
mockBackend.connections.subscribe((connection : MockConnection) => {
expect(connection.request.method).toBe(RequestMethod.Get);
expect(connection.request.url).toBe(expectedUrl);
connection.mockRespond(new Response(
new ResponseOptions({ body: mockResponse })
));
});
newsService.getSectionNews('home')
.subscribe( (res: any) => {
expect(res).toEqual(mockResponse);
});
})
));
因此,根据规范,我需要编写前端代码。
这就是我写的,
import { Http } from '@angular/http';
constructor(private http: Http) {}
getSectionNews(sectionName: string): any {
// fetch news of that sectionName
// return this.mockResponse;
const expectedUrl = 'https://api.nytimes.com/svc/topstories/v2/home.json?api-key=315a5a51483b469a918246dc2753b339';
return this.http.get(expectedUrl).subscribe(res => res);
}
但是在运行测试用例时,我收到此错误:
TypeError:newsService.getSectionNews(...).subscribe 不是函数
请告诉我我在这里做错了什么。
我想通过测试用例。
更新
更新我的服务规范后。
getSectionNews(sectionName: string): Observable<any> {
const expectedUrl = `https://api.nytimes.com/svc/topstories/v2/${sectionName}.json?api-key=315a5a51483b469a918246dc2753b339`;
return this.http.get(expectedUrl);
}
现在我收到以下错误,
预期响应状态:null null 对于 URL:null 等于 Objectt({ 状态: '确定', 版权: 'C ...
getSectionNews(sectionName: string): Observable { // 获取该sectionName的新闻 this.apiURL =
https://api.nytimes.com/svc/topstories/v2/${sectionName}.json?api-key=XXXXXXXXXXXXXXXXXXXXXXXXX
;
返回 this.http.get(this.apiURL).map((res) => res.json());
}
上述共享代码将解决此问题。谢谢