【问题标题】:unit testing angular service, beforeEach inject doesn't execute单元测试角度服务,beforeEach 注入不执行
【发布时间】:2017-06-13 07:13:16
【问题描述】:

我正在尝试使用 jasmine/karma 为 Angular 服务编写单元测试。我有一个类似的服务测试,效果很好。但是这个有一些额外的依赖,在不同的模块中,只是没有找到注入的服务。

服务看起来像这样。 bService 在同一个模块中,但 commonFactorycommonService 在另一个模块中,比如 commonModule

(function () {
    'use strict';
     angular
         .module('myService')
         .service('aService', aService);

     aService.$inject = [
         'commonFactory',
         'commonService'
         'bService'
     ];

     function aService (
         commonFactory,
         commonService,
         bService
     ) {

     };

     return {
         codeIWantToTest: CodeIWantToTest;
     }

     function CodeIWantToTest () {
          console.log('surprise!');
     }
})();

我的茉莉花测试看起来像:

describe('myService.aService', function () {
    'use strict';
    var aService;
    // I tried adding beforeEach(module('commonModule')); too, but that didn't do anything
    beforeEach(module('myService'));

    beforeEach(function() {
        inject(function(_aService_) {
            console.log('getting aService');
            aService = _aService_;
        });
    }); 

    it('tests my service is defined', function() {
        expect(myService).toBeDefined();
    });
});

此测试失败。 myService 未定义,并且注入函数中的 console.log 永远不会触发。我的karma.conf.js 基本上按照它们被注入服务的顺序列出了依赖项,然后添加服务然后测试。

什么会导致注入无法获取服务?我错过了什么?我提到我对commonService 进行了类似的测试,它工作得很好。所以我很困惑。

【问题讨论】:

  • 您通常不会测试服务,而是在控制器中测试服务的结果。
  • 已编辑代码,在bService 上添加了缺少的'。万一这不是复制到 SO 的问题。
  • 它也缺少aService =_aService_ 末尾的_
  • @MatthewGreen 您通常不会像这样测试它们吗?这是否意味着它不起作用?我需要在更高的层次上做吗?
  • @MatthewGreen 你是从哪里得到这个的?实际上恰恰相反;在单元测试中,您单独测试单独的单元,因此活动部件较少,红色测试明确指示哪个单元失败。因此名称为单元测试。

标签: angularjs unit-testing jasmine karma-runner


【解决方案1】:

我团队的另一位开发人员找到了解决方案,我想将其发布为未来人们的答案。我有一种感觉,这是一个依赖问题,而且确实如此。当我们正确加载所有 JS 内容时,组件使用的模板正在加载另一个 js 依赖项。所以要为茉莉花解决这个问题,我们有两种不同的解决方案:

在组件测试文件的顶部,我们可以添加:

beforeEach(function () {
    module(function ($provide) {
        $provide.constant('myMissingDependency', {
            // do things to load the dependency here
            });
    });
});

在我们的例子中,它是一个翻译库

另一种解决方案是在单元测试目录中添加一个“shim”文件,并在测试之前使用 karma.config.js 加载它。看起来像:

(function() {
    angular
        .module('MyService')
        .constant('myMissingDependency', Object.freeze({
            // things to load the dependency
        }));
})();

我无法切换到 Chrome,因为我们使用的是 Docker,而且我无法让测试在本地运行以运行 Chrome。因此,我需要为此添加第二双眼睛。

【讨论】:

    猜你喜欢
    • 2018-03-15
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 2020-07-10
    • 2017-09-17
    相关资源
    最近更新 更多