【问题标题】:Jasmine unit test asynchronous controller methodJasmine 单元测试异步控制器方法
【发布时间】:2014-08-21 06:24:04
【问题描述】:

我正在使用 Jasmine 对具有异步运行方法的 Angular 控制器进行单元测试。我能够成功地将依赖项注入控制器,但我不得不改变处理异步的方法,因为我的测试将在加载数据之前运行。我目前正在尝试监视模拟依赖项并使用andCallThrough(),但这会导致错误TypeError: undefined is not a function

这是我的控制器...

myApp.controller('myController', function($scope, users) {
    $scope.user = {};

    users.current.get().then(function(user) {
        $scope.user = user;
    });
}); 

还有我的 test.js...

describe('myController', function () {
    var scope, createController, mockUsers, deferred;
    beforeEach(module("myApp"));

    beforeEach(inject(function ($rootScope, $controller, $q) {
        mockUsers = {
            current: {
                get: function () {
                    deferred = $q.defer();
                    return deferred.promise;
                }
            }
        };
        spyOn(mockUsers.current, 'get').andCallThrough();

        scope = $rootScope.$new();
        createController = function () {
            return $controller('myController', {
                $scope: scope,
                users: mockUsers
            });
        };
    }));


    it('should work', function () {
        var ctrl = createController();          
        deferred.resolve('me');
        scope.$digest();
        expect(mockUsers.current.get).toHaveBeenCalled();
        expect(scope.user).toBe('me');           
    });
});

如果有更好的此类测试方法,请告诉我,谢谢。

【问题讨论】:

    标签: angularjs unit-testing asynchronous jasmine jasmine2.0


    【解决方案1】:

    试试

    spyOn(mockUsers.current, 'get').and.callThrough();
    

    取决于您使用的版本:在较新的版本上,并且CallThroungh() 在对象内部。 这里是文档http://jasmine.github.io/2.0/introduction.html

    【讨论】:

    • 啊,谢谢,我使用的是 2.0,我正在查看旧版本的示例
    猜你喜欢
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    相关资源
    最近更新 更多