无法测试 Jasmine 中是否调用了嵌套函数
Not able to test if nested function is called in Jasmine
我正在学习用 jasmine 编写测试用例,我试图创建一个测试用例来检查函数中定义的函数是否被调用
我要测试的功能如下,sData方法写在另一个组件中,该组件正在被当前组件扩展
public rPage() {
this.sData();
this.setupPage()
}
我写的测试用例如下
it('should check if sData is called', () => {
const sData = spyOn<any>(component, 'sData');
component.rPage();
fixture.detectChanges();
expect(sData).toHaveBeenCalled();
});
已经在 beforeach 中的 rpage 上创建了 spy,如下所示
beforeEach(() => {
fixture = TestBed.createComponent(BasicComponent);
component = fixture.componentInstance;
spyOn(component, 'rPage');
fixture.detectChanges();
});
仍然在我 运行 测试时,测试用例失败并显示“预期间谍 sData 已被调用。” ,我哪里错了
您正在调用函数然后定义间谍,这就是导致问题的原因。您需要定义间谍然后调用函数。
试试下面
it('should check if sData is called', () => {
const toggleSpy = spyOn<any>(component, 'sData');
component.rPage();
fixture.detectChanges();
expect(toggleSpy).toHaveBeenCalled();
});
如果要确保调用sData
,则需要正确调用rPage
。通过在你的 beforeEach
中使用 spyOn(component, 'rPage');
,你有效地告诉你所有的测试永远不要 运行 rPage
真实的,并且只是模拟它。因此,它永远不会真正被调用,sData
真的永远不会被调用。
为了让您正确检查rPage
,您需要在测试它的测试中不使用间谍,或者将.and.callThrough()
添加到间谍中以实际调用函数
我正在学习用 jasmine 编写测试用例,我试图创建一个测试用例来检查函数中定义的函数是否被调用
我要测试的功能如下,sData方法写在另一个组件中,该组件正在被当前组件扩展
public rPage() {
this.sData();
this.setupPage()
}
我写的测试用例如下
it('should check if sData is called', () => {
const sData = spyOn<any>(component, 'sData');
component.rPage();
fixture.detectChanges();
expect(sData).toHaveBeenCalled();
});
已经在 beforeach 中的 rpage 上创建了 spy,如下所示
beforeEach(() => {
fixture = TestBed.createComponent(BasicComponent);
component = fixture.componentInstance;
spyOn(component, 'rPage');
fixture.detectChanges();
});
仍然在我 运行 测试时,测试用例失败并显示“预期间谍 sData 已被调用。” ,我哪里错了
您正在调用函数然后定义间谍,这就是导致问题的原因。您需要定义间谍然后调用函数。
试试下面
it('should check if sData is called', () => {
const toggleSpy = spyOn<any>(component, 'sData');
component.rPage();
fixture.detectChanges();
expect(toggleSpy).toHaveBeenCalled();
});
如果要确保调用sData
,则需要正确调用rPage
。通过在你的 beforeEach
中使用 spyOn(component, 'rPage');
,你有效地告诉你所有的测试永远不要 运行 rPage
真实的,并且只是模拟它。因此,它永远不会真正被调用,sData
真的永远不会被调用。
为了让您正确检查rPage
,您需要在测试它的测试中不使用间谍,或者将.and.callThrough()
添加到间谍中以实际调用函数