0
我的單元測試工作出現問題。 在broswer我的指令很好,但是當我測試它時,我有一個失敗測試。 這裏的代碼:對角度指令的單元測試不考慮對元素的更改
angular.module('helloWorldApp')
.directive('helloworld', function() {
var helloworld = {};
class Hello {
constructor(name) {
this.name = name ;
}
SayHello() {
//console.log('Hello ' + this.name);
return 'Hello ' + this.name;
}
};
helloworld.template = '<label for="name">Your Name </label> <input type="text" name="name" ng-model="name"/><br/><div id="result"></div>';
helloworld.restrict = 'E';
helloworld.link = (scope,element,attrs) => {
scope.$watch('name',() => {
if (scope.name) {
let HelloMe = new Hello(scope.name);
let helloStr = HelloMe.SayHello();
element.find('#result').text(helloStr);
console.log(element.find('#result').text());
};
});
};
return helloworld;
});
這裏測試:
'use strict';
describe('Directive: helloworld', function() {
// load the directive's module
beforeEach(module('helloWorldApp'));
var element,
scope;
beforeEach(inject(function ($compile, $rootScope) {
scope = $rootScope.$new();
element = angular.element('<helloworld></helloworld>');
element = $compile(element)(scope);
}));
describe('Test', function() {
it('Hello Lola', inject(function ($compile) {
var inputElt = element.find('input');
console.log(scope.name);
inputElt.val('Lola');
inputElt.triggerHandler('input');
element = $compile(element)(scope);
scope.$digest();
console.log(scope.name);
expect(scope.name).toBeDefined();
expect(element.find('input').val()).toBe('Lola');
expect(element.find('#result').text()).toBe('Hello Lola');
}));
});
});
據我所知,在單元測試有比在broswer一些差異。但$watch
確實在我的測試中觸發,但它不會改變結果div。
謝謝您的解釋。
編輯:失敗測試的答案
LOG: undefined
LOG: ''
LOG: ''
LOG: 'Lola'
Chrome 38.0.2125 (Windows 7) Jasmine__TopLevel_
Hello Lola FAILED
Expected '' to be 'Hello Lola'.
Error: Expected '' to be 'Hello Lola'.