【问题标题】:karma/jasmine/angular toHaveBeenCalledWith is really called业力/茉莉花/角度 toHaveBeenCalledWith 真的被称为
【发布时间】:2014-08-17 23:50:36
【问题描述】:

以我的应用为例,我有

$rootScope.$emit('loggedin',data.user);
$rootScope.$on('loggedin', function(event,user) {
    console.log('called');           
});

在我的测试中

spyOn($rootScope, '$emit');

var response = {
    "success":1,
    "user":{
        "id":1,
        "email":"lama@test.test",
        "fullname":"Lama user",
        "username":"lamauser",
        "groups":["Users"]
    },
    "logged":1
};
$httpBackend.when('POST', '/api/v1/user').respond(200,response);
$scope.save();
$httpBackend.flush();
expect($scope.errors.length).toEqual(0);
expect($rootScope.$emit).toHaveBeenCalledWith('loggedin',response.user);

应用程序和测试都运行良好 但在测试中我从来没有看到控制台消息 叫

所以我想知道在测试期间是否从未触发 $on 或者我错过了什么。

【问题讨论】:

    标签: angularjs jasmine karma-runner karma-jasmine angular-mock


    【解决方案1】:

    如果您想调用真正的$emit(),则必须在spyOn 之后显式设置它,如下所示:

    spyOn($rootScope, '$emit').and.callThrough();
    

    或者在 Jasmine 1.3 中:

    spyOn($rootScope, '$emit').andCallThrough();
    

    希望这会有所帮助。

    【讨论】:

    • 我刚刚尝试过 .andCallThrough();但我一直看不到“叫”
    • 嗯,似乎存在 $rootScope 问题,因为如果我将 $on 侦听器放在运行块中,它就可以工作
    • 你的$emit 和$on 真的是这个顺序吗?如果是,这就是原因,您试图在订阅之前发出一个事件。尝试将$on 移动到$emit 之前。
    • 我在单独的控制器中有 $on,控制器中的 $emit 附加到路由。我不明白为什么它在应用程序中而不是在测试中有效
    • 您的separate controller 似乎没有在测试中初始化。如果你想测试它,你必须以某种方式让它被初始化。
    猜你喜欢
    • 2014-12-12
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    相关资源
    最近更新 更多