zippy.component.ts:
import { Component } from '@angular/core';
import {ZippyService} from '../services/zippy.service'
import {Renderer} from '@angular/core'
@Component({
selector: 'app-zippy',
templateUrl: './zippy.component.html',
styleUrls: ['./zippy.component.less']
})
export class ZippyComponent {
doNotShow:boolean = true;
text:string;
constructor(private zippyService:ZippyService, private renderer:Renderer) {
this.text = this.zippyService.getText();
}
toggleDisplay() {
this.doNotShow = !this.doNotShow;
}
}
zippy.component.spec.ts
describe('Zippy component shallow tests', ()=>{
let fixture:ComponentFixture<ZippyComponent>,
component: ZippyComponent;
let rendererMock = jasmine.createSpyObj('rendererMock', ['myFakeMethod']);
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ZippyComponent, ZippyPipe],
providers: [
{ provide: ZippyService, useValue: zippyServiceMock },
{ provide: Renderer, useValue: rendererMock }
],
schemas: [NO_ERRORS_SCHEMA]
});
TestBed.compileComponents().then(()=>{
fixture = TestBed.createComponent(ZippyComponent);
component = fixture.componentInstance;
});
}));
...
});
使用 karma 调试创建的组件表明正在注入(inject) zippyServiceMock 而不是 ZippyService。 但是注入(inject)的不是 rendererMock,而是真正的渲染器。 如何在我的测试中注入(inject) rendererMock 而不是真正的?
最佳答案
您正在覆盖整个模块的渲染器。但是你应该只为你的组件覆盖渲染器:
TestBed.configureTestingModule({
declarations: [ZippyComponent, ZippyPipe],
providers: [
{ provide: ZippyService, useValue: zippyServiceMock }
],
schemas: [NO_ERRORS_SCHEMA]
})
.overrideComponent(ZippyComponent, {
set: {
providers: [
{provide: Renderer, useValue: rendererMock}
]
}
});
TestBed.compileComponents().then(()=>{
fixture = TestBed.createComponent(ZippyComponent);
component = fixture.componentInstance;
});
关于 Angular 2 : Replace injected Renderer with jasmine spy object in component shallow tests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42838164/