【发布时间】:2016-04-01 12:30:43
【问题描述】:
我目前正在用 mocha 测试一个控制器。控制器有一个激活函数,它应该根据响应触发成功/失败。我无法在测试期间触发失败或成功函数。
viewController.js:
(function() {
'use strict';
angular
.module('app')
.controller('viewCtrl', viewCtrl);
function viewCtrl(Service) {
vm.Service = Service;
activate();
function activate() {
vm.Service.get().then(success, failure);
function success(data) {
if (!data || data == 401) {
failure(data);
}
}
function failure(error) {
if (error) {
console.error("Loading question failed:", error);
vm.Service.set();
}
}
}
}
})();
viewControllerTest.js:
describe('question_view_controller', function() {
var httpBackend, controller;
var expect = chai.expect;
var assert = chai.assert;
var Service = {};
var createController;
beforeEach(function(){
angular.mock.module('ui.router');
angular.mock.module('question');
Service = {
set : sinon.stub(),
get : sinon.stub().returns(Promise.reject({error:{}}));
}
})
beforeEach(inject(function($httpBackend,$controller,$q){
httpBackend = $httpBackend;
createController = function(){
return $controller('ViewCtrl', {
$scope: scope,
Service: Service
});;
}
}));
afterEach(function(){
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
describe('activate', function () {
describe('get.then() error', function(){
beforeEach(function(){
Service.get.returns(Promise.reject({error:{}}))
})
it('should do nothing and setFailedQuestion should be called once', function(){
vm = createController();
scope.$digest();
expect(vm.Service.set.callCount).to.equal('1');
})
})
});
});
如果有人能指出我的错误或提供任何见解,那就太好了。有任何问题请追问。
更新: 编辑代码以反映 danday74 的答案。还是不行。
更新: 编辑代码以反映 danday74 的评论。还是不行。
【问题讨论】:
-
在你的viewControllerTest.js中
var QuestionService = {};应该是var Service = {};吗?否则,您在 beforeEach 中声明的“服务”可能与您在其他地方访问的“服务”不同...... -
是的,应该。现在将修复。
-
不抱歉仍然无法正常工作。
-
我认为这不是问题的原因,但您在 viewCtrl 中也缺少
var vm = this;... viewCtrl 代码是否真的有效(在测试之外)?
标签: javascript angularjs unit-testing mocha.js sinon