【问题标题】:spyOn function not being called Jasmine Angular 2spyOn 函数未被称为 Jasmine Angular 2
【发布时间】: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


【解决方案1】:

我已经让它与以下内容一起工作:

  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)

调用函数,这是处理这种事情的正确方法吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多