Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
  });
});
like image 416
Aymeric Avatar asked Nov 28 '17 20:11

Aymeric


1 Answers

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;
    }
  }
}
like image 53
timray Avatar answered Oct 16 '22 20:10

timray