我试图验证一个函数被点击链接后调用。在Jasmine测试中用jQuery调用点击,但看起来范围与测试中的控制器不同。在这种情况下我怎样才能使测试工作?有问题的代码可以在http://plnkr.co/edit/yqKme59WD9isrZTCutKB?p=preview找到。如何间谍控制器的功能,由用户界面点击的链接调用?
describe('Testing a Hello World controller', function() {
var $scope;
var ctrl;
//you need to indicate your module in a test
beforeEach(module('plunker'));
beforeEach(inject(function($rootScope, $controller) {
$scope = $rootScope.$new();
ctrl = $controller('MainCtrl as mc', {
$scope: $scope
});
spyOn(ctrl, 'loadData').and.callThrough();
}));
it('should call load data', function() {
ctrl.loadData();
console.log("1:" + ctrl.name);
expect(ctrl.loadData).toHaveBeenCalled();
});
it('should call load data after link cliked', function() {
$('#change-name')[0].click();
console.log("2:" + ctrl.name);
expect(ctrl.loadData).toHaveBeenCalled();
});
});
模板确实与控制器无关,所以我只是直接通过调用它来测试控制器功能。对于你的测试,假装模板不存在,只是测试控制器的API – Phil
这里是我的意思的例子〜http://plnkr.co/edit/4MsnnrWllcNdLBvqpKdr?p=preview – Phil
有没有办法弄到该模板使用的控制器或范围?我只希望我能验证由UI事件引起的这种状态变化。 – barryku