首页 > 解决方案 > 无法使用静态方法返回的类实例访问类方法

问题描述

我创建了一个订阅者类来存储订阅者详细信息并使用静态方法返回该类的实例,但我无法使用该实例设置值

这是订阅者类:

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());
});

这是赛普拉斯控制台上的输出

柏

问题:

  1. 为什么即使我在before块中设置订阅者ID 为空
  2. 如果我打印订阅者对象,为什么我看不到订阅者 ID

这是订阅者对象的输出

订阅者对象

标签: javascriptecmascript-6cypress

解决方案


属性usernamepassword在 中同步定义before(),因此在测试时存在于对象上。

但是subscriberId是异步获取的,所以你需要在测试中等待完成,例如

cy.wrap(Subscriber.getSubscriber()).should(function(subscriber){
  expect(subscriber.getSubsciberId()).not.to.be.null
})

请参阅wra​​p - Objects以了解如何使用 Cypress 命令处理对象。

看看应该 - 差异

另一方面,当使用带有 .should() 或 .and() 的回调函数时,有特殊的逻辑可以重新运行回调函数,直到其中没有断言抛出。

换句话说,should将重试(最多 5 秒),直到expect内部回调没有失败(即在您的情况下,异步调用已完成)。


推荐阅读