我找不到如何测试我的角度指令..。
google-places.directive.ts
import { Directive, ElementRef, EventEmitter, NgZone, Output } from '@angular/core';
import {} from '@types/googlemaps';
@Directive({
selector: '[appGooglePlace]'
})
export class AppGooglePlaceDirective {
@Output() placeChange: EventEmitter<any> = new EventEmitter<any>();
constructor(private el: ElementRef, private ngZone: NgZone) {
const autocomplete = new google.maps.places.Autocomplete(this.el.nativeElement);
autocomplete.addListener('place_changed', () => {
this.ngZone.run(() => {
const place = autocomplete.getPlace();
this.placeChange.emit(place);
});
});
}
}mypage.component.html
<input type="search" appGooglePlace (placeChange)="placeChanged($event)"/>它在应用程序中运行得很好,但不知道用ng测试,我不知道怎么写.
我有个错误:
"ReferenceError: google没有定义“
以及dev控制台中的以下错误:
从源'https://maps.googleapis.com/maps/api/js?key=XXXXX&libraries=places‘访问脚本的'http://localhost:9876’已被CORS策略阻止:请求的资源上没有“访问控制-允许-原产地”标题。因此,“http://localhost:9876”源是不允许访问的。
第一种情况是,如果我没有在指令中导入@type/googlemaps,那么行为也是相同的,但我不知道为什么在测试中会出现这个错误。我需要在因果报应/茉莉花的某个地方定义类型吗?
第二,我的spec.ts可以调用真正的google吗?如果我想测试"placeChange“的返回?
这是我的单元测试计划:
google-places.directive.spec.ts
import { By } from '@angular/platform-browser';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Component, ElementRef, DebugElement, NgZone } from '@angular/core';
import { AppGooglePlaceDirective } from './google-place.directive';
import {} from '@types/googlemaps';
@Component({
template: `<input type="search" appGooglePlace (placeChange)="placeChanged($event)" name="test"/>`
})
class TestGooglePlaceComponent {}
export class MockElementRef extends ElementRef {}
export class MockNgZone extends NgZone {
constructor() {
super({ enableLongStackTrace: false });
}
}
fdescribe('GooglePlaceDirective', () => {
let component: TestGooglePlaceComponent;
let fixture: ComponentFixture<TestGooglePlaceComponent>;
let zone: NgZone;
let searchInput: DebugElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestGooglePlaceComponent, AppGooglePlaceDirective],
providers: [{ provide: NgZone, useClass: MockNgZone }]
});
fixture = TestBed.createComponent(TestGooglePlaceComponent);
component = fixture.componentInstance;
searchInput = fixture.debugElement.query(By.css('input[name=test]'));
zone = new MockNgZone();
});
it('should create an instance', () => {
const directive = new AppGooglePlaceDirective(new MockElementRef(searchInput), zone);
expect(directive).toBeTruthy();
});
});谢谢你的帮助!我真的不知道怎么写这个单元测试..。
发布于 2019-09-25 12:33:38
将其放在您的导入项下:声明var google: any;
https://stackoverflow.com/questions/50378197
复制相似问题