perivoje
perivoje

Reputation: 3

is there way to get and set token to local storage?

I'm writing e2e tests on http:localhost/ using protractor since we are only developing front-end app. I have to login into clients integration and manually copy token value from local storage and pass it to custom login method witch I created. Is there away to automate this login process?

Any suggestion would be great

So far I have tried window.localStorage.getItem() and window.localStorage.setItem()

public static Login(): void {
    browser.get('login url');
    browser.driver.findElement(by.id('username')).sendKeys('user');
    browser.driver.findElement(by.id('password')).sendKeys('pass');
    browser.driver.findElement(by.id('submit')).click();
    browser.waitForAngular();
    const token: string = window.localStorage.getItem('AuthenticationToken');
    browser.get('error page');
    window.localStorage.setItem('AuthenticationToken', token);
    browser.get('home page');
}

I get this errors:

Upvotes: 0

Views: 3540

Answers (1)

Sergey Pleshakov
Sergey Pleshakov

Reputation: 8978

According to @Abhishek items of a local storage can be set and gotten using localStorage.setItem('Auth_token', data) and localStorage.getItem(keyName)

However, from my understanding this can be done only from the browser's console, not from protractor script. Thus, if you want to accomplish the same results in your protractor script you could do the following:

browser.executeScript(`return window.localStorage.getItem(keyName);`);

Or if you intend to use local storage a lot, implement a new local-storage.js module as follow:

function LocalStorage () {

    this.get = async function () {
        let storageString = await browser.executeScript("return JSON.stringify(window.localStorage);");
        return JSON.parse(storageString);
    };

    this.clear = async function () {

        return browser.executeScript("return window.localStorage.clear();");
    };

    this.getValue = async function (key) {

        return browser.executeScript(`return window.localStorage.getItem('${key}');`);
    };

    this.setValue = async function (key, value) {
        return browser.executeScript(`window.localStorage.setItem('${key}', '"${value}"');`);
    };
}

module.exports = new LocalStorage();

And then in your spec, do the following:

localStorage = require("./local-storage.js");

describe(`Suite: Home page`, () => {

    fit("Login to the application", async () => {

        console.log(await localStorage.getValue("calltrk-calltrk_referrer"));
        await localStorage.setValue("key", "value");
        console.log(await localStorage.getValue("key"));
        console.log(await localStorage.get());
    });
});

Note I solely handle Promises with async/await keywords. So your syntax can be different, but the approach should remain the same

Upvotes: 1

Related Questions