當用戶單擊按鈕時,我正在嘗試進行簡單的測驗,它應該從服務中呼叫方法。但是我仍然只是沒有呼叫該方法。組件.ts
@Component({
...
providers: [MyService]
})
export class MyComponent implements OnInit, OnDestroy {
constructor(public myService: myService) { }
}
組件.html
<button id="myId"
(click)="myService.myMethodX()">
</button>
我的服務.ts
@Injectable()
export class MyService {
constructor() { }
myMethodX(){
...
}
}
在茉莉花中,我正在像這樣測驗它。
const mySpyObj = jasmine.createSpyObj('MyService', ['myMethodX']);
it('...', () => {
// Given
const button = ...
// When
button.click();
fixture.detectChanges();
// Then
expect(mySpyObj.myMethodX).toHaveBeenCalled();
});
但它說它不叫我做錯了什么?
uj5u.com熱心網友回復:
您必須將您的模擬注入測驗場景,現在您正在使用真正的實作。通常你會通過providerson來做,TestBed#configureTestModule但你的服務是“組件”范圍而不是單例,因此你也必須覆寫它。
這里有作業示例。注意評論,尤其是overrideComponent電話。它具有至關重要的影響,因為如果沒有它,就會使用真正的實作而不是我們的模擬。
// your service
@Injectable()
class FooBar {
foo() {
return 'bar';
}
}
//your component
@Component({
template: `
<button (click)="fooBar.foo()"></button>
`,
providers: [FooBar] // FooBar is in scope of component, not singleton, therfore....
})
class FooBarComponent {
constructor(public fooBar: FooBar) {
}
}
describe('Foobar', async () => {
let fooMock: SpyObj<FooBar>;
beforeEach(async () => {
fooMock = createSpyObj<FooBar>(['foo']);
return TestBed.configureTestingModule({
declarations: [FooBarComponent],
}).overrideComponent(FooBarComponent, {
set: { // ..... threfore we are overriding component scope provider - now our mock will be provided instead of real implementation
providers: [
{provide: FooBar, useValue: fooMock} // here you actually start using your mock inside component
]
}
}).compileComponents();
});
//passes without a problems
it('calls foo() on click', () => {
const fixture = TestBed.createComponent(FooBarComponent);
fixture.detectChanges();
fixture.debugElement.query(By.css('button')).nativeElement.click();
expect(fooMock.foo).toHaveBeenCalled();
});
});
uj5u.com熱心網友回復:
從您的組件呼叫myMethodX的方法不是服務的方法。在該方法內部呼叫服務方法(我假設),例如myService.calculate().
您應該監視和測驗的是服務中的該方法。你可以這樣做:
// Arange
spyOn(myService, 'calculate');
// Act
button.click();
// Assert
expect(myService.calculate).toHaveBeenCalled();
第二種方法是測驗是否呼叫了組件的方法:
// Arange
spyOn(component, 'myMethodX');
// Act
button.click();
// Assert
expect(component.myMethodX).toHaveBeenCalled();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/429983.html
上一篇:L未定義,使用傳單
