我的角度組件中有以下物件:
let _user = {user: { id: 1 } };
ngOnInit(){
if(Object.keys(_user.user).length > 0){
callSomething()
}
}
=> 現在為那個組件 spec.ts 檔案
describe("",() => {
let _user = { user: {id: 1} };
let component: TempComponent;
let fixture: ComponentFixture<TempComponent>;
beforeEach(() => {
... component configuration
fixture.detectChanges();
// this will call lifecycle methods and from there component's callSomething() will also get called.
});
it("should not call callSomething() if user properties == 0", () => {
delete _user.user["id"];
// now _user will be only { user: {} }
component.ngOnInit(); // or can call fixture.detectChanges();
expect(component.callSomething).not.toHaveBeenCalled();
// as now the user object will be empty, but because of beforeEach's detectChanges call, it is failing.
});
});
問題:
在這里,當我運行測驗用例時它失敗了
預計間諜不會被呼叫。
通過除錯,我發現它失敗了,因為最初根據條件callSomething()從那里呼叫的 fixture.detectChanges( ) ngOnInit也被呼叫了。
因此,當測驗用例運行時,它已經呼叫了 callSomething()。所以,它失敗了。
我該怎么做才能正確測驗案例?
uj5u.com熱心網友回復:
正如@AliF50 在問題評論中所建議的那樣,休息該方法的呼叫對我有用。 stackoverflow.com/a/54419453/7365461。
解決方案:
it("should not call callSomething() if user properties == 0", () => {
component.callSomethig.calls.reset();
// Note: callSomething should be part of spy object. Then only `calls` property will be applied to it.
delete _user.user["id"];
component.ngOnInit();
expect(component.callSomething).not.toHaveBeenCalled();
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416278.html
標籤:
