我正在尝试设置@Injectable
存储服务的测试。
@Injectable()
export class StorageService {...
constructor(private platform: Platform,
public instanceService: InstanceService,
private logger: LoggingService,
private database: SQLite = null) {... //injecting a db mock
我已经创建了几个成功的测试版本,但我知道它们只是成功,因为它们是异步的并且误报了错误。
这是设置。
describe('Storage Service tests', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [],
providers: [
StorageService,
{ provide: Platform, useClass: PlatformMock },
{ provide: InstanceService, useClass: InstanceServiceMock },
{ provide: LoggingService, useClass: LoggingServiceMock },
{ provide: ConfigurationService, useClass: ConfigurationServiceMock },
{ provide: SQLite, useClass: DBMock },
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory: (mockBackend, options) => {
return new Http(mockBackend, options);
},
deps: [MockBackend, BaseRequestOptions]
}
],
imports: [
HttpModule
]
}).compileComponents();
}));
我正在尝试测试setFailedImageUpdate
我很难知道如何同时注入服务,因此它初始化和传递done
以进行异步完成。
it('should set failed image', (done) => {
let cu = new UnsavedImageUpdate();
inject([StorageService, MockBackend], (storageService, mockBackend) => {
storageService.db = new DBMock();
storageService.setFailedImageUpdate([cu]).then((res) => {
expect(res).toEqual("1234");
done();
})();
})
});
我在这次迭代中遇到的错误是:
Error: Timeout - Async callback was not invoked within timeout
specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
如何设置我的测试以同时注入StorageService
和传入done
?
编辑:试着按照@学习者的建议,我创建了这个:
it('should set failed image', async() => {
let cu = new UnsavedImageUpdate();
var storageService = TestBed.get(StorageService);
storageService.db = new DBMock();
storageService.setFailedImageUpdate([cu]).then((res) => {
expect(res).toEqual("1234");
})
});
测试成功,但是当我调试它时,我收到了这个错误:
'expect' was used when there was no current spec,
this could be because an asynchronous test timed out
答案 0 :(得分:1)
您可以使用inject
在测试方法中获取注入的服务,而不是使用TestBed.get(StorageService)
,您可以使用角度测试模块中的async
函数来等待异步操作完成而不是使用done
。
像这样使用:
it('should set failed image', (done) => {
let cu = new UnsavedImageUpdate();
var storageService = TestBed.get(StorageService);
storageService.db = new DBMock();
storageService.setFailedImageUpdate([cu]).then((res) => {
expect(res).toEqual("1234");
done();
})
});