使用 jasmine.SpyObj - Angular/Jasmine 在服务 属性 上测试可观察对象

Testing an observable on a service property using jasmine.SpyObj - Angular/Jasmine

我正在尝试测试绑定到内联 属性 的可观察对象,而不是服务上的方法,但是我似乎找不到任何有关如何 return 的示例SpyObj 本身或通过 spyOn/SpyOnProperty 调用的正确值。

// ContentService 
readonly content$ = this.http.get('www.testContent.com');

// ParentService
constructor(private readonly contentService: ContentService){
  this.loadContent();
}

// This could return different content dependent on locale for example
loadContent(){
  this.contentService.content$.subscribe((response)=>{
    // Handle response
  })
}

// Unit test 
let service: ParentService;
let contentServiceSpy: jasmine.SpyObj<ContentService>;

beforeEach(() => {
  const spy = jasmine.createSpyObj('ContentService', [], {
    // Returns cannot read subscribe of undefined
    content$: of()
  });

  TestBed.configureTestingModule({
    providers: [
      ParentService,
      { provide: ContentService, useValue: spy }
    ]
  });

  service = TestBed.get(ParentService);
  contentServiceSpy = TestBed.get(ContentService) as jasmine.SpyObj<ContentService>;
});

我看过几个关于将 spyOnProperty 与 get 和 set 方法一起使用的示例,但这不是这里发生的事情,我是在 jasmine.SpyObj 上错误地声明了它,还是我有一个特定的 jasmine 方法' m 缺少 return content$

中的所需值

我在这些场景中所做的是将一个实例 属性 添加到 createSpyObj 本身。

// Unit test 
let service: ParentService;
let contentServiceSpy: jasmine.SpyObj<ContentService>;
let mockContent$ = new BehaviorSubject(/* content mock goes here*/);

beforeEach(() => {
  const spy = jasmine.createSpyObj('ContentService', ['loadContent']);

  spy.content$ = mockContent$; // add the instance property itself

  TestBed.configureTestingModule({
    providers: [
      ParentService,
      { provide: ValueService, useValue: spy }
    ]
  });

  service = TestBed.get(ParentService);
  contentServiceSpy = TestBed.get(ContentService) as jasmine.SpyObj<ContentService>;
});

以后,如果你想改变content$的值,你可以mockContent$.next(/* new mock content goes here*/);