【发布时间】:2017-10-04 10:22:00
【问题描述】:
在我的 Angular 组件的设置中,我有一个功能:
populateForm(id:String, index:number){
let blogs = this.blogsService.returnBlogs()
blogs.map((blog:Blog)=>{
blog._id === id ? this.blogsService.populateForm.next({blog:blog, index:index}) : blog._id = blog._id;
})
}
我已经设置了一个关于按钮单击的测试,它调用 populateForm 函数,该函数调用 returnBlogs 函数,从一个服务给我一个数组来操作。
但我无法监视 returnBlogs 函数:
it('Should be able to click element and call PopulateForm function with correct parameters', () => {
let blogs = [{_id1: 'xyz', title: 'title1', vidUrl: 'XpiipWULkXk'}, {_id1: 'abc', title: 'title2', vidUrl: 'XpiipWULkXk'}]
blogsService = TestBed.get(BlogsService)
component.blogs = blogsTest
fixture.detectChanges();
let spy = spyOn(blogsService, 'returnBlogs').and.returnValue(blogs);
let domEl = fixture.nativeElement.querySelector('.blog-thumb');
domEl.click();
expect(component.populateForm).toHaveBeenCalledWith('xyz', 1);
expect(spy).toHaveBeenCalled();
});
我收到一个错误:
预期的间谍 returnBlogs 已被调用。
任何指针都将不胜感激,我正在努力掌握应该和不应该测试的内容
【问题讨论】:
-
我相信
TestBed.get会为您创建一个新的服务实例,而不是组件拥有的那个。相反,创建const serviceSpy = jasmine.createSpyObj('BlogService', ['returnBlogs']);并使用注入器{ provide: BlogsService, useValue: serviceSpy }。
标签: javascript angular jasmine