Search code examples
angularunit-testingkarma-jasminegoogle-api-js-client

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


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();
  });
});

Solution

  • 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;
        }
      }
    }