javascript - Angular 4 测试用例 .then() 不是一个函数

标签 javascript angular jasmine karma-jasmine

我正在尝试使用测试用例覆盖组件中的服务调用,如下所述。 但在运行 ng test 时出现错误,如下所示:

Failed: this.monthService.getMonthView(...).then is not a function TypeError: this.monthService.getMonthView(...).then is not a function

服务:(MonthService.ts)

getMonthViewMonthService内部的服务调用

 getMonthView(forecastMonth: string): Promise<any[]> {
        const options = new RequestOptions({ headers: this.headers });
        const url = this.BaseUrl + forecastMonth;
        return this.http.get(url, options)
            .toPromise()
            .then(response => response.json() as any[])
            .catch(this.handleError);
    }

组件:(MonthComponent.ts)

MonthService 被导入并注入(inject)到 MonthComponent.ts

 loadDataOnMonthViewClicked(forecastMonth) {
            this.monthService.getMonthView(forecastMonth)
                .then(response =>
                    this.result = response
                );
        }

测试套件:

 beforeEach(() => {
        /**
          * Ref:https://angular.io/guide/testing#!#component-fixture
          */
        fixture = TestBed.createComponent(MonthComponent);
        component = fixture.componentInstance;        
        myService = TestBed.get(MonthService );        
        //fixture.detectChanges();
    });
    it('should be created', () => {
        expect(component).toBeTruthy();
    }); 

    fit('should test loadDataOnMonthViewClick', async(() => { 
        let data=["10","20","30"];
        spyOn(component.monthService, 'getMonthView').and.returnValue(result);        
        component.loadDataOnMonthViewClicked('Jan');
        fixture.detectChanges();
        expect(component.result).toBe(data);
    }));

最佳答案

这是我为使其发挥作用所做的工作。

// the component

import { Component, OnInit } from "@angular/core";
import { MonthService } from "./month.service";

@Component({
  selector: "app-root",
  template: "",
})
export class AppComponent {
  result = undefined;
  constructor(private monthService: MonthService) { }

  loadDataOnMonthViewClicked(forecastMonth) {
    this.monthService
      .getMonthView(forecastMonth)
      .then(response => (this.result = response));
  }
}

和服务

// the service

import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import "rxjs/add/operator/toPromise";

@Injectable()
export class MonthService {
  constructor(private http: Http) { }

  getMonthView(_forecastMonth: string) {
    return this.http
      .get("http://jsonplaceholder.typicode.com/posts/1")
      .toPromise()
      .then(response => response.json())
      .catch(console.error);
  }
}

和测试

import { TestBed, async, ComponentFixture } from "@angular/core/testing";
import { AppComponent } from "./app.component";
import { MonthService } from "./month.service";
import { HttpModule } from "@angular/http";
import { Observable } from "rxjs/Observable";
import "rxjs/add/observable/of";

describe("AppComponent", () => {
  let fixture: ComponentFixture<AppComponent>;
  let component: AppComponent;
  let myService;

  beforeEach(
    async(() => {
      TestBed.configureTestingModule({
        providers: [MonthService],
        declarations: [AppComponent],
        imports: [HttpModule],
      }).compileComponents();
    }),
  );

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    myService = fixture.debugElement.injector.get(MonthService);
    fixture.detectChanges();
  });

  it(
    "should test loadDataOnMonthViewClick",
    async(() => {
      let data = ["10", "20", "30"];
      spyOn(myService, "getMonthView").and.callFake(() =>
        Promise.resolve(data),
      );
      component.loadDataOnMonthViewClicked("Jan");
      fixture.whenStable().then(() => {
        expect(component.result).toBe(data);
      });
    }),
  );
});

但我建议完全模拟该服务,例如

providers: [
  { provide: FetchDataService, useClass: FetchDataServiceMock }
],

关于javascript - Angular 4 测试用例 .then() 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46783182/

相关文章:

javascript - 如何在 NodeJS 中获取 UTC 日期对象?

angular - 如何获取 AgGrid 的选定行列索引(Angular)

javascript - Jasmine + TypeScript,找不到Spy类的withArgs()方法

javascript - 我应该将 Jasmine 文件存储在 Symfony 项目中的什么位置?

jasmine - 如何使用 Protractor 测试页面上不存在某个元素?

javascript - Three.js 中的相机闪光灯

Java servlet和Ajax上传文件进度条

javascript - 当我删除 HTML 中的表单时,为什么我的 WebSocket 不起作用?

Angular 4 与 React 混合

javascript - Angular http post 通过服务将数据返回给组件