简体   繁体   English

无法测试嵌套的 function 是否在 Jasmine 中被调用

[英]Not able to test if nested function is called in Jasmine

I'm learning to write test cases in jasmine,I was trying to create a test case to check if the functions defined within the function are called我正在学习在 jasmine 中编写测试用例,我试图创建一个测试用例来检查 function 中定义的函数是否被调用

My function that I'm trying to test is as follows,and the sData method is written in another component that is being extended by current component我正在尝试测试的 function 如下,并且 sData 方法写在当前组件正在扩展的另一个组件中

public rPage() {
    this.sData();
    this.setupPage()
  }

the test case that i wrote is as below我写的测试用例如下

   it('should check if  sData is called', () => {
    const sData = spyOn<any>(component, 'sData');
    component.rPage();
    fixture.detectChanges();
    expect(sData).toHaveBeenCalled();
  });

have created spy on rpage already in beforeeach as below在 beforeeach 中已经在 rpage 上创建了间谍,如下所示

 beforeEach(() => {
    fixture = TestBed.createComponent(BasicComponent);
    component = fixture.componentInstance;
    spyOn(component, 'rPage');
    fixture.detectChanges();
  });

still when i run the test,the test case fails saying "Expected spy sData to have been called.",where I'm going wrong仍然当我运行测试时,测试用例失败说“预期的间谍 sData 已被调用。”,我错了

If you want to make sure that sData is called, you need to properly call rPage .如果要确保调用sData ,则需要正确调用rPage By having spyOn(component, 'rPage');通过spyOn(component, 'rPage'); in your beforeEach , you are effectively telling all your tests to never run rPage for real, and to just mock it.在您的beforeEach中,您实际上是在告诉所有测试永远不要真正运行rPage ,而只是模拟它。 So therefore it is never called for real, an sData really will never be called.因此,它永远不会被真正调用, sData真的永远不会被调用。

In order for you to check rPage properly, you need to not use a spy in the test that tests it, or add .and.callThrough() to the spy to the function is actually called为了让您正确检查rPage ,您不需要在测试它的测试中使用间谍,或者将.and.callThrough()添加到间谍中,以实际调用 function

You are calling the function then defining the spy, this is what is causing the problem.您正在调用 function 然后定义间谍,这就是导致问题的原因。 You need to define the spy then call the function.您需要定义间谍然后调用 function。

Try below试试下面

  it('should check if sData is called', () => {
    const toggleSpy = spyOn<any>(component, 'sData');
    component.rPage();
    fixture.detectChanges();
    expect(toggleSpy).toHaveBeenCalled();
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM