【问题标题】:Angular Karma-Jasmine Cannot read property 'get' of undefinedAngular Karma-Jasmine 无法读取未定义的属性“获取”
【发布时间】:2018-02-02 08:48:52
【问题描述】:

example.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, URLSearchParams, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { environment as ENV } from '../../environments/environment';
import { SharedService } from './shared.service';

video(id): Observable<any> {
let sessionId = this.sharedService.sessionId();

return this.http.get(ENV.api_url + '&videoId=' + id)
      .map(this.extractData)
      .catch(this.handleError);

}

example.service.spec.ts

import { async, ComponentFixture, TestBed } from 

'@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { Http, HttpModule } from '@angular/http';
import { MockBackend } from '@angular/http/testing';


describe('VideosComponent', () => {
  let component: VideosComponent;
  let fixture: ComponentFixture<VideosComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [ VideosComponent ],
      providers: [
        {
          provide: Http,
          deps: [MockBackend]
        },
      ]
    })
    .compileComponents();
  }));

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

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

我在尝试运行测试时遇到 TypeError: Cannot read property 'get' of undefined。 我对单元测试很陌生,但我在这里发布了单元测试文件和返回“get”的服务的代码。

【问题讨论】:

    标签: angular unit-testing karma-jasmine


    【解决方案1】:

    首先你的服务是没有服务的。 我真的推荐阅读https://angular.io/tutorial/toh-pt6#heroes-and-http

    在那里你可以看到你需要创建一个constructor(private http: Http) { },你的http现在是undefined

    【讨论】:

    • 我知道,但我没有在这里粘贴完整的服务
    • 那么请这样做。
    • 我认为问题出在测试文件而不是服务上!
    • 好的,如果您的服务运行良好,请使用注入和 spyOn。 inject([VideoService], (videoService: VideoService) => { spyOn(videoService, 'method').and.returnValue(yourVideo);
    • 抱歉,我是 Angular 新手,你能在任何地方更新或给我完整的 sn-p 吗?谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 2019-02-07
    • 1970-01-01
    • 2021-02-27
    相关资源
    最近更新 更多