【发布时间】:2018-06-01 01:27:12
【问题描述】:
我试图弄清楚如何模拟注入到组件中的ElementRef。我的组件如下:
app.component.ts:
import { Component, ElementRef } from '@angular/core';
import { AppService } from './app.service';
@Component({
selector: 'app-root',
templateUrl: './app/app.component.html',
styleUrls: ['./app/app.component.css']
})
export class AppComponent {
title = 'app works!';
constructor(private _elementRef: ElementRef, private _appService: AppService) {
console.log(this._elementRef);
console.log(this._appService);
}
}
我的测试规范如下:
app.component.spec.ts:
import { TestBed, async } from '@angular/core/testing';
import { ElementRef, Injectable } from '@angular/core';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
@Injectable()
export class MockElementRef {
nativeElement: {}
}
@Injectable()
export class MockAppService {
}
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
providers: [
{provide: ElementRef, useClass: MockElementRef},
{provide: AppService, useClass: MockAppService}
]
}).compileComponents();
}));
...
});
运行测试时,console.log 在app.component.ts 的构造函数中的输出为:
如您所见,它注入的是MockAppService,而不是MockElementRef(尽管它们都以相同的方式模拟)。
这个SO post suggests 可以像设置任何其他模拟一样设置它,但是我注意到这是针对 Angular 2 的 - 所以我想知道 Angular 4 中的情况是否发生了变化?
可以在here 找到具有上述代码和 Jasmine 测试的 Plunker。运行 Plunker,然后单击“运行单元测试”链接以启动单元测试。控制台输出可以在开发者工具/Firebug中观察到。
【问题讨论】: