本文介绍了角度单元测试是否根据来自服务的数据调用组件方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法弄清楚如何在服务数据条件下测试组件方法是否被触发...
I can't figure out how to test if a component method is fired or not on service data condition...
服务看起来像:
@Injectable()
export class SomeService {
someData() {
return true;
}
}
comp:
export class SomeComponent {
constructor(private someService: SomeService) {
if (this.someService.someData()) {
this.someMethod();
} else {
console.log('keep kalm!');
}
}
someMethod() {
console.log('some method is fired!')
}
}
测试:
describe('SomeComponent', () => {
let component: SomeComponent;
let fixture: ComponentFixture<SomeComponent>;
let mockSomeService = {
someData: () => true
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers: [
{
provide: SomeService, useValue: mockSomeService
}
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('method should be called', () => {
spyOn(component, 'someMethod');
expect(component.someMethod).toHaveBeenCalled();
});
});
someMethod触发组件,但测试失败:
The component someMethod fires but test fails with:
我该如何解决这个问题?
How can I fix this?
提前致谢!
推荐答案
Oke它是固定的!感谢@Supamiu的答案
Oke It is fixed! thanks to the answer from @Supamiu
将来有人会需要它:
将初始化移至ngOnInit,remove fixture.detectChanges();来自beforeEach并在测试中执行它。所以:
Move the initialization into ngOnInit, remove fixture.detectChanges(); from beforeEach and execute it in the test. So:
Comp:
constructor(private someService: SomeService) { }
ngOnInit() {
if (this.someService.someData()) {
this.someMethod();
} else {
console.log('keep kalm!');
}
}
测试:
beforeEach(() => {
fixture = TestBed.createComponent(SomeComponent);
component = fixture.componentInstance;
// fixture.detectChanges(); <<< Remove this
});
it('method should be called', () => {
spyOn(component, 'someMethod');
fixture.detectChanges(); // trigger ngOnInit here
expect(component.someMethod).toHaveBeenCalled();
});
这篇关于角度单元测试是否根据来自服务的数据调用组件方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!