AngularJS - 如何测试如果一个函数从另一个函数中调用? [英] AngularJS - How to test if a function is called from within another function?

查看:369
本文介绍了AngularJS - 如何测试如果一个函数从另一个函数中调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想开始使用卡玛 - 茉莉,我不知道为什么这个测试失败:

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();
});

在我的控制器,我已经previously设立这个测试我有以下几点:

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});

    });

});

如果我的测试是这样的:

If I test something like:

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.

您将需要更改code使用控制器,而不是这些独立的功能。

You'll need to change your code to use your controller, rather than these independent functions.

修改:您还需要在没有你的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆