angular6+ ng test 单元测试遇到的坑

原创 booogle 随笔 经验之谈 66阅读 2018-12-26 16:51:00 举报

在angular中写单元测试时经常会遇到无法模拟远程数据,特别时Promise类型的数据。通过ng test进行单元测试的时候,此时会用到jasmine的createSpyObj方法。具体操作如下:

let spy: jasmine.Spy;
beforeEach(async (() => {
let a = '123';
let spyservice = jasmine.createSpyObj('DemoService', ['getData']);
spy = spyservice.getData.and.returnValue( Promise.resolve(a) );
TestBed.configureTestingModule({
declarations: ...,
imports: ...,
providers: [{ provide: DemoService, useValue: spyservice }]
}).compileComponents().then(() => {
fixture = TestBed.createComponent(DemoComponent);
component = fixture.componentInstance;
...
...
fixture.debugElement.injector.get(DemoService);
fixture.detectChanges();
});
}))

校验断言

it('the spy was called', async(() => {
expect(spy.calls.any()).toBe(true, 'get called');
}), 3000);

参考资料:https://github.com/karma-runner/karma/issues/2801

评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复