在我的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;
})
}
我已经设置了一个按钮点击测试,它调用了一个调用returnBlogs函数的populateForm函数,该函数从一个服务中获取一个数组来操作。
但我在使用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();
});
我收到错误:
预期的间谍返回博客已被调用。
任何指示都会受到赞赏,我试图掌握应该和不应该测试的内容
答案 0 :(得分:0)
我已经使用了以下内容:
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);
blogsService.returnBlogs()
console.log(blogsService.returnBlogs())
expect(blogsService.returnBlogs).toHaveBeenCalled();
});
在设置间谍后显式调用blogsService.returnBlogs()。
记录后,它会返回我在脚本顶部设置的博客数组。
但我想:
spyOn(blogsService, 'returnBlogs').and.returnValue(blogs)
调用函数,这是处理这种事情的正确方法吗?