Hi, how can I handle session and local storages?
I've been searching but can't find documentation anywhere.
Thanks
Hi!,
If you need to read or write value to storage from test code, you can create a bunch of ClientFunctions:
import { ClientFunction } from 'testcafe';
const localStorageSet = ClientFunction((key, val) => localStorage.setItem(key, val));
const localStorageGet = ClientFunction(key => localStorage.getItem(key));
fixture `Test fixture`;
test ('Test', async t => {
await localStorageSet('foo', 'bar');
await t.expect(localStorageGet('foo')).eql('bar');
});
Hi @inikulin
I did it yesterday after found in this repository @hackathonic/hackathonic-client
My fault was trying to get the sessionStorage object.
Thank you so much @inikulin
Note that TestCafe won't complain if you try and set a localStorage item before a page is loaded. You can read it back too but when a different page is then loaded the item will not be set (which makes sense). That had me confused for a while. Just recording my mistake here in case it helps someone.
Hello,
Can I set session storage as well like this
const sessionStorageSet = ClientFunction((key,val) => sessionStorage.setItem(key,val))
await sessionStorageSet("GCLOUD_TOKEN",token).then(function(data){
console.log(data);
}).catch(function(err){
console.log(err);
})
As I run the above code key hammerhead|storages-sandbox-temp of session storage sets it value as GCLOUD_TOKEN. Is there any thing wrong which I do in the above code.
Hi @TestAndunR, TestCafe proxies access to the storage from JS scripts. You can see in DevTools that values are saved under a different key, but scripts on a page are modified to hide this difference from JS code.
import {ClientFunction} from 'testcafe';
fixture `123`.page `example.com`;
const sessionStorageSet = ClientFunction((key,val) => sessionStorage.setItem(key,val))
test(`1`, async t => {
await sessionStorageSet("GCLOUD_TOKEN", '42');
await console.log(await t.eval(() => sessionStorage.getItem('GCLOUD_TOKEN')));
});
Thanks @AndreyBelym. But when I use, useRole function as I refresh the page after setting values to session storage, It reset its value and goes to the index page. Without using the useRole function it works correctly.
Is it a known issue?
This thread has been automatically locked since it is closed and there has not been any recent activity. Please open a new issue for related bugs or feature requests. We recommend you ask TestCafe API, usage and configuration inquiries on StackOverflow.
Most helpful comment
Hi!,
If you need to read or write value to storage from test code, you can create a bunch of ClientFunctions: