[英]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. 我正在尝试在我的angular 4项目中为使用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
ReferenceError:未定义gapi
How can I mock the gapi global variable (and its calls to load and auth2)? 我如何模拟gapi全局变量(及其对load和auth2的调用)?
Here are my 2 classes (implementation and test class) 这是我的2个类(实现和测试类)
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();
});
});
I had a similar problem with the Google API const. 我在使用Google API const时遇到了类似的问题。
@estus is correct; @estus是对的; you can define the global variable on window within the
beforeEach
block: 您可以在
beforeEach
块中的窗口上定义全局变量:
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
window['gapi'] = {
load() {
return null;
},
anotherFunction() {
return null;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.