Chris Collins
Chris Collins

Reputation: 717

Protractor & Angular 8: Set localStorage before Angular app runs?

I have some E2E testing requirements where I need to mock some data through localStorage, but I'm having a hard time getting localStorage set before Angular runs. The app eventually does see the localStorage item I set, but only after Angular is well into running component code and making HTTP requests. Here is what I have tried:

beforeAll(() => {
  // Attempt #1
  browser.get('/');
  browser.executeScript(`window.localStorage.setItem('foo', 'bar');`);

  // Attempt #2
  browser.get('/').then(() => {
    return browser.executeScript(`window.localStorage.setItem('foo', 'bar');`);
  });
});

Does Protractor have some other mechanism to accomplish this? Or maybe some other creative way of injecting data into an Angular app before it loads on a per-spec (or browser.get) basis? Thanks!

Upvotes: 0

Views: 184

Answers (1)

Yevhen Laichenkov
Yevhen Laichenkov

Reputation: 8682

I recommend you set up this in the onPrepare hook in the protractor config file.

This can be used if the preparation involves any asynchronous calls, e.g. interacting with the browser.

in config:

onPrepare() {
  return browser.get('/').then(() => {
    return browser.executeScript(`window.localStorage.setItem('foo', 'bar');`);
  });
}

Upvotes: 0

Related Questions