【问题标题】:Testing an observable on a service property using jasmine.SpyObj - Angular/Jasmine使用 jasmine.SpyObj 测试服务属性上的 observable - Angular/Jasmine
【发布时间】:2020-09-05 20:15:45
【问题描述】:

我正在尝试测试绑定到内联属性而不是服务上的方法的可观察对象,但是我似乎找不到任何关于如何在 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 方法content$ 中的所需值

【问题讨论】:

  • 不应该有{ provide: ContentService, useValue: { content$: spy() } } 而不是ValueService 吗?据我所知,父母注入ContentService

标签: javascript angular typescript jasmine


【解决方案1】:

我在这些场景中所做的是将实例属性添加到 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*/);

【讨论】:

  • 传奇就像一个魅力,我假设没有办法直接使用 spyObj 和 spyOn.return 来实现这一点?
  • 我就是这样做的。我记得做过一些简短的研究,我认为这是最好的选择。如果您想四处玩耍,甚至想出适合您的更好方法,请随意。
  • 不不,我对这种方法很满意,只是好奇,给了你答案:)
猜你喜欢
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-04
  • 1970-01-01
  • 2016-07-09
  • 1970-01-01
相关资源
最近更新 更多