Expected Response with status: null null for URL: null to equal 'Project11'

后端 未结 1 1067
南笙
南笙 2021-01-29 09:43

I am using angular7 and doing unit testing in jasmine and karma. And I am facing error -

Error: Expected Response with status: null null for URL: null to

相关标签:
1条回答
  • 2021-01-29 10:28

    @Stevy and Shashank, Thanks for your advice. I created a separate service.spec.ts file and tested the service like this -

    fdescribe('ProjectManagementServiceStub', () => {
      let service: ProjectManagementServiceStub;
      let httpMock: HttpTestingController;
      beforeEach(()=>{
    
          TestBed.configureTestingModule({ providers : [
              ProjectManagementServiceStub] , 
    
            imports: [HttpClientModule, HttpClientTestingModule,RouterTestingModule, RouterModule, NgbModule, NgxPaginationModule, FormsModule, ReactiveFormsModule, BrowserModule,]
            ,})
    
            service = TestBed.get(ProjectManagementServiceStub);
            httpMock = TestBed.get(HttpTestingController);
      })
    
    
      it("should be initialized ", inject([ProjectManagementServiceStub], (service1:ProjectManagementServiceStub)=>{
          expect(service1).toBeTruthy();
      }));
    
      it("should fetch data asynchronously", 
         fakeAsync(
             inject(
                 [ProjectManagementServiceStub, HttpTestingController],
                 (service1: ProjectManagementServiceStub, backend : HttpTestingController)=>{
    const url = "http://192.168.x.xxx:3002/api/project/";
    const responseObject :any[]= [{
        projectId: "ID123",
        name: 'Project1'
    }]
    let response = null;
    
    service1.getProject().subscribe(
        (receivedResponse : any) =>{
            response = receivedResponse;
            console.log("Response = ", response)  
    
    
            expect (response).toEqual(responseObject);
            expect(receivedResponse.length).toBe(1);
        },
        (error: any) =>{}
    );
    
    const requestWrapper = backend.expectOne({url :"http://192.168.x.xxx:3002/api/project/" });
    
    
    expect (requestWrapper.request.method). toEqual('GET');
    expect(requestWrapper.cancelled).toBeFalsy();
    
    requestWrapper.flush(responseObject)
    
                 }
             )
         ))
    
         afterEach(() => {
            httpMock.verify();
        });
    
    });
    

    courtsey - https://blog.knoldus.com/unit-testing-of-angular-service-with-httpclient/

    https://alligator.io/angular/testing-httpclient/

    0 讨论(0)
提交回复
热议问题