Home > other >  Access service from Angular component test
Access service from Angular component test

Time:11-18

I am testing my component and did not want to have to create a mock service so instead I injected the real service. I wanted to spy on one of the service's functions in a test but was getting a Typescript error: argument of type 'string' is not assignable to parameter of type 'never'..

Is there a correct way of doing this without mocking the entire service?

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ DocumentsPage ],
      imports: [HttpClientTestingModule,],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [
        ClientDocService
      ]
    })
    .compileComponents();
  }));

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

  describe('loadClientDocuments', () => {
    it('should call clientDocService.fetchClientAndSignedDocuments', () => {

      // This is the error
      const spy = spyOn(ClientDocService, 'fetchClientAndSignedDocuments')

      component.loadClientDocuments()
      expect(spy).toHaveBeenCalledTimes(1)
    })
  })
});

Here's the function:

fetchClientDocs( clientId : number, updateDocs: boolean = true ) : Observable<IClientDoc[]> {
    const url = `${this.base_url}/clients/${clientId}/client_docs`
    return this.http.get<IClientDoc[]>(url).pipe(
      tap( clientDocs => {
        clientDocs.forEach(doc => {
          doc.fileKey = decodeURIComponent(doc.fileKey)
        })

        if (updateDocs) {
          this.setClientDocs(clientDocs)
          this.setMergedDocuments([], clientDocs)
        }
      })
    )
  }

CodePudding user response:

Like possum mentioned, I would use TestBed.inject to get a handle on the service.

it('should call clientDocService.fetchClientAndSignedDocuments', () => {
      // !! Get a handle on the service
      const clientDocService = TestBed.inject(ClientDocService);
      // !! spy on the one we have
      const spy = spyOn(clientDocService, 'fetchClientAndSignedDocuments')

      component.loadClientDocuments()
      expect(spy).toHaveBeenCalledTimes(1)
    })
  • Related