how to stub Google gapi global variable in component tests using Karma
Asked Answered
B

1

6

I'm trying to setup tests in my angular 4 project for a service that uses Google gapi. The problem I have is that the variable is declared globally but not mocked, therefore when I run the tests I get the following error:

ReferenceError: gapi is not defined

How can I mock the gapi global variable (and its calls to load and auth2)?

Here are my 2 classes (implementation and test class)

Component class

declare const gapi: any;

@Component({
  selector: 'app-register-google',
  templateUrl: './register-google.component.html',
  styleUrls: ['./register-google.component.css']
})

export class RegisterGoogleComponent implements OnInit, AfterViewInit {...}

Test class

describe('RegisterGoogleComponent', () => {

  beforeEach(async(() => {

    TestBed.configureTestingModule({
      declarations: [RegisterGoogleComponent]
    })
      .compileComponents();
  }));

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
Bellbella answered 28/11, 2017 at 20:50 Comment(1)
As any other global. Define it on window and replicate relevant parts with Jasmine spies.Ogata
L
7

I had a similar problem with the Google API const.

@estus is correct; you can define the global variable on window within the beforeEach block:

beforeEach(() => {
  fixture = TestBed.createComponent(MyComponent);
  component = fixture.componentInstance;

  window['gapi'] = {
    load() {
      return null;
    },
    anotherFunction() {
      return null;
    }
  }
}
Lorikeet answered 10/10, 2018 at 15:59 Comment(3)
This should be marked correct. Clean way to add a global variable for a test. Thank you so much.Foliage
@L1ghtk3ira: I know this is long ago now but how did you solve the issue exactly?The above does get rid off gapi is undefined error but still how do you stab gapi.auth2.init methods etc?Garry
@NieSelam Sorry it has been a while and the answer above looks correct. If it is the same issue as above can you explain in a it more detail? If its different can you make a StackOverflow question and tag me? ThanksFoliage

© 2022 - 2024 — McMap. All rights reserved.