我正在用AngularJs 1.4.4编写一个应用程序,并且刚刚开始使用TDD。我在Jasmine中使用Karma,并且没有在$ scope上测试表达式的麻烦,但是当试图在Controller中测试使用'this'定义的表达式时,它将返回为undefined。 Angular表示在你的控制器中使用'this'是最好的练习,但我还没有找到一个明确的测试例子。AngularJs单元测试'这''
这里是我的控制器
'user_strict';
var app = angular.module('app', ['ngRoute', 'ngAnimate']);
angular.module('app')
app.controller('LoginCtrl', ['$scope', function($scope) {
var login = this;
login.user = {message:'hello'};
$scope.userName = "Anthony";
}])
我的测试脚本
'use strict';
describe('Controller: LoginCtrl', function() {
\t
\t // load the controller's module
\t beforeEach(module('app'));
\t var LoginCtrl,
\t scope;
\t // initalize the controller and a mock scope
\t beforeEach(inject(function ($controller, $rootScope) {
\t \t scope = $rootScope.$new();
\t \t LoginCtrl = $controller('LoginCtrl', {
\t \t \t $scope: scope,
\t \t });
\t }));
\t it('should equal to equal to Anthony', function() {
\t \t expect(scope.userName).toBe("Anthony");
\t });
\t it('login user should equal to hello', function() {
\t \t expect(login.user.message).toBe('hello');
\t })
});
第一个测试通过,但塞康d返回这个错误/失败;
控制器:LoginCtrl登录用户应该等于为hello FAILED
类型错误: '未定义' 不是(评价 'login.user.message')的对象
我的假设是,它需要像控制器和范围注入,但我试过的方法没有奏效。任何帮助非常感谢:)
谢谢,完美的作品!但是AngularJs的例子没有显示这一点。你有什么想法,为什么? –
哪个AngularJs例子?没有得到问题。 –
查看本页面上的控制器和范围部分; https://google-styleguide.googlecode.com/svn/trunk/angularjs-google-style.html –