在Jasmine单元测试中模拟AngularJS模块依赖性 [英] Mocking AngularJS module dependencies in Jasmine unit tests

查看:80
本文介绍了在Jasmine单元测试中模拟AngularJS模块依赖性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在将其他模块作为依赖项的模块中对单元测试控制器代码进行单元化,但是还无法弄清楚如何正确模拟它们.

I'm attempting to unit test controller code inside a module that takes other modules as dependencies, but haven't been able to figure out how to mock them properly.

我正在使用Jasmine Framework,并使用Karma(Testacular)运行测试.

I'm using the Jasmine Framework and running my tests with Karma (Testacular).

模块代码

var app = angular.module('events', ['af.widgets', 'angular-table']);

app.controller('eventsCtrl', function([dependencies]){
    $scope.events = [];
    ...
});

规范代码

describe('events module', function(){
    var $scope,
        ctrl;

    beforeEach(function(){
        angular.mock.module('af.widgets', []);
        angular.mock.module('angular-table', []);
        module('events', ['af.widgets', 'angular-table']);
    });

    beforeEach(inject(function($rootScope, $controller){
        $scope = $rootScope.new();
        ctrl = $controller('NameCtrl', {
            $scope: $scope,
        });
    }));

    it('should have an empty events array', function(){
        expect($scope.events).toBe([]);
    })
});

我得到的错误是Karma是无模块af.widgets",因此显然我没有嘲笑模块依赖关系.有什么提示吗?

The error I'm getting is Karma is "no module af.widgets", so obviously I'm not mocking the module dependencies right. Any hints?

推荐答案

如果要模拟一个声明一个或多个服务的模块,我将使用以下代码:

If you want to mock a module that declare one or more services I have used this code:

beforeEach(function(){
    module('moduleToMock');
    module(function ($provide) {
        $provide.value('yourService', serviceMock);
    });
});

如果要模拟的服务也是要进行单元测试的服务(用另一个茉莉花描述),这将很有用. fscof提出的解决方案很好,但是您不能为angular-table模块创建单元测试.

This is useful if the service you want to mock is also a service that you want to unit test (in another jasmine describe). The solution proposed by fscof is fine but you cannot create a unit test for the angular-table module.

这篇关于在Jasmine单元测试中模拟AngularJS模块依赖性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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