How to set local storage in TestCafe before the page initialization

Viewed 1471

I need to set local storage to bypass Login screen before the page is initialized by Testcafe. I tried injecting custom scripts but that is not working.

Can someone please help me how to do it ?

3 Answers

To set local storage variables in TestCafe sessions, you can use ClientFunction's. You could set your local storage variable with your key in a beforeEach hook, so that it's called before every single one of your tests. The code to achieve this could look like the following:

const setLocalStorageItem = ClientFunction((key: string, value: string) => window.localStorage.setItem(key, value));

fixture(`My tests`)
  .page("https://www.my-test-url.com")
  .beforeEach(async (t) => {
    await setLocalStorageItem("myLocalStorageKey", "myValue");
  });

test('Some test', async (t) => {
  // This assertion should be fine for every test
  await t.expect(await getLocalStorageItem("myLocalStorageKey")).eql("myValue");

  // more test code should follow here
})

As TestCafe clears the localStorage and sessionStorage after each test, you'd need to do if you want to have access to the same local storage key/value pair in every test (or it needs to be set for each test for some reason).

if you wish to set the local storage entry only for a specific test, you could proceed as follows:

test('Some other test', async (t) => {

  // my test code
}).before(async (t) => {
  await setLocalStorageItem("testKey", "testValue");
});

I tried setting the local storage item in a beforeEach, but in my case, I found that it was getting set too late for my needs. I was able to get things working by using the clientScripts function. So, it looks something like this:

fixture(`My tests`)
  .page("https://www.my-test-url.com")
  .clientScripts({
    content: 'window.localStorage.setItem("myKey", "myValue");'
  });
Related