我正在尝试为 Angular 1.5 构建基本的单元测试,目的是 A) 练习单元测试,以及 B) 熟悉 Angular 1.5.x 中基于组件的开发。我正在尝试对一个简单的组件进行单元测试,但我不断收到以下消息:
错误: [$injector:modulerr] 由于以下原因,无法实例化模块应用:
错误: [$injector:模块rr] 无法实例化模块 ngComponentRouter 由于:
错误: [$injector:nomod] 模块 "ng组件路由器"不可用!您要么拼错了模块 名称或忘记加载它。如果注册模块,请确保 将依赖项指定为第二个参数。
我想就如何将此特定依赖项/模块注入单元测试提供一些指导。这是我的代码:
应用.js
(function(){
"use strict";
const app = angular.module("app", ["ngComponentRouter"])
app.value("$routerRootComponent", "componentApp");
})();
component-app.component.js
(function(){
"use strict";
angular.module("app").component("componentApp", {
templateUrl: "/javascripts/component-app.component.html",
controller: ["$router", function($router){
$router.config([
{ path: "/users", component: "usersComponent", name: "Users" },
{ path: "/**", redirectTo: ["Users"]}
]);
}]
});
})();
component-app.component.spec.js
describe("componentApp component", function(){
beforeEach(module("app"));
var $componentController, componentApp;
beforeEach(inject(function($injector){
$componentController = $injector.get("$componentController");
componentApp = $componentController("componentApp", { $scope: {}});
}));
it("componentApp component is defined", function(){
expect(componentApp).toBeDefined();
});
});
所以有两个更改可以解决问题,首先我需要更改组件-app.component.js:
angular.module("app").component("componentApp", {
templateUrl: "/templates/component-app.component.html",
$routeConfig: [
{ path: "/Users", name: "Users", component: "usersComponent" },
{ path: "/Home", name: "Home", component: "homeComponent"},
{ path: "/Profile/:id", name: "Profile", component: "profileComponent" },
{ path: "/**", redirectTo: ["Users"]}
]
});
我需要将该文件包含在 karma.conf 中.js:
module.exports = function(config) {
config.set({
basePath: "",
frameworks: ["jasmine"],
files: [
"bower_components/angular/angular.js",
"bower_components/angular-mocks/angular-mocks.js",
"bower_components/angular-component-router/angular_1_router.js",
"javascripts/**/*.js"
],
exclude: [
],
preprocessors: {
},
reporters: ["progress"],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ["Chrome"],
singleRun: false,
concurrency: Infinity
});
};