繁体   English   中英

this.ProductDataService.getAllProducts 不是使用 jasmine-karma 的函数

[英]this.ProductDataService.getAllProducts is not a function using jasmine-karma

我正在 angular7 中运行单元测试用例,即 jasmine-karma。 我收到这个错误 -

ProjectManagementComponent 应该使用服务中的 ProjectList

类型错误:this.ProjectManagementService.getProject 不是函数

如果我使用 useClass 而不是 useValue ,则会出现错误 -

[对象 ErrorEvent] 抛出

我尝试了多种选择,但无法通过互联网弄清楚。

app.component.spec.ts

describe('ProjectManagementComponent', () => {
  let comp: ProjectManagementComponent;
  let fixture: ComponentFixture<ProjectManagementComponent>;
  let de: DebugElement;
  let el: HTMLElement;

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ProjectManagementComponent],
      imports: [HttpClientModule, RouterTestingModule, RouterModule, NgbModule, NgxPaginationModule, FormsModule, ReactiveFormsModule, BrowserModule,],
      providers: [{ provide: ProjectManagementService, useClass: ProjectManagementService },
               {provide: ProductsService, useClass: ProductsService}]
    })
      .compileComponents().then(() => {
        fixture = TestBed.createComponent(ProjectManagementComponent);
        comp = fixture.componentInstance;
       de = fixture.debugElement.query(By.css('form[id=addProjectCreationData]'))
        el =de.nativeElement;
      });
  }));


it("should use the ProjectList from the service", () => {
    console.log("Create a Project Service")
    const projectService = fixture.debugElement.injector.get(ProjectManagementService);
    fixture.detectChanges();
    expect(projectService.getProject()).toEqual(comp.getResponse);
  });
});

app.component.service.stub.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { config } from "config";
const baseUrl: string = config.url;


@Injectable()
export class ProjectManagementServiceStub {
    constructor(private http: HttpClient) { }
              
    getProject(url) :Observable<any>{
        
        return this.http.get(url )
            .pipe(map(Response => Response))
                
    }

}

更正您的providers部分,因为您没有使用您创建的stubProjectManagementServiceStub

 providers: [{ provide: ProjectManagementService, useClass: ProjectManagementServiceStub },
             {provide: ProductsService, useClass: ProductsService}] // <--- FIX  this as well, you need to inject "stub"

旁注:在it下面的块似乎没有意义。

it("should use the ProjectList from the service", () => {
    console.log("Create a Project Service")
    const projectService = fixture.debugElement.injector.get(ProjectManagementService);
    fixture.detectChanges();
    expect(projectService.getProject()).toEqual(comp.getResponse);
  });
});

这缺少单元测试的本质,因为您正在测试属于service不是component projectService.getProject()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM