unit-testing - SpyOn 返回预期是 spy ,但得到了函数

标签 unit-testing service controller karma-runner spyon

我正在测试一个调用服务(通过 goToPage 函数)的 Controller ,以便使用 spy 进行重定向。这很简单,但我收到“预期是 spy ,但得到了功能”。错误。我究竟做错了什么? 这是我的规范:

var createController,service scope;
beforeEach(inject(function($rootScope, $controller,$injector){
    service = $injector.get('service ');
    scope = $rootScope.$new();
    createController = function() {
        return $controller('controller', {
            '$scope': scope
        });
        spyOn(service , ['redirect']).andCallThrough();
    };
}));

describe('test if service is called', function() {
    it('should call the service', function() {
        var controller=createController();
        scope.goToPage();
        expect(service.redirect).toHaveBeenCalled();
    });
});

});

最佳答案

首先,您在调用 return 后定义了 spy ,因此该代码永远不会运行。其次,在测试中定义您的 spy ,而不是在 beforeEach 中。

var createController,service scope;
beforeEach(inject(function($rootScope, $controller,$injector){
    service = $injector.get('service ');
    scope = $rootScope.$new();
    createController = function() {
        return $controller('controller', {
            '$scope': scope
        });    
    };
}));

describe('test if service is called', function() {
    it('should call the service', function() {
        var controller=createController();
        spyOn(service , ['redirect']).andCallThrough();
        scope.goToPage();
        expect(service.redirect).toHaveBeenCalled();
    });
});

关于unit-testing - SpyOn 返回预期是 spy ,但得到了函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33374812/

相关文章:

angularjs - 测试使用数据表的 Angular Controller - 模拟 DTOptionsBuilder 和 DT ColumnBuilder

node.js - 在 Node.js 中模拟模块以进行单元测试

unit-testing - 当我取消单元测试运行时,当前运行的测试是否完成?

c# - 如何伪造/单元测试Azure存储队列?

java - 在方法返回后运行 Java 代码?

mysql - EasyAdmin 3.1 CrudControllers Symfony

javascript - 如何在 Angular js 中将值传递给不同的 Controller

php - CodeIgniter Helper Functions 可以使用数据库函数吗?

android - 如何在 Android 服务中启动没有标志 FLAG_ACTIVITY_NEW_TASK 的 Intent ?

java - 如何知道我的 Activity 是否在服务中被破坏?