NagRock / ts-mockito

Mocking library for TypeScript
MIT License
977 stars 93 forks source link

Field mocking fails when mock is injected into Angular component #161

Closed tamas-szekeres closed 5 years ago

tamas-szekeres commented 5 years ago

I have written a quick test to verify that field mocking works as expected when nothing special is around it:

it('plain mock', () => {
  const translateMock = mock(TranslateService);
  const translateInstance = instance(translateMock);
  when(translateMock.currentLang).thenReturn('de');
  when(translateMock.instant('aa')).thenReturn('bb');
  console.log("currentLang-direct", translateInstance.currentLang);
  console.log("instant-direct", translateInstance.instant('aa'));
});

Which works as expected:

    console.log test.spec.ts:12
      currentLang-direct de
    console.log test.spec.ts:13
      instant-direct bb

Then a second one using the testbed:

it('through angular', () => {
  const translateMock = mock(TranslateService);
  const translateInstance = instance(translateMock);
  when(translateMock.currentLang).thenReturn('de');
  when(translateMock.instant('aa')).thenReturn('bb');

  TestBed.configureTestingModule({
    declarations: [AppComponent],
    providers: [
      {provide: TranslateService, useValue: translateInstance}
    ]
  }).compileComponents();

  const componentInstance = TestBed.createComponent(AppComponent).componentInstance;
  console.log("currentLang-indirect", componentInstance.getCurrentLanguage());
  console.log("instant-indirect", componentInstance.getTranslation());
});

With the following component:

import {Component, OnInit} from '@angular/core';
import {TranslateService} from "@ngx-translate/core";

@Component({
  template: 'app.component'
})
export class AppComponent implements OnInit {
  constructor(private translate: TranslateService) {
  }

  ngOnInit(): void {}

  getCurrentLanguage() {
    return this.translate.currentLang;
  }

  getTranslation() {
    return this.translate.instant("aa");
  }
}

Unfortunately the field mock somehow gets lost in the second case:

    console.log test.spec.ts:30
      currentLang-indirect undefined
    console.log test.spec.ts:31
      instant-indirect bb
joshdawson commented 5 years ago

In your TestBed test, if you try useFactory: () => translateInstance instead of useValue. That usually works for me.

tamas-szekeres commented 5 years ago

Looks good, thanks.