jeudi 16 mars 2017

Angular 2: Replace injected Renderer with jasmine spy object in component shallow tests

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;
                });
            }));
       ... 
       });

Debugging the created component with karma shows that zippyServiceMock is being injected instead of ZippyService. but instead of rendererMock, the real Renderer is being injected. How can I inject rendererMock instead of the real one in my tests?

Aucun commentaire:

Enregistrer un commentaire