AngularJS - 如何测试一个函数是否从另一个函数中调用? [英] AngularJS - How to test if a function is called from within another function?
问题描述
我正在尝试开始使用 karma-jasmine,但我想知道为什么这个测试会失败:
I'm trying to get started with karma-jasmine and I'm wondering why this test fails:
it("should call fakeFunction", function() {
spyOn(controller, 'addNew');
spyOn(controller, 'fakeFunction');
controller.addNew();
expect(controller.fakeFunction).toHaveBeenCalled();
});
在我之前为此测试设置的控制器中,我有以下内容:
In my controller that I've previously set up for this test I have the following:
function addNew() {
fakeFunction(3);
}
function fakeFunction(number) {
return number;
}
addNew
和 fakeFunction
都使用:
vm.addNew = addNew;
vm.fakeFunction = fakeFunction;
但是,测试失败并显示以下内容:
The test, however, fails with the following:
预期的间谍 fakeFunction 已被调用.
如果我在测试中调用该函数,我可以使测试通过.但是,我希望可以测试 fakeFunction
是否被另一个函数调用.实现这一目标的正确方法是什么?
I can make the test pass if I call the function from within my test. I was hoping, however, I could test if fakeFunction
was called by another function. What is the proper way to achieve this?
更新:
//test.js
beforeEach(function() {
module("app");
inject(function(_$rootScope_, $controller) {
$scope = _$rootScope_.$new();
controller = $controller("CreateInvoiceController", {$scope: $scope});
});
});
如果我测试类似:
it('should say hello', function() {
expect(controller.message).toBe('Hello');
});
如果我将以下内容放入控制器中,则测试通过:
The test passes if I put the following in my controller:
var vm = this;
vm.message = 'Hello';
我只想知道如何测试公共函数是否被另一个函数调用.
I just want to know how I can test if a public function was called from another function.
推荐答案
你的 addNew
方法正在调用 fakeFunction
.但是,它没有调用 controller.fakeFunction
,这是您的期望.
Your addNew
method is calling fakeFunction
. However, it is not calling controller.fakeFunction
, which is what your expectation is.
您需要更改代码以使用您的控制器,而不是这些独立的功能.
You'll need to change your code to use your controller, rather than these independent functions.
EDIT:您还需要不要监视您的 addNew
函数.这导致该功能被间谍替换.另一种选择是将其更改为:
EDIT: You also need to not spy on your addNew
function. This is causing the function to be replaced with a spy. The other alternative is to change it to:
spyOn(controller, 'addNew').and.callThrough()
这篇关于AngularJS - 如何测试一个函数是否从另一个函数中调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!