[英]Angular unit test if component method is called according to a data from a service
我不知道如何在服務數據條件下測試組件方法是否被觸發...
服務看起來像:
@Injectable()
export class SomeService {
someData() {
return true;
}
}
比較:
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會觸發,但測試失敗並顯示以下內容:
預期已經調用了間諜someMethod。
我怎樣才能解決這個問題?
提前致謝!
在創建組件之前,您必須先創建間諜,因為間諜無法查看過去,並且由於僅在構造函數中調用了您的方法,因此在創建間諜后就不會對其進行調用。
您應該將初始化移動到ngOnInit
方法或在構造函數中調用的簡單init()
方法,這種方式可以調用init
方法或ngOnInit
並檢查是否已調用someMethod
。
您設置間諜太遲了。 在您將間諜安裝到服務上時,它已經被構造並且已經調用someMethod
。 因此,在defining
組件之后調用間諜
it('method should be called', () => {
var spy = spyOn(component, "someMethod").and.callThrough();
expect(component).toBeDefined();
expect(spy);
expect(component.someMethod).toHaveBeenCalled();
});
奧克它是固定的! 感謝@Supamiu的回答
如果將來有人需要它:
將初始化移到ngOnInit中,刪除夾具。 從beforeEach開始並在測試中執行它。 所以:
比較:
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();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.