我正在用 Jasmine 为 Angular 2 组件编写单元测试。当我的组件被实例化时,我想测试我的文档元标记是否设置为特定值。我的组件:
import { Component } from '@angular/core';
import { Meta } from '@angular/platform-browser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
constructor (
private meta: Meta
) {
// Only 2 objects of metatag for example
this.meta.addTags([
{httpEquiv: 'X-UA-Compatible', content: 'IE=edge', title: '123'},
{name: 'keywords', content: 'My keywords'}
], true)
}
}
这是我为测试编写的内容,但它不起作用。
import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { Meta } from '@angular/platform-browser';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
let meta: Meta;
let metatags: HTMLMetaElement[];
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AppComponent ],
providers: [ { provide: Meta } ],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
fixture.detectChanges();
});
it(`should have a metatag name=keywords with content='My keywords'`, () => {
meta = TestBed.get(Meta);
expect(meta.getTag('name=keywords')).toBe('My keywords');
});
it(`should have a metatag httpEquiv=X-UA-Compatible with content: 'IE=edge' and title: '123'`, () => {
metatags = TestBed.get(Meta);
expect(metatags.getTags('httpEquiv=X-UA-Compatible').content).toBe('IE=edge');
expect(metatags.getTags('httpEquiv=X-UA-Compatible').title).toBe('123');
});
});
当我启动测试时,它会在控制台中给出一些错误:
src/app/app.component.spec.ts:27:47 中的错误 - 错误 TS2345:“我的关键字”类型的参数不可分配给“预期”类型的参数。
27 expect(meta.getTag('name=keywords')).toBe('我的关键字');
src/app/app.component.spec.ts:32:21 - 错误 TS2339:“HTMLMetaElement[]”类型上不存在属性“getTags”。
32 期望(metatags.getTags('httpEquiv=X-UA-Compatible').content).toBe('IE=edge');
src/app/app.component.spec.ts:33:21 - 错误 TS2339:“HTMLMetaElement[]”类型上不存在属性“getTags”。
33 期望(metatags.getTags('httpEquiv=X-UA-Compatible').title).toBe('123');