如何使用 Karma 在组件测试中存根 Google gapi 全局变量

Aym*_*ric 6 unit-testing google-api-js-client karma-jasmine angular

我正在尝试在我的 angular 4 项目中为使用 Google gapi 的服务设置测试。我遇到的问题是变量是全局声明的,但没有被模拟,因此当我运行测试时,我收到以下错误:

参考错误:gapi 未定义

如何模拟 gapi 全局变量(及其对 load 和 auth2 的调用)?

这是我的 2 个类(实现和测试类)

组件类

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 {...}
Run Code Online (Sandbox Code Playgroud)

测试班

describe('RegisterGoogleComponent', () => {

  beforeEach(async(() => {

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

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
Run Code Online (Sandbox Code Playgroud)

tim*_*ray 7

我对 Google API const 有类似的问题。

@estus 是正确的;您可以在beforeEach块内的窗口上定义全局变量:

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

  window['gapi'] = {
    load() {
      return null;
    },
    anotherFunction() {
      return null;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)