javascript - 无法使用静态方法返回的类实例访问类方法
问题描述
我创建了一个订阅者类来存储订阅者详细信息并使用静态方法返回该类的实例,但我无法使用该实例设置值
这是订阅者类:
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());
});
这是赛普拉斯控制台上的输出
问题:
- 为什么即使我在
before
块中设置订阅者ID 为空 - 如果我打印订阅者对象,为什么我看不到订阅者 ID
这是订阅者对象的输出
解决方案
属性username
和password
在 中同步定义before()
,因此在测试时存在于对象上。
但是subscriberId
是异步获取的,所以你需要在测试中等待完成,例如
cy.wrap(Subscriber.getSubscriber()).should(function(subscriber){
expect(subscriber.getSubsciberId()).not.to.be.null
})
请参阅wrap - Objects以了解如何使用 Cypress 命令处理对象。
看看应该 - 差异
另一方面,当使用带有 .should() 或 .and() 的回调函数时,有特殊的逻辑可以重新运行回调函数,直到其中没有断言抛出。
换句话说,should
将重试(最多 5 秒),直到expect
内部回调没有失败(即在您的情况下,异步调用已完成)。
推荐阅读
- python - 如何制作一个自动选择并准备写入的 tkinter 输入字段?
- c# - 如何检查已发布的自包含应用程序的 .NET Core 版本?
- python-3.x - 对存储在变量中的多个关键字使用运行关键字
- cordova - Apache cordova Build 在实施 firebase 时失败:依赖失败
- ubuntu - rsyslog stop 命令复制消息而不是移动
- google-bigquery - 如何在 BigQuery 的 WITH 下的 select 中构建表?
- mysql - MySql 在 WHERE 中使用变量
- android - 是否可以重新路由 FCM 的应用内消息弹出窗口?
- php - 如何使用 eloquent 从数据库中检索 created_at 数据
- php - PHP中某个字符后1个字符的最小值