我正在尝试在 AngularJS 中为 $modal 编写单元测试。模态的代码位于控制器中,如下所示:
$scope.showProfile = function(user){
var modalInstance = $modal.open({
templateUrl:"components/profile/profile.html",
resolve:{
user:function(){return user;}
},
controller:function($scope,$modalInstance,user){$scope.user=user;}
});
};
该函数在 HTML 中的 ng-repeat 中的按钮上调用,如下所示:
<button class='btn btn-info' showProfile(user)'>See Profile</button>
正如您所看到的,用户被传入并在模式中使用,然后数据将绑定到其 HTML 中的配置文件部分。
我正在使用 Karma-Mocha 和 Karma-Sinon 来尝试执行单元测试,但我不明白如何实现这一点,我想验证传入的用户是否与模式的解析参数中使用的用户相同。
我已经看到了一些如何使用 Jasmine 执行此操作的示例,但我无法将它们转换为 mocha + sinon 测试。
这是我的尝试:
设置代码:
describe('Unit: ProfileController Test Suite,', function(){
beforeEach(module('myApp'));
var $controller, modalSpy, modal, fakeModal;
fakeModal = {// Create a mock object using spies
result: {
then: function (confirmCallback, cancelCallback) {
//Store the callbacks for later when the user clicks on the OK or Cancel button of the dialog
this.confirmCallBack = confirmCallback;
this.cancelCallback = cancelCallback;
}
},
close: function (item) {
//The user clicked OK on the modal dialog, call the stored confirm callback with the selected item
this.result.confirmCallBack(item);
},
dismiss: function (type) {
//The user clicked cancel on the modal dialog, call the stored cancel callback
this.result.cancelCallback(type);
}
};
var modalOptions = {
templateUrl:"components/profile/profile.html",
resolve:{
agent:sinon.match.any //No idea if this is correct, trying to match jasmine.any(Function)
},
controller:function($scope,$modalInstance,user){$scope.user=user;}
};
var actualOptions;
beforeEach(inject(function(_$controller_, _$modal_){
// The injector unwraps the underscores (_) from around the parameter names when matching
$controller = _$controller_;
modal = _$modal_;
modalSpy = sinon.stub(modal, "open");
modalSpy.yield(function(options){ //Doesn't seem to be correct, trying to match Jasmines callFake function but get this error - open cannot yield since it was not yet invoked.
actualOptions = options;
return fakeModal;
});
}));
var $scope, controller;
beforeEach(function() {
$scope = {};
controller = $controller('profileController', {
$scope: $scope,
$modal: modal
});
});
afterEach(function () {
modal.open.restore();
});
实际测试:
describe.only('display a user profile', function () {
it('user details should match those passed in', function(){
var user= { name : "test"};
$scope.showProfile(user);
expect(modalSpy.open.calledWith(modalOptions)).to.equal(true); //Always called with empty
expect(modalSpy.open.resolve.user()).to.equal(user); //undefined error - cannot read property resolve of undefined
});
});
我的测试设置和实际测试基于我遇到的 Jasmine 代码并尝试将其转换为 Mocha + SinonJS 代码,我对 AngularJS 和编写单元测试都是新手,所以我希望我只需要朝着正确的方向轻推.
任何人都可以分享使用 Mocha + SinonJS 而不是 Jasmine 时采取的正确方法吗?