首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用jasmine.SpyObj - Angular/Jasmine测试服务属性上的可观察值

问使用jasmine.SpyObj - Angular/Jasmine测试服务属性上的可观察值
EN

Stack Overflow用户
提问于 2020-05-20 00:54:33
回答 1查看 731关注 0票数 1

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

代码语言:javascript
复制
// 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>;
});

我已经看到了几个关于在get和set方法中使用spyOnProperty的示例,但这并不是这里发生的事情,是我在jasmine.SpyObj上错误地声明了它,还是缺少一个特定的jasmine方法来从content$返回所需的值

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-20 01:10:12

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

代码语言:javascript
复制
// 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*/);

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61896576

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档