在单元测试中模拟Angular 1.5组件

时间:2016-03-17 10:45:00

标签: angularjs unit-testing

我有一个基本的角度1.5组件,如下所示:

angular
  .module('app')
  .component('techs', {
    templateUrl: 'app/techs/techs.html',
    controller: TechsController
  });

我想模拟仅此组件而不是整个应用,因为angular.mock.module('app')会模仿应用的每个组件。有办法吗?
我试过了angular.mock.module('techs'),但发生了这个错误:

Failed to instantiate module techs due to:
Module 'techs' is not available! You either misspelled the module name or forgot to load it

2 个答案:

答案 0 :(得分:1)

你应该通过$ componentController注入组件。

Forex: component = $componentController('Component', {yourscope}, {yourbindings});

答案 1 :(得分:-1)

我发现在我的角度模块定义中至少有一层或两层嵌套有助于测试它们。例如,您可以这样做:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div class="normalize">
    <div class="normalize-item">
        <span> Item 1.1 <br><br><br><br></span>
    </div>
    <div class="normalize-item">
        <span>
      Item 1.2
    </span>
        <div class="normalize">
            <div class="normalize-item">
                <span> Item 2.1 </span>
            </div>
            <div class="normalize-item">
                <span> Item 2.2 </span>
            </div>
        </div>
    </div>
    <div class="normalize-item">
        <span> Item 1.3 </span>
    </div>
    <div class="normalize-item">
        <span> Item 1.4 </span>
    </div>
</div>

这样就可以让你不要强调全局名称空间污染以及你担心的潜在无意识。

虽然,我意识到这并不能直接回答你的问题。回到你的例子一下:

angular.module('app.ui')
    .component('techs', {
        templateUrl: 'app/techs/techs.html',
        controller: TechsController
    });

如果你是真正的单元测试,那么理论上 - 你只会自己加载这个文件(而不是

相关问题