TypeError:x(...)。subscribe不是函数

时间:2018-08-20 18:16:07

标签: angular unit-testing components

我正在尝试对在ngOnInit中调用服务方法的组件进行单元测试。当我尝试运行测试时,出现错误:

TypeError:this.adminService.getTestString(...)。subscribe不是函数

以下是参考文件。

app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ISAppAdmin';

  greet: String;
  errorMessage: String;
  constructor(private adminService: AdminService, private router: Router) {}

  ngOnInit() {
    this.adminService.getTestString().subscribe(
      data => this.greet = data,
      error => this.errorMessage = < any > error
    )

    this.adminService.putTestString().subscribe(
      res => console.log(res),
      error => this.errorMessage = < any > error
    )

    console.log("in app");
  }

  onClick() {
    console.log("button clicked");
    this.router.navigate(['admin']);
    console.log("still on same page");
  }

}

app.component.spec.ts

class MockAdminService {
  res = "Hello World";
  getTestString() {
    return this.res;
  }
}

describe('AppComponent', () => {

  let mockAdminService: MockAdminService;
  let fixture: ComponentFixture < AppComponent > ;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      providers: [{
        provide: AdminService,
        useClass: MockAdminService
      }],
      imports: [HttpClientTestingModule, RouterTestingModule],
      declarations: [AppComponent],
    }).compileComponents();

    mockAdminService = new MockAdminService();
    fixture = TestBed.createComponent(AppComponent);
    const component = fixture.componentInstance;
    //mockAdminService = jasmine.createSpyObj(['getTestString']);

  }));
  it('should receive Hello World when getTestString is called', () => {
    let testData = "Hello World";
    fixture.detectChanges();
    expect(this.component.greet).toEqual(testData);
  });
});

admin.service.ts

@Injectable({
  providedIn: 'root'
})
export class AdminService {

  private url = 'http://localhost:8080/rest/test';
  data: String;
  constructor(private http: HttpClient) {}


  getTestString(): Observable < any > {

    const headers = new HttpHeaders({
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': '*'
    });
    return this.http.get("http://localhost:8080/rest/test", {
      headers: headers,
      responseType: 'text'
    });
  }
}

Chrome 65.0 .3325(Windows 10.0 .0) AppComponent should receive Hello World when getTestString is called FAILED
TypeError: this.adminService.getTestString(...).subscribe is not a
function
at AppComponent.ngOnInit(webpack: ///./src/app/app.component.ts?:26:43)
    at checkAndUpdateDirectiveInline(webpack: ///./node_modules/@angular/core/fesm5/core.js?:9547:19)
      at checkAndUpdateNodeInline(webpack: ///./node_modules/@angular/core/fesm5/core.js?:10811:20)
        at checkAndUpdateNode(webpack: ///./node_modules/@angular/core/fesm5/core.js?:10773:16)
          at debugCheckAndUpdateNode(webpack: ///./node_modules/@angular/core/fesm5/core.js?:11406:38)
            at debugCheckDirectivesFn(webpack: ///./node_modules/@angular/core/fesm5/core.js?:11366:13)
              at Object.eval[as updateDirectives](ng: ///DynamicTestModule/AppComponent_Host.ngfactory.js:9:9)
                at Object.debugUpdateDirectives[as updateDirectives](webpack: ///./node_modules/@angular/core/fesm5/core.js?:11358:21)
                  at checkAndUpdateView(webpack: ///./node_modules/@angular/core/fesm5/core.js?:10755:14)

有人可以帮助我理解我的错误以及如何纠正它。

谢谢

1 个答案:

答案 0 :(得分:2)

您的模拟服务未返回可观察到的结果:

import { of } from 'rxjs';

class MockAdminService {
  res = "Hello World";

  getTestString() {
    return of(this.res);
  }
}