typescript 从Angular 组件测试访问服务

lstz6jyr  于 2022-11-18  发布在  TypeScript
关注(0)|答案(1)|浏览(108)

我正在测试我的组件,不想创建一个模拟服务,所以我注入了真实的的服务。我想在测试中监视服务的一个函数,但是得到了一个Typescript错误:argument of type 'string' is not assignable to parameter of type 'never'. .

是否有一种正确的方法可以在不嘲笑整个服务的情况下执行此操作?

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

函数如下:

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

rt4zxlrg1#

就像前面提到的possum一样,我将使用TestBed.inject来获取服务的句柄。

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

相关问题