首页 > 解决方案 > 错误: : 找不到对象来监视 Foo()

问题描述

我试图在我的 LoyaltyService 中创建一个简单的 Foo 方法。

    public Foo(): Observable<string> {
    return of('1');
  }

像这样在spec.ts中注入它 -

  //const loyaltyService: LoyaltyService = TestBed.inject(LoyaltyService);
  const loyaltyService: LoyaltyService = fixture.debugElement.injector.get(LoyaltyService);
  spyOn(loyaltyService, 'test').and.returnValue(of('1'));

但是出现错误:错误::找不到用于监视 Foo() 的对象。我已经尝试过 TestBed.inject 方法和 injector.get 方法。

标签: angularunit-testingjasminekarma-jasmine

解决方案


AngularJS当我们在和stub promises使用中编写测试时,SpyOn我们做了这样的事情:

spyOn(someService,'get').and.returnValue(deferred.promise);

上面的代码是完全有效的——不像observables,promises总是异步的。但是如何测试Observables?使用jasmine-marbles是这里最好的部分。所以尝试这样的事情:

app-foo.component.ts

@Component({
  selector: 'app-foo',
  template: `
    <div class="foo">
      {{ foo | async }}
    </div>
  `
})
export class FooComponent implements OnInit {
  foo: string = "";

  constructor(private fooService: FooService) { }

  ngOnInit() {
    this.fooService.get().subscribe(res => {
      this.foo = res;
    });
  }

}

app-foo.component.spec.ts

import { cold, getTestScheduler } from 'jasmine-marbles';

const fooServiceStub = {
  get() {
    const foo$ = cold('--x|', { x: `1` });
    return foo$
  }
};

describe('FooComponent', () => {

  it('should work', () => {
    const foo = element.querySelectorAll('.foo');
    getTestScheduler().flush(); // flush the observables
    fixture.detectChanges();
    expect(element.querySelectorAll('.foo').length).toEqual(1);
  });

});

有关observables测试的更多信息,请参阅以下文章:

在 Angular 中测试 Observables

如何测试 Observables


推荐阅读