【问题标题】:should call function inside ngOnInit应该在 ngOnInit 中调用函数
【发布时间】:2020-03-20 10:16:34
【问题描述】:

我是角度测试的新手,我想知道如何测试调用 ngOnInit 时调用的函数。下面是我要测试的代码

it('should call TestMethod method inside ngOnInit' , async() => {
    spyOn(component , 'TestMethod')
    fixture.detectChanges()
    expect(component.TestMethod).toHaveBeenCalled()
  })

下面是我遇到的错误

Expected spy TestMethod to have been called.

BeforeEach 在下面

beforeEach(() => {
    fixture = TestBed.createComponent(CreateRoomsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

【问题讨论】:

  • TestMethod 是私有的吗?如果是这样 spyOn(component , 'TestMethod')
  • 它是一个公共函数。
  • 好的,你需要添加 .and.callthrough() 来绕过它。
  • 喜欢这个 spyOn(component , 'TestMethod').and.callthrough() ?

标签: javascript angular unit-testing jasmine


【解决方案1】:

将 spy 对象分配给一个变量并在期望函数中使用该变量

    it('should call TestMethod method inside ngOnInit' , async() => {
    const obj = spyOn(component , 'TestMethod')
    fixture.detectChanges()
    expect(obj).toHaveBeenCalled()
  })

【讨论】:

  • 在下面得到这个:预期的间谍 TestMethod 已被调用。错误:预期的间谍 TestMethod 已被调用。
【解决方案2】:

我找到了解决方案,它正在工作。

it('should call TestMethod method inside ngOnInit' , async() => {
    const obj = spyOn(component , 'TestMethod')
    component.ngOnInit()
    expect(obj).toHaveBeenCalled()
  })

【讨论】:

    猜你喜欢
    • 2018-12-14
    • 1970-01-01
    • 2022-01-14
    • 2020-08-23
    • 2017-01-22
    • 1970-01-01
    • 2018-11-14
    • 2020-11-07
    • 2018-07-30
    相关资源
    最近更新 更多