我有一个角度模块,它使用了角度ui bootstrap typeahead指令。我试图用qunit和chutzpah进行单元测试。
单元测试在浏览器运行时运行并通过,但在使用Chutzpah运行时返回错误:
错误:错误:[$ injector:modulerr]无法实例化模块myApp 由于:错误:[$ injector:nomod]模块'myApp'不可用!您 要么错误拼写模块名称,要么忘记加载它。如果注册 模块确保您将依赖项指定为第二个 参数。
为什么会出现此错误?
JS
(function () {
var app = angular.module('myApp', ['ui.bootstrap']);
app.factory('myFactory', ['$http', function ($http) {
var myFactory = {};
myFactory.getLocations = function (query) {
return $http.get('/Locations', { params: { query: query } });
};
return myFactory;
}]);
app.controller('MyController', ['myFactory', function (myFactory) {
this.location = '';
this.getLocations = function (query) {
return myFactory.getLocations(query).then(function (response) {
return response.data;
});
};
}]);
})();
HTML
<div data-ng-app="myApp" data-ng-controller="MyController as my">
<input name="location" type="text" data-ng-model="my.location" data-typeahead="location for location in my.getLocations($viewValue)" class="form-control">
</div>
单元测试
///<reference path="angular.js"/>
///<reference path="angular-mocks.js"/>
///<reference path="angular-ui/ui-bootstrap-tpls.js"/>
///<reference path="qunit-1.15.0.js"/>
///<reference path="sinon-1.9.1.js"/>
///<reference path="myapp.js"/>
var appMocks = angular.module("appMocks", []);
appMocks.config(function ($provide) {
$provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
});
var injector = angular.injector(['ng', 'myApp', 'appMocks']);
var scope = {};
var $controllers = injector.get('$controller');
var $httpBackend = injector.get('$httpBackend');
var myFactory = injector.get('myFactory');
QUnit.module("MyApp Tests", {
setup: function () {
scope = injector.get('$rootScope').$new();
$controllers('MyController as my', {
$scope: scope,
myFactory: myFactory
});
}
});
QUnit.test('Get locations returns valid locations', function (assert) {
$httpBackend.expectGET('/Locations?query=l').respond(['london', 'leeds']);
var result;
scope.my.getLocations('l').then(function (response) {
result = response;
});
$httpBackend.flush();
assert.equal(2, result.length, "correct number of results returned");
});
Chutzpah设置
{
"Framework": "qunit",
"CodeCoverageIncludes": ["*.js"],
"CodeCoverageExcludes": [
"*\\sinon-1.9.1.js",
"*\\angular.js",
"*\\angular-mocks.js",
"*\\angular-ui/ui-bootstrap-tpls.js",
"*\\Tests\\*"
],
"RootReferencePathMode":"SettingsFileDirectory",
"TestHarnessDirectory": "./"
}
答案 0 :(得分:2)
问题是.js加载顺序之一。当您使用代码覆盖率运行时,blanket.js插件将检测您的文件并导致它们异步加载。由于您从测试中排除了测试文件,因此它在源文件之前加载它。要更改此功能,只需删除&#34; \ test-js \ &#34;即可对测试文件进行检测。来自您的coverageexcludes部分:
{
"Framework": "qunit",
"CodeCoverageIncludes": ["*.js"],
"CodeCoverageExcludes": [
"*\\angular/angular.js",
"*\\angular/angular-mocks.js",
"*\\angular-ui/ui-bootstrap-tpls.js",
"*\\qunit/qunit-1.15.0.js",
"*\\sinon/sinon-1.9.1.js"
],
"RootReferencePathMode":"SettingsFileDirectory",
"TestHarnessDirectory": "./"
}