简体   繁体   English

Angular 单元测试: Function 未被调用

[英]Angular unit testing: Function not being called

I am trying to unit test my service and cannot seem to get it working.我正在尝试对我的服务进行单元测试,但似乎无法使其正常工作。 The concept is that when setEmployees() is called with an empty array, the service fetches employees from the server.这个概念是,当使用空数组调用setEmployees()时,服务会从服务器获取员工。

Service服务

  setEmployees( employees : Employee[] ) {
    console.log("Setting employees...", employees)
    if (employees && employees.length) {
      this.employees.next(employees)
      this.storage.set('employees', employees);
    } else {
      this.getEmployees().subscribe()
    }
  }

  getEmployees() {
    console.log("getting employees...")
    let url = `${this.base_url}/employees`;
    return this.http.get<Employee[]>(url).pipe(
      tap(employees => {
        console.log("got em", employees)
        this.setEmployees(employees)
        this.storage.set('employees', employees)
      })
    )
  }

  returnEmployees() : IEmployee[] {
    return Object.assign([], this.employees.getValue())
  }

Test测试

it('should set employees correctly', fakeAsync(() => {
  let dummy = [{id: 1, name: 'Jeremy'}, {id: 2, name: 'Paige'}]
  spyOn(employeeService, 'getEmployees').and.returnValue(of(dummy));
  employeeService.setEmployees([]);
  tick();
  expect(employeeService.returnEmployees()).toEqual(dummy)
}))

Test Response测试响应

Expected $.length = 0 to equal 2.
Expected $[0] = undefined to equal Object({ id: 1, name: 'Jeremy' }).
Expected $[1] = undefined to equal Object({ id: 2, name: 'Paige' }).

It's also worth noting that the console.log() statements don't occur in the expected order.还值得注意的是, console.log()语句没有按预期顺序出现。 When running this test I see the following in the console:运行此测试时,我在控制台中看到以下内容:

getting employees...
Setting employees... []

...when I would've expected to see: ...当我期望看到:

Setting employees... []
getting employees...
got em [{id: 1, name: 'Jeremy'}, {id: 2, name: 'Paige'}]
Setting employees... [{id: 1, name: 'Jeremy'}, {id: 2, name: 'Paige'}]

Clearly something isn't firing as expected but I'm not sure where the issue lies.显然有些东西没有按预期触发,但我不确定问题出在哪里。

There are a few catches with the test of async functions, your snipped seems susceptible to some of them... I would suggest a more standard usage of Observables.异步函数的测试有一些问题,你的剪辑似乎容易受到其中一些的影响......我建议更标准地使用 Observables。 And using ReplaySubject to keep the latest employee Array value in the service.并使用ReplaySubject将最新的员工数组值保留在服务中。 Something Like:就像是:

service:服务:

employees$ = new ReplaySubject<Employee[]>(); 

setEmployees( employees : Employee[] ) {
  if (employees && employees.length) {
    this.employees$.next(employees)
  } else {
    this.getEmployees()
  }
}

getEmployees() {
  let url = `${this.base_url}/employees`;
  this.http.get<Employee[]>(url).pipe(take(1))
      .subscribe(employees => this.employees$.next(employees))
}

your test:你的测试:

it('should set employees correctly', done => { // the 'done' helper function ensures necessary async callbacks are waited for
  let dummy = [{id: 1, name: 'Jeremy'}, {id: 2, name: 'Paige'}]

  employeeService.setEmployees(dummy)

  employeeService.employees$.subscribe(employees => {
    expect(employees).toEqual(dummy) // you might want to do a better element comparison here
    done()
  })
}))

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

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