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

查看:34
本文介绍了在 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 框架并使用 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);
    });
});

如果您要模拟的服务也是您要进行单元测试的服务(在另一个 jasmine 描述中),这将很有用.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天全站免登陆