如何在Angular 1.5组件中对函数进行单元测试
how to unit test a function inside Angular 1.5 component
我已经用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. 类型错误:无法读取未定义的属性"title"2. TypeError:无法读取未定义属性" navigate "
您的测试中有一些错误。
首先,你需要注入服务$componentController和$rootScope。之后,你需要使用$componentController服务实例化你的控制器:
let bindings = {$router: router};
$ctrl = $componentController('firstComponent', null, bindings);
然后你可以测试一些功能:
it("are things define properly", function() {
expect($ctrl).toBeDefined();
expect($ctrl.goToNextPage).toBeDefined();
});
要测试导航函数,你必须在路由器上创建一个间谍,执行函数$ctrl.goToNextPage()并在间谍上断言:
let routerSpy = spyOn(router, "navigate");
...//you must instantiate your controller here as shown above
$ctrl.goToNextPage();
expect(routerSpy).toHaveBeenCalled();
我已经更新了你的Plunker,你可以看到完整的代码:
https://plnkr.co/edit/TiuXM5?p =预览
相关文章:
- AngularJS指令单元测试中未定义的函数
- 如何在JavaScript中对箭头函数进行单元测试
- 在http服务单元测试中使用request-js时,chai.request不是一个函数
- 如何对调用getJSON的javascript函数进行单元测试
- AngluarJS单元测试-未定义不是函数
- 因果报应单元测试'未定义'不是函数错误
- 没有返回类型的函数的Javascript单元测试
- 在对揭示模块进行单元测试时,如何存根私有函数
- 如何对延迟函数执行单元测试
- jquery中的单元测试函数
- 如何使用 express、猫鼬和节点单元测试异步函数
- 对函数的参数(即函数)进行单元测试
- 连接到数据库的单元测试异步函数
- AngularJS私有函数单元测试混乱
- 模块中的单元测试函数
- 如何对传递给JavaScript函数的匿名回调进行单元测试
- $event.stopProposation不是Angularjs单元测试中的函数错误
- 在单元测试时,如何测试绑定函数的相等性
- 未定义不是函数:单元测试护照身份验证自定义回调
- 使用函数单元测试弹出窗口