我是测试API调用的新手。我在Angular 2中有这个单元测试代码:
beforeEach(inject([JobListService, MockBackend],
(testedService: JobListService, mockBackend: MockBackend) => {
service = testedService;
backend = mockBackend;
backend.connections.subscribe((c) => {
c.mockRespond(new Response(
new ResponseOptions({body: JSON.stringify(JOBLISTMOCK)})
));
});
}));
describe('getAll', () => {
it('should return jobs', () => {
service.getAll(1, 10, '0').subscribe(response => {
console.log(response.data.length);
expect(response.data.data.length).toBeGreaterThan(0);
});
});
it('should return jobs based on company ID', () => {
service.getAll(1, 10, '26').subscribe(response => {
console.log(response.data.data.length);
expect(response.data.data.length).toEqual(1);
});
});
});
它有url结构: http://example.com/api/jobs/1/10/26
第一段和第二段是分页,第三段是公司ID。
我正在测试此服务功能:
getAll(page: number, pageSize: number, company: string): Observable<any> {
if (company !== 'null') {
return this.http.get(`${this.conf.apiUrl}/jobs/companies/get/${page}/${pageSize}/${company}`)
.map((response: Response) => response.json());
} else {
return this.http.get(`${this.conf.apiUrl}/jobs/companies/get/${page}/${pageSize}/0`)
.map((response: Response) => response.json());
}
}
我有这个模拟回应:
{
'id': 13,
'title': 'Sample Title',
'valid_from': '2016-01-01',
'valid_to': '2016-02-01',
'field_id': '1',
'image': '',
'description': null,
'user_id': 0,
'company_id': 26,
'created_at': '2017-01-23 14:37:01',
'updated_at': '2017-01-23 14:37:01',
'fields': {
'field_id': 1,
'name': 'Respiratory Therapy Technician'
}
},
{
'id': 15,
'title': 'Sample Title',
'valid_from': '2016-01-01',
'valid_to': '2016-02-01',
'field_id': '1',
'image': 'asd',
'description': 'This is my sample des',
'user_id': 0,
'company_id': 0,
'created_at': '2017-01-23 14:37:27',
'updated_at': '2017-01-23 14:37:27',
'fields': {
'field_id': 1,
'name': 'Respiratory Therapy Technician'
}
}
}
显然,第二个失败了,因为我的模拟响应被设置为有0和26作为ID的公司。
我得到的是我通过mockbackend嘲笑响应但是我想要的是测试函数,使得getAll()只返回带有company_id 26的作业。但是我的模拟响应是静态的。无论如何,我可以制作一个动态的模拟后端&#34;这将适用于我想要测试的内容吗?