我已经使用 Angular 1.5 组件创建了导航。但面临测试困难。我是 Angular 和单元测试的新手。 请在此 PLUNKER 上查找代码
这是我的组件。
module.component('firstComponent', {
templateUrl: "1.html",
bindings: {
"$router": "<"
},
controller: function($rootScope) {
var $ctrl = this;
$rootScope.title = "Title from Page 1";
$ctrl.goToNextPage = function() {
$ctrl.$router.navigate(["Second"]);
};
}
});
我正在尝试测试我的当前页面是否有正确的标题以及它是否导航到下一页。
这是我的 test-spec.js
describe("Check if component is defined", function() {
beforeEach(module("app"));
var $ctrl;
var router;
var $rootscope;
beforeEach(inject(function($componentController) {
$ctrl = $componentController("firstComponent", {
$router: router,
$rootscope: $rootscope
});
}));
it("are things define properly", function() {
expect($ctrl).toBeDefined();
expect($ctrl.goToNextPage).toBeDefined();
});
it("should have proper title", function() {
expect($rootscope.title).toBe("Title from Page 1");
});
it("should navigate to next page", function() {
expect($ctrl.router.navigate).toHaveBeenCalled();
});
});
这些是运行测试时遇到的错误:
3 个规范,2 个失败 1. TypeError: 无法读取未定义的属性'title' 2. 类型错误:无法读取未定义的属性“导航”
最佳答案
你的测试有一些错误。
首先,您需要注入(inject)服务 $componentController 和 $rootScope。
之后,您需要使用$componentController 服务实例化您的 Controller :
let bindings = {$router: router};
$ctrl = $componentController('firstComponent', null, bindings);
然后你可以测试一些功能:
it("are things define properly", function() {
expect($ctrl).toBeDefined();
expect($ctrl.goToNextPage).toBeDefined();
});
要测试导航功能,您必须在路由器上创建一个 spy ,执行函数 $ctrl.goToNextPage() 并在 spy 上断言:
let routerSpy = spyOn(router, "navigate");
...//you must instantiate your controller here as shown above
$ctrl.goToNextPage();
expect(routerSpy).toHaveBeenCalled();
我已经更新了您的 Plunker,您可以在其中看到完整的代码:
关于javascript - 如何对 Angular 1.5 组件中的函数进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39279485/