简体   繁体   中英

Access service from Angular component test

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)
        }
      })
    )
  }

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)
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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