TestBed模拟服务

时间:2018-08-15 12:07:39

标签: angular jasmine testbed

我有要使用方法测试的组件

     switchDocumentLanguage(lang, formData):any {
        if (lang === this.currentLang) {
          return null;
        }
        if (formData.invalid && this.currentLang === this.appConfig.defaultLanguage ||
          !this.documentFormData.content && this.currentLang === this.appConfig.defaultLanguage) {

          return this.modalService.open(this.setDefaultModal);

        }

        //(2*)
        if (formData.invalid || !this.documentFormData['content']) {
          return this.modalService.open(this.tabSwitchModal).result.then(() => {
            this.fillFormData(lang);
          }, (reason) => {
          });
        } else {
          return this.fillFormData(lang);
        }
      }

它处于标记为(2 *)的状态

在测试中,我使用存根类ModalService:

    class ModalService {
      open(someArg?: any){
        return {result : Promise.resolve('success')};
      }
    }

    const appConfig =
    {
      defaultLanguage: 'en-US'
    }

我的测试配置如下:

 describe('document.edit component test', () => {

  let component: DocumentEditComponent;
  let fixture: ComponentFixture<DocumentEditComponent>;

  beforeEach(() => {

    TestBed.configureTestingModule({
      imports: [FormsModule],

      schemas: [NO_ERRORS_SCHEMA],
      declarations: [DocumentEditComponent],
      providers: [{provide: AppConfig, useValue: appConfig},
        {provide: DocumentsService, useValue: documentsService},
        {provide: NgbModal, useClass: ModalService},
        {provide: ActivatedRoute, useValue: activatedRoute},
        {provide: BaThemeSpinner, useValue: loader},
        {provide: PopupResultService, useValue: popupResultService},
      ],
    })
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(DocumentEditComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

这是给我错误的测试:

  it("try to leave custom language with invalid form", async(() => {
      const componentService = fixture.debugElement.injector.get(NgbModal);

      let spyObj = spyOn(componentService, "open")

      component.documentFormData.content = "some test values";
      component.currentLang = "es-VE";


      fixture.detectChanges();
      component.switchDocumentLanguage("ru-Ru", {invalid: true})
      fixture.detectChanges();

      fixture.whenStable().then(() => {
        fixture.detectChanges();
        expect(spyObj).toHaveBeenCalled()
      })
    }));

错误文字:

document.edit component test try to leave custom language with invalid form
Failed: Cannot read property 'result' of undefined
TypeError: Cannot read property 'result' of undefined

看起来我的存根类“ ModalService”没有返回任何内容,我试图将console.log()放置在那里,但是它从未出现。 有没有人遇到过类似的东西?

1 个答案:

答案 0 :(得分:1)

因为有人监视它而没有被调用。

可能您可以做的是,用callThrough()

扩展间谍
let spyObj = spyOn(componentService, "open").and.callThrough();

编辑:

您也可以使用returnValue()

let spyObj = spyOn(componentService, "open").and.returnValue({result : Promise.resolve('success')}); 

在这种情况下,将不会调用open(),而是将返回模拟类方法返回的相同结果。如果使用此类,则也不需要模拟类。