提问人:Venkata 提问时间:8/18/2018 最后编辑:ischenkodvVenkata 更新时间:8/20/2018 访问量:265
无法使用静态方法返回的类实例访问类方法
not able to access class methods using the class instance returned by a static method
问:
我创建了一个订阅者类来存储订阅者详细信息,并使用静态方法返回该类的实例,但我无法使用该实例设置值
下面是订阅者类:
let _instance;
export class Subscriber {
constructor(username, password) {
this._username = username;
this._password = password;
}
setSubscriberId(subscriberId) {
cy.log(subscriberId);
this._subscriberId = subscriberId;
}
setSessionId(sessionId) {
this.sessionId = sessionId;
}
getUserName = () => {
return this._username;
}
getPassword = () => {
return this._password;
}
getSubsciberId() {
return this._subscriberId;
}
getSessionId() {
return this.sessionId;
}
static createSubscriber(username, password) {
if (!_instance) {
_instance = new Subscriber(username, password);
}
return _intance;
}
static getSubscriber() {
return _instance;
}
}
我正在创建块中类的实例并访问块中的实例before
Given
before("Create a new subscriber before the tests and set local storage", () => {
const username = `TestAutomation${Math.floor(Math.random() * 1000)}@sharklasers.com`;
const password = "test1234";
subscriberHelpers.createSubscriber(username, password, true).then((response) => {
cy.log(response);
Subscriber.createSubscriber(username, password);
Subscriber.getSubscriber().setSubscriberId(response.Subscriber.Id);
Subscriber.getSubscriber().setSessionId(response.SessionId);
}).catch((error) => {
cy.log(error);
});
});
Given(/^I launch selfcare app$/, () => {
cy.launchApp();
});
Given(/^I Set the environemnt for the test$/, () => {
cy.log(Subscriber.getSubscriber());
cy.log(Subscriber.getSubscriber().getSubsciberId());
});
这是 Cypress 控制台上的输出
问题:
- 为什么 subscriberID 为 null,即使我在块中设置它
before
- 如果我打印订阅者对象,为什么我没有看到订阅者 ID
这是订阅者对象的输出
答:
0赞
Richard Matsen
8/20/2018
#1
属性和 在 中同步定义,因此在测试时存在于对象上。username
password
before()
但是是异步获取的,因此您需要在测试中等待完成,例如subscriberId
cy.wrap(Subscriber.getSubscriber()).should(function(subscriber){
expect(subscriber.getSubsciberId()).not.to.be.null
})
请参阅 wrap - Objects,了解如何使用 Cypress 命令处理对象。
并查看应该 - 差异
另一方面,当使用带有 .should() 或 .and() 的回调函数时,有特殊的逻辑来重新运行回调函数,直到其中没有断言。
换句话说,将重试(最多 5 秒),直到内部回调没有失败(即,在您的情况下,异步调用已完成)。should
expect
评论
_intance
_instance
() =>