测试返回承诺的Angular 2服务
我正在尝试对一个服务进行单元测试,该服务应该使用Angular的内存数据服务提供的伪http后端。以下是相关代码:测试返回承诺的Angular 2服务,angular,testing,asynchronous,Angular,Testing,Asynchronous,我正在尝试对一个服务进行单元测试,该服务应该使用Angular的内存数据服务提供的伪http后端。以下是相关代码: describe('getCars() method ', () => { it('should return a resolved Promise', inject([DataService], (service: DataService) => { service.getCars().then((value) => {
describe('getCars() method ', () => {
it('should return a resolved Promise', inject([DataService], (service: DataService) => {
service.getCars().then((value) => {
expect(value.length).toBe(3);
});
}));
});
问题是我不能使用Jasmine的done回调来处理异步服务.getCars()调用,因为inject函数是如何工作的。我也不能使用异步测试助手,因为它不能与承诺一起工作。因此,我不知道如何等待承诺的解决——测试只是在没有达到预期的情况下运行。使用
async
,它将把它包装成一个区域,等待所有异步任务在测试完成之前完成
import { async } from '@angular/core/testing';
// !!!!!!!
it('should return a resolved Promise', async(inject([DataService], (service: DataService)=>{
service.getCars().then((value) => {
expect(value.length).toBe(3);
});
})));
另一个选项是根本不使用inject
。您只需从测试床
获取服务即可。这是一个很好的选择
let service: DataService;
beforeEach(() => {
const injector = TestBed.configureTestingModule({});
service = injector.get(DataService);
});
不需要注入
,而且它的详细程度要低得多。您现在可以使用done
。或者,如果您愿意,仍然以角度方式进行,并使用async
另请参见:
异步
。不过,您可能可以将其与fakeAsync
一起使用。请参见“另请参见”中的链接。它显示了如何使用fakeAsync