![](/img/trans.png)
[英]How to reuse a function from an existing Cypress test, and call it in a new one?
[英]How to call a helper function from Cypress?
我正在測試一個組件,它依賴於提供 object 的服務:
export class MyComponent {
public constructor { private myObjectService: ObjectService }
public ngOnInit() {
this.functionThatNeedsObject();
}
private functionThatNeedsObject() {
this.myObjectService.getObject();
}
}
這個 object 最初總是null
。 為了讓我的測試成功,它應該由服務初始化:
export class ObjectService {
private NeededObject myObject;
public getObject() {
... return object
}
public setObject() {
... this function needs to be called, so that myObject is not null
}
}
我的測試檢查是否顯示了 MyComponent,這只會在 MyObject 不是 null 時發生。 就像是:
When('I receive data from my services', () => {
cy.get('my-component-selector').should('be.visible')
})
在這種情況下,object 是一個 Behaviorsubject,通常由測試時不可用的服務設置,因此我需要在賽普拉斯測試中以編程方式手動調用myObjectService.setObject()
。
這可能嗎?
你試過inject
嗎? 此外,為了測試可見性,您可能需要使用nativeElement
訪問 dom
When('I receive data from my services', inject([ServiceName],(serviceName:ServiceName) => { // here you can set the data using serviceName // then call the component. cy.get('my-component-selector').should('be.visible') })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.