Angular 4单元测试获取错误 - 失败:无法读取未定义

时间:2018-02-15 15:43:15

标签: javascript angular unit-testing

我正试图在Angular 4单元测试中获得成功,但是我得到了不同的错误,我收到了错误Failed: Cannot read property 'map' of undefined

我只在服务文件上使用.map(),但我不知道为什么会显示此错误

我想知道如何才能在这次测试中获得成功,如果我是在正确的方向上?

看看我的代码:

我的规格

import { TestBed, async, inject } from '@angular/core/testing';
import { HttpModule } from '@angular/http';
import { of } from 'rxjs/observable/of';
import { fileX } from '../../../models/fileX';
import { fileXService } from '../../../services/fileX.service';
import { fileYfileXComponent } from './fileY-fileX.component';
import { dataService } from '../../../services/data.service';
import { ComponentFixture } from '@angular/core/testing';

describe('fileYfileXComponent', () => {
  let fileXService;
  let myComponent;
  let fixture: any;
  let element;
  let mockHttp: httpClient;

  beforeEach(async(() => {
      mockHttp = jasmine.createSpyObj('http', ['get']);

      TestBed.configureTestingModule({
          declarations: [fileYfileXComponent],
          providers: [
              fileXService,
              dataService,
              { provide: Http, useValue: mockHttp }
          ],
          imports: [HttpModule]
      }).compileComponents();
    }));

  beforeEach(inject([fileXService], s => {
      fileXService = s;
      fixture = TestBed.createComponent(fileYfileXComponent);
      myComponent = fixture.componentInstance;
      element = fixture.nativeElement;
    }));

  it(
    'should get values',
    async(() => {
      const response: fileX[] = [];

      spyOn(fileXService, 'method1').and.returnValue(of(response));

      myComponent.searchdatafileX();

      fixture.detectChanges();

      expect(myComponent.datafileX).toEqual(response);
    })
  );
});

1 个答案:

答案 0 :(得分:1)

目前您正在嘲笑HubWrapperComponent,因此每次调用get时都不会调用您的后端。为了使其正常工作,您需要使用Jasmine的Spy实用程序returnValue来告诉测试在调用http.get时应该返回什么。目前,未指定此内容,因此map上正在调用undefined

在您的spec文件中,在行之后:

mockHub = jasmine.createSpyObj('hubWrapperComponent', ['get']);

添加以下行:

mockHub.get.and.returnValue(// your test response);

根据服务中的代码,我的假设是您期望使用get方法的Observable,因此您的returnValue调用将如下所示:

mockHub.get.and.returnValue(Observable.of(
    { 
      json: () => { 
        return // object with properties you want to test 
      } 
    }
  )
);

此处有关此方法的更多信息:https://jasmine.github.io/api/2.7/Spy_and.html